Ë
    S^(hw5  ã                   ó¨   — d Z ddlZddlZddlmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ d	d
lmZ  ej"                  e«      Z G d„ de
«      ZdgZy)z
Processor class for Bark
é    N)ÚOptionalé   )ÚBatchFeature)ÚProcessorMixin)Úlogging)Úcached_fileé   )ÚAutoTokenizerc                   ó¤   ‡ — e Zd ZdZdZdgZddddœZdˆ fd„	Ze	 dd„«       Z		 	 	 dd	e
fˆ fd
„Zddee   fd„Zddee   fd„Z	 	 	 	 	 	 	 dd„Zˆ xZS )ÚBarkProcessora	  
    Constructs a Bark processor which wraps a text tokenizer and optional Bark voice presets into a single processor.

    Args:
        tokenizer ([`PreTrainedTokenizer`]):
            An instance of [`PreTrainedTokenizer`].
        speaker_embeddings (`Dict[Dict[str]]`, *optional*):
            Optional nested speaker embeddings dictionary. The first level contains voice preset names (e.g
            `"en_speaker_4"`). The second level contains `"semantic_prompt"`, `"coarse_prompt"` and `"fine_prompt"`
            embeddings. The values correspond to the path of the corresponding `np.ndarray`. See
            [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c) for
            a list of `voice_preset_names`.

    r
   Ú	tokenizeré   r	   ©Úsemantic_promptÚcoarse_promptÚfine_promptc                 ó2   •— t         ‰| �  |«       || _        y ©N)ÚsuperÚ__init__Úspeaker_embeddings)Úselfr   r   Ú	__class__s      €úf/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/bark/processing_bark.pyr   zBarkProcessor.__init__<   s   ø€ Ü‰Ñ˜Ô#à"4ˆÕó    c                 ó^  — |�þt        |||j                  dd«      |j                  dd«      |j                  dd«      |j                  dd«      |j                  dd«      |j                  dd«      |j                  d	d«      |j                  d
d«      ddd¬«      }|€:t        j                  dt        j
                  j                  ||«      › d�«       d}n,t        |«      5 }t        j                  |«      }ddd«       nd}t        j                  |fi |¤Ž} | |¬«      S # 1 sw Y   Œ)xY w)aÛ  
        Instantiate a Bark processor associated with a pretrained model.

        Args:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                This can be either:

                - a string, the *model id* of a pretrained [`BarkProcessor`] hosted inside a model repo on
                  huggingface.co.
                - a path to a *directory* containing a processor saved using the [`~BarkProcessor.save_pretrained`]
                  method, e.g., `./my_model_directory/`.
            speaker_embeddings_dict_path (`str`, *optional*, defaults to `"speaker_embeddings_path.json"`):
                The name of the `.json` file containing the speaker_embeddings dictionary located in
                `pretrained_model_name_or_path`. If `None`, no speaker_embeddings is loaded.
            **kwargs
                Additional keyword arguments passed along to both
                [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`].
        NÚ	subfolderÚ	cache_dirÚforce_downloadFÚproxiesÚresume_downloadÚlocal_files_onlyÚuse_auth_tokenÚrevision©r   r   r   r    r!   r"   Útokenr$   Ú _raise_exceptions_for_gated_repoÚ%_raise_exceptions_for_missing_entriesÚ'_raise_exceptions_for_connection_errorsú`zã` does not exists
                    , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json
                    dictionary if wanted, otherwise set `speaker_embeddings_dict_path=None`.)r   r   )r   ÚpopÚloggerÚwarningÚosÚpathÚjoinÚopenÚjsonÚloadr
   Úfrom_pretrained)ÚclsÚ!pretrained_processor_name_or_pathÚspeaker_embeddings_dict_pathÚkwargsÚspeaker_embeddings_pathr   Úspeaker_embeddings_jsonr   s           r   r4   zBarkProcessor.from_pretrainedA   sB  € ð. (Ð3Ü&1Ø1Ø,Ø Ÿ*™* [°$Ó7Ø Ÿ*™* [°$Ó7Ø%Ÿz™zÐ*:¸EÓBØŸ
™
 9¨dÓ3Ø &§
¡
Ð+<¸dÓ CØ!'§¡Ð,>ÀÓ!FØ—j‘jÐ!1°4Ó8ØŸ™ J°Ó5Ø16Ø6;Ø8=ô'Ð#ð 'Ð.Ü—‘Øœ"Ÿ'™'Ÿ,™,Ð'HÐJfÓgÐhð i]ð `ôð
 &*Ñ"äÐ1Ó2ð LÐ6MÜ)-¯©Ð3JÓ)KÐ&÷Lð Lð "&Ðä!×1Ñ1Ð2SÑ^ÐW]Ñ^ˆ	á˜YÐ;MÔNÐN÷Lð Lús   Ã"D#Ä#D,Úpush_to_hubc                 óÂ  •— | j                   ��4t        j                  t        j                  j	                  ||d«      d¬«       i }||d<   | j                   D ]Ÿ  }|dk7  sŒ	| j                  |«      }i }	| j                   |   D ]m  }
t        j                  t        j                  j	                  |d   ||› d|
› �«      ||
   d¬«       t        j                  j	                  ||› d|
› d	�«      |	|
<   Œo |	||<   Œ¡ t        t        j                  j	                  ||«      d
«      5 }t        j                  ||«       ddd«       t        ‰| �0  ||fi |¤Ž y# 1 sw Y   ŒxY w)a|  
        Saves the attributes of this processor (tokenizer...) in the specified directory so that it can be reloaded
        using the [`~BarkProcessor.from_pretrained`] method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the tokenizer files and the speaker embeddings will be saved (directory will be created
                if it does not exist).
            speaker_embeddings_dict_path (`str`, *optional*, defaults to `"speaker_embeddings_path.json"`):
                The name of the `.json` file that will contains the speaker_embeddings nested path dictionary, if it
                exists, and that will be located in `pretrained_model_name_or_path/speaker_embeddings_directory`.
            speaker_embeddings_directory (`str`, *optional*, defaults to `"speaker_embeddings/"`):
                The name of the folder in which the speaker_embeddings arrays will be saved.
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs:
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        NÚv2T)Úexist_okÚrepo_or_pathÚ_F)Úallow_picklez.npyÚw)r   r.   Úmakedirsr/   r0   Ú_load_voice_presetÚnpÚsaver1   r2   Údumpr   Úsave_pretrained)r   Úsave_directoryr7   Úspeaker_embeddings_directoryr;   r8   Úembeddings_dictÚ
prompt_keyÚvoice_presetÚtmp_dictÚkeyÚfpr   s               €r   rH   zBarkProcessor.save_pretrainedy   si  ø€ ð8 ×"Ñ"Ñ.Ü�K‰KœŸ™Ÿ™ ^Ð5QÐSWÓXÐcgÕhà ˆOà.<ˆO˜NÑ+à"×5Ñ5ò ;�
Ø Ó/Ø#'×#:Ñ#:¸:Ó#F�Là!�HØ#×6Ñ6°zÑBò n˜ÜŸ™ÜŸG™GŸL™LØ /°Ñ ?ÐA]ÐblÐamÐmnÐorÐnsÐ_tóð )¨Ñ-Ø).õô )+¯©¯©Ð5QÐV`ÐUaÐabÐcfÐbgÐgkÐSlÓ(m˜ šðnð 3;�O JÒ/ð;ô" ”b—g‘g—l‘l >Ð3OÓPÐRUÓVð /ÐZ\Ü—	‘	˜/¨2Ô.÷/ô 	‰Ñ °ÑF¸vÓF÷/ð /ús   Ä$EÅErM   c                 óž  — | j                   |   }i }dD �]5  }||vrt        d|› d|› d�«      ‚t        | j                   j                  dd«      ||   |j	                  dd «      |j	                  dd «      |j	                  d	d
«      |j	                  dd «      |j	                  dd «      |j	                  dd
«      |j	                  dd «      |j	                  dd «      d
d
d
¬«      }|€Mt        dt
        j                  j                  | j                   j                  dd«      ||   «      › d|› d�«      ‚t        j                  |«      ||<   �Œ8 |S )Nr   ú#Voice preset unrecognized, missing z% as a key in self.speaker_embeddings[z].r?   ú/r   r   r   Fr    r!   r"   r#   r$   r%   r*   z{` does not exists
                    , no preloaded voice preset will be used - Make sure to provide correct paths to the z 
                    embeddings.)
r   Ú
ValueErrorr   Úgetr+   r.   r/   r0   rE   r3   )r   rM   r8   Úvoice_preset_pathsÚvoice_preset_dictrO   r/   s          r   rD   z BarkProcessor._load_voice_preset²   sv  € Ø!×4Ñ4°\ÑBÐàÐØFó 	3ˆCØÐ,Ñ,Ü Ø9¸#¸Ð>cÐdpÐcqÐqsÐtóð ô Ø×'Ñ'×+Ñ+¨N¸CÓ@Ø" 3Ñ'Ø Ÿ*™* [°$Ó7Ø Ÿ*™* [°$Ó7Ø%Ÿz™zÐ*:¸EÓBØŸ
™
 9¨dÓ3Ø &§
¡
Ð+<¸dÓ CØ!'§¡Ð,>ÀÓ!FØ—j‘jÐ!1°4Ó8ØŸ™ J°Ó5Ø16Ø6;Ø8=ôˆDð ˆ|Ü Øœ"Ÿ'™'Ÿ,™, t×'>Ñ'>×'BÑ'BÀ>ÐSVÓ'WÐYkÐloÑYpÓqÐrð sjØjvÐiwð x ð#óð ô &(§W¡W¨T£]Ð˜cÓ"ð9	3ð< !Ð r   c           	      ó^  — dD ]¨  }||vrt        d|› d�«      ‚t        ||   t        j                  «      s't	        |› dt        | j                  |   «      › d�«      ‚t        ||   j                  «      | j                  |   k7  sŒƒt        |› dt        | j                  |   «      › d�«      ‚ y )Nr   rR   z
 as a key.z voice preset must be a z
D ndarray.)	rT   Ú
isinstancerE   ÚndarrayÚ	TypeErrorÚstrÚpreset_shapeÚlenÚshape)r   rM   rO   s      r   Ú_validate_voice_preset_dictz)BarkProcessor._validate_voice_preset_dictÖ   s¾   € ØFò 	jˆCØ˜,Ñ&Ü Ð#FÀsÀeÈ:Ð!VÓWÐWä˜l¨3Ñ/´·±Ô<Ü 3 %Ð'?ÄÀD×DUÑDUÐVYÑDZÓ@[Ð?\Ð\fÐ gÓhÐhä�< Ñ$×*Ñ*Ó+¨t×/@Ñ/@ÀÑ/EÓEÜ  C 5Ð(@ÄÀT×EVÑEVÐWZÑE[ÓA\Ð@]Ð]gÐ!hÓiÐiñ	jr   c           
      óž  — |�‡t        |t        «      swt        |t        «      r,| j                  � || j                  v r| j	                  |«      }n;t        |t        «      r|j                  d«      s|dz   }t        j                  |«      }|�  | j                  |fi |¤Ž t        ||¬«      } | j                  |f|d||||dœ|¤Ž}	|�||	d<   |	S )aÖ  
        Main method to prepare for the model one or several sequences(s). This method forwards the `text` and `kwargs`
        arguments to the AutoTokenizer's [`~AutoTokenizer.__call__`] to encode the text. The method also proposes a
        voice preset which is a dictionary of arrays that conditions `Bark`'s output. `kwargs` arguments are forwarded
        to the tokenizer and to `cached_file` method if `voice_preset` is a valid filename.

        Args:
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
            voice_preset (`str`, `Dict[np.ndarray]`):
                The voice preset, i.e the speaker embeddings. It can either be a valid voice_preset name, e.g
                `"en_speaker_1"`, or directly a dictionary of `np.ndarray` embeddings for each submodel of `Bark`. Or
                it can be a valid file name of a local `.npz` single voice preset.
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors of a particular framework. Acceptable values are:

                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.

        Returns:
            Tuple([`BatchEncoding`], [`BatchFeature`]): A tuple composed of a [`BatchEncoding`], i.e the output of the
            `tokenizer` and a [`BatchFeature`], i.e the voice preset with the right tensors type.
        z.npz)ÚdataÚtensor_typeÚ
max_length)Úreturn_tensorsÚpaddingrd   Úreturn_attention_maskÚreturn_token_type_idsÚadd_special_tokensÚhistory_prompt)rY   Údictr\   r   rD   ÚendswithrE   r3   r`   r   r   )
r   ÚtextrM   re   rd   ri   rg   rh   r8   Úencoded_texts
             r   Ú__call__zBarkProcessor.__call__á   sí   € ðH Ð#¬J°|ÄTÔ,Jä˜<¬Ô-Ø×+Ñ+Ð7Ø  D×$;Ñ$;Ñ;à#×6Ñ6°|ÓD‘ô ˜l¬CÔ0¸×9NÑ9NÈvÔ9VØ#/°&Ñ#8�Lä!Ÿw™w |Ó4�àÐ#Ø,ˆD×,Ñ,¨\ÑD¸VÒDÜ'¨\À~ÔVˆLà%�t—~‘~Øð	
à)Ø Ø!Ø"7Ø"7Ø1ñ	
ð ñ	
ˆð Ð#Ø-9ˆLÐ)Ñ*àÐr   r   )úspeaker_embeddings_path.json)rp   r   F)NNÚpté   FTF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Útokenizer_classÚ
attributesr]   r   Úclassmethodr4   ÚboolrH   r   r\   rD   rk   r`   ro   Ú__classcell__)r   s   @r   r   r   #   s¥   ø„ ñð &€OØ�€Jð ØØñ€Lõ5ð
 àMkò5Oó ð5Oðt &DØ%9Ø!ñ7Gð
 õ7Gñr"!¨x¸©}ó "!ñH	j¸À¹ó 	jð ØØØØ Ø"Ø#÷Dr   r   )rv   r2   r.   Útypingr   ÚnumpyrE   Úfeature_extraction_utilsr   Úprocessing_utilsr   Úutilsr   Ú	utils.hubr   Úautor
   Ú
get_loggerrs   r,   r   Ú__all__© r   r   ú<module>r†      sT   ðñó Û 	Ý ã å 4Ý .Ý Ý $Ý  ð 
ˆ×	Ñ	˜HÓ	%€ôB�Nô BðJ Ð
�r   