Ë
    ÛÓ^j±<  ã                   ó¶   — d Z ddlZddl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mZ ddlmZ d	d
lmZ  ej$                  e«      Ze G d„ de«      «       ZdgZy)z
Processor class for Bark
é    Né   )ÚBatchFeature)ÚProcessorMixin)ÚBatchEncoding)Úauto_docstringÚlogging)Úcached_fileé   )ÚAutoTokenizerc                   óè   ‡ — e Zd ZddddœZdˆ fd„	Ze	 dd„«       Z	 	 	 ddefˆ fd„Ze	d	e
d
e
de
fd„«       Zdde
dz  fd„Zddedz  fd„Zedefd„«       Zddefd„Ze	 	 	 	 	 	 	 ddefd„«       Zˆ xZS )ÚBarkProcessoré   r
   ©Úsemantic_promptÚcoarse_promptÚfine_promptNc                 ó2   •— t         ‰| �  |«       || _        y)a*  
        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`.
        N)ÚsuperÚ__init__Úspeaker_embeddings)ÚselfÚ	tokenizerr   Ú	__class__s      €ús/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/bark/processing_bark.pyr   zBarkProcessor.__init__*   s   ø€ ô 	‰Ñ˜Ô#à"4ˆÕó    c                 óT  — |j                  d«      }|�Ýt        |||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}�	d|v r||d<   t        j                  |fi |¤Ž} | ||¬«      S # 1 sw Y   Œ4x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`].
        ÚtokenNÚ	subfolderÚ	cache_dirÚforce_downloadFÚproxiesÚlocal_files_onlyÚrevision©
r   r   r    r!   r"   r   r#   Ú _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`.Úrepo_or_path)r   r   )Úgetr	   ÚpopÚloggerÚwarningÚosÚpathÚjoinÚopenÚjsonÚloadr   Úfrom_pretrained)	ÚclsÚ!pretrained_processor_name_or_pathÚspeaker_embeddings_dict_pathÚkwargsr   Úspeaker_embeddings_pathr   Úspeaker_embeddings_jsonr   s	            r   r4   zBarkProcessor.from_pretrained7   sO  € ð, —
‘
˜7Ó#ˆØ'Ð3Ü&1Ø1Ø,Ø Ÿ*™* [°$Ó7Ø Ÿ*™* [°$Ó7Ø%Ÿz™zÐ*:¸EÓBØŸ
™
 9¨dÓ3Ø!'§¡Ð,>ÀÓ!FØØŸ™ J°Ó5Ø16Ø6;Ø8=ô'Ð#ð 'Ð.Ü—‘Øœ"Ÿ'™'Ÿ,™,Ð'HÐJfÓgÐhð i]ð `ôð
 &*Ñ"äÐ1Ó2ð LÐ6MÜ)-¯©Ð3JÓ)KÐ&÷Lð Lð "&ÐàÐ)ØÐ!3Ñ3Ø5VÐ" >Ñ2Ü!×1Ñ1Ð2SÑ^ÐW]Ñ^ˆ	á˜YÐ;MÔNÐN÷Lð Lús   ÃDÄD'Úpush_to_hubc           	      ó  •— | j                   ��_t        j                  t        j                  j	                  ||d«      d¬«       i }||d<   t        j                  j	                  ||«      }| j
                  D ]ª  }| j                  |«      }	i }
| j                   |   D ]~  }t        j                  j	                  ||› d|› �«      }| j                  |||«       t        j                  ||	|   d¬«       t        j                  j	                  ||› d|› d	�«      |
|<   Œ€ |
||<   Œ¬ t        t        j                  j	                  ||«      d
«      5 }t        j                  ||«       ddd«       t        ‰| �8  ||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_okr)   Ú_F)Úallow_picklez.npyÚw)r   r.   Úmakedirsr/   r0   Úavailable_voice_presetsÚ_load_voice_presetÚ_reject_path_traversalÚnpÚsaver1   r2   Údumpr   Úsave_pretrained)r   Úsave_directoryr7   Úspeaker_embeddings_directoryr;   r8   Úembeddings_dictÚembeddings_subdirÚ
prompt_keyÚvoice_presetÚtmp_dictÚkeyÚtarget_filepathÚfpr   s                 €r   rI   zBarkProcessor.save_pretrainedq   s{  ø€ ð8 ×"Ñ"Ñ.Ü�K‰KœŸ™Ÿ™ ^Ð5QÐSWÓXÐcgÕhà ˆOà.<ˆO˜NÑ+ä "§¡§¡¨^Ð=YÓ ZÐØ"×:Ñ:ò 
7�
Ø#×6Ñ6°zÓB�à�Ø×2Ñ2°:Ñ>ò j�CÜ&(§g¡g§l¡lÐ3DÈÈÐTUÐVYÐUZÐF[Ó&\�OØ×/Ñ/Ð0AÀ?ÐT^Ô_Ü—G‘G˜O¨\¸#Ñ->ÈUÕSÜ$&§G¡G§L¡LÐ1MÐR\ÐQ]Ð]^Ð_bÐ^cÐcgÐOhÓ$i�H˜S’Mð	jð /7� 
Ò+ð
7ô ”b—g‘g—l‘l >Ð3OÓPÐRUÓVð /ÐZ\Ü—	‘	˜/¨2Ô.÷/ô 	‰Ñ °ÑF¸vÓF÷/ð /ús   ÅF Æ F	Úbase_dirÚtarget_pathÚoffending_valuec                 ó  — t         j                  j                  | «      }t         j                  j                  |«      }	 t         j                  j                  ||g«      |k(  }|st	        d|›�«      ‚y # t        $ r d}Y Œw xY w)NFzInvalid voice preset path: )r.   r/   ÚabspathÚ
commonpathÚ
ValueError)rT   rU   rV   ÚbaseÚtargetÚ	containeds         r   rE   z$BarkProcessor._reject_path_traversal¦   s~   € ô �w‰w�‰˜xÓ(ˆÜ—‘—‘ Ó-ˆð	ÜŸ™×*Ñ*¨D°&¨>Ó:¸dÑBˆIñ ÜÐ:¸?Ð:MÐNÓOÐOð øô ò 	àŠIð	ús   Á $A5 Á5BÂBrO   c                 ó$  — | j                   |   }i }|j                  d«      }| j                   j                  dd«      }dD �]K  }||vrt        d|› d|› d�«      ‚| j                  |t        j
                  j                  |||   «      ||   «       t        | j                   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                  |«      ||<   �ŒN |S )Nr   r)   ú/r   ú#Voice preset unrecognized, missing z% as a key in self.speaker_embeddings[z].r   r   r    Fr!   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   r*   rZ   rE   r.   r/   r0   r	   r+   rF   r3   )	r   rO   r8   Úvoice_preset_pathsÚvoice_preset_dictr   r)   rQ   r/   s	            r   rD   z BarkProcessor._load_voice_preset¹   sµ  € Ø!×4Ñ4°\ÑBÐàÐØ—
‘
˜7Ó#ˆØ×.Ñ.×2Ñ2°>À3ÓGˆØFó 	3ˆCØÐ,Ñ,Ü Ø9¸#¸Ð>cÐdpÐcqÐqsÐtóð ð ×'Ñ'ØœbŸg™gŸl™l¨<Ð9KÈCÑ9PÓQÐSeÐfiÑSjôô Ø×'Ñ'×+Ñ+¨N¸CÓ@Ø" 3Ñ'Ø Ÿ*™* [°$Ó7Ø Ÿ*™* [°$Ó7Ø%Ÿz™zÐ*:¸EÓBØŸ
™
 9¨dÓ3Ø!'§¡Ð,>ÀÓ!FØØŸ™ 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Ó"ð=	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   r`   z
 as a key.z voice preset must be a z
D ndarray.)	rZ   Ú
isinstancerF   ÚndarrayÚ	TypeErrorÚstrÚpreset_shapeÚlenÚshape)r   rO   rQ   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   Úreturnc                 ó’   — | j                   €g S t        | j                   j                  «       «      }d|v r|j                  d«       |S )z…
        Returns a list of available voice presets.

        Returns:
            `list[str]`: A list of voice preset names.
        r)   )r   ÚlistÚkeysÚremove)r   Úvoice_presetss     r   rC   z%BarkProcessor.available_voice_presetsì   sJ   € ð ×"Ñ"Ð*ØˆIä˜T×4Ñ4×9Ñ9Ó;Ó<ˆØ˜]Ñ*Ø× Ñ  Ô0ØÐr   Úremove_unavailablec                 óF  — g }| j                   �s| j                  D ]%  }	 | j                  |«      }| j                  |«       Œ' |r%t        j                  dt        |«      › d|› d�«       |r|D ]  }| j                   |= Œ y y y # t        $ r |j	                  |«       Y Œ„w xY w)NzThe following z' speaker embeddings are not available: zU If you would like to use them, please check the paths or try downloading them again.)	r   rC   rD   rZ   Úappendrk   r,   r-   ri   )r   rr   Úunavailable_keysrO   rb   s        r   Ú_verify_speaker_embeddingsz(BarkProcessor._verify_speaker_embeddingsü   sÕ   € àÐØ×"Ñ"Ð.Ø $× <Ñ <ò D�ðØ(,×(?Ñ(?ÀÓ(MÐ%ð
 ×0Ñ0Ð1BÕCðDñ  Ü—‘Ø$¤SÐ)9Ó%:Ð$;Ð;bÐcsÐbtð ukð kôñ
 "Ø$4ò >�LØ×/Ñ/°Ñ=ñ>ð "ð! /øô "ò à$×+Ñ+¨LÔ9Ùðús   ŸBÂB ÂB 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ù  
        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 containing the keys
            `"semantic_prompt"`, `"coarse_prompt"` and `"fine_prompt"`.

        Returns:
            [`BatchEncoding`]: A [`BatchEncoding`] object containing the output of the `tokenizer`.
            If a voice preset is provided, the returned object will include a `"history_prompt"` key
            containing a [`BatchFeature`], i.e the voice preset with the right tensors type.
        z.npz)ÚdataÚtensor_typeÚ
max_length)Úreturn_tensorsÚpaddingrz   Úreturn_attention_maskÚreturn_token_type_idsÚadd_special_tokensÚhistory_prompt)rd   Údictrg   r   rD   ÚendswithrF   r3   rk   r   r   )
r   ÚtextrO   r{   rz   r   r}   r~   r8   Úencoded_texts
             r   Ú__call__zBarkProcessor.__call__  sì   € ð0 Ð#¬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   )N)úspeaker_embeddings_path.json)r†   r   F)T)NNÚpté   FTF)Ú__name__Ú
__module__Ú__qualname__rh   r   Úclassmethodr4   ÚboolrI   Ústaticmethodrg   rE   rD   r�   rk   Úpropertyrn   rC   rv   r   r   r…   Ú__classcell__)r   s   @r   r   r   "   s   ø„ ð ØØñ€Lõ5ð àMkò7Oó ð7Oðx &DØ%9Ø!ñ3Gð
 õ3Gðj ðP¨ð P¸3ð PÐQTò Pó ðPñ$&!¨s°T©zó &!ñP	j¸¸t¹ó 	jð ð¨ò ó ðñ>¸Tó >ð. ð ØØØØ Ø"Ø#ñ7ð 
ò7ó ô7r   r   )Ú__doc__r2   r.   ÚnumpyrF   Úfeature_extraction_utilsr   Úprocessing_utilsr   Útokenization_utils_baser   Úutilsr   r   Ú	utils.hubr	   Úautor   Ú
get_loggerr‰   r,   r   Ú__all__© r   r   ú<module>rœ      sd   ðñó Û 	ã å 4Ý .Ý 4ß ,Ý $Ý  ð 
ˆ×	Ñ	˜HÓ	%€ð ôh�Nó hó ðhðV	 Ð
�r   