Ë
    ÝÍ:jäP  ã                   ó$  — d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZmZmZ d dlZd dlmZ d dlmZmZ ej(                  j+                  d«      Z G d„ de«      Z G d	„ d
e«      Z G d„ dej4                  «      Z G d„ d«      Zy)é    N)ÚPath)ÚCallableÚMappingÚOptionalÚUnion)ÚResponse)ÚConnectionErrorÚ	HTTPErrorzpyannoteai-sdkc                   ó   — e Zd ZdZy)ÚPyannoteAIFailedJobz2Raised when a job failed on the pyannoteAI web APIN©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© ó    új/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/pyannoteai/sdk/client.pyr   r   (   s   „ Ù<àr   r   c                   ó   — e Zd ZdZy)ÚPyannoteAICanceledJobz8Raised when a job was canceled on the pyannoteAI web APINr   r   r   r   r   r   .   s   „ ÙBàr   r   c                   óB   ‡ — e Zd ZdZdededefˆ fd„Zddefˆ fd„Zˆ xZ	S )	Ú_UploadingCallbackBytesIOaK  BytesIO subclass that calls a callback during the upload process

    Parameters
    ----------
    callback : Callable
        Callback called during upload as `callback(total_in_bytes, completed_in_bytes)`
    total_size : int
        Total size to upload (in bytes)
    initial_bytes : bytes
        Initial bytes to upload
    ÚcallbackÚ
total_sizeÚinitial_bytesc                 óN   •— || _         d| _        || _        t        ‰| �  |«       y )Nr   )r   Ú_completed_sizeÚ	_callbackÚsuperÚ__init__)Úselfr   r   r   Ú	__class__s       €r   r    z"_UploadingCallbackBytesIO.__init__A   s(   ø€ ð %ˆŒØ ˆÔØ!ˆŒÜ‰Ñ˜Õ'r   Úreturnc                 óÈ   •— t         ‰| �  |«      }| xj                  t        |«      z  c_        | j                  r'| j	                  | j
                  | j                  ¬«       |S )N)ÚtotalÚ	completed)r   Úreadr   Úlenr   r   )r!   ÚsizeÚdatar"   s      €r   r'   z_UploadingCallbackBytesIO.readL   sU   ø€ Ü‰w‰|˜DÓ!ˆØ×Ò¤ D£	Ñ)ÕØ�>Š>Ø�N‰NØ—o‘oØ×.Ñ.ð ô ð ˆr   )éÿÿÿÿ)
r   r   r   r   r   ÚintÚbytesr    r'   Ú__classcell__)r"   s   @r   r   r   4   s:   ø„ ñ
ð	(àð	(ð ð	(ð õ		(ñ˜u÷ ñ r   r   c                   ó  — e Zd ZdZdZd)dee   fd„Zdefd„Z	ded	efd
„Z
d)dedee   d	efd„Zed„ «       Zej                  ded	dfd„«       Zded	efd„Zdeeef   d	efd„Z	 	 d*deez  eeeez  f   z  dee   dee   d	efd„Z	 	 	 	 	 	 	 	 	 d+dededz  dedz  dedz  dededededededz  d	efd „Z	 d,deded	efd!„Z	 	 	 	 	 	 	 	 	 d-ded"eeef   d#ed$ededz  dedz  dedz  dedededed	efd%„Zd.d&ed'ed	efd(„Zy)/ÚClienta  Official client for pyannoteAI web API

    Parameters
    ----------
    token : str, optional
        pyannoteAI API key created from https://dashboard.pyannote.ai.
        Defaults to using `PYANNOTEAI_API_KEY` environment variable.

    Usage
    -----

    # instantiate client for pyannoteAI web API
    >>> from pyannoteai.sdk import Client
    >>> client = Client(token="{PYANNOTEAI_API_KEY}")

    # upload your audio file to the pyannoteAI web API
    # and store it for a few hours for later re-use.
    >>> media_url = client.upload("/path/to/your/audio.wav")

    # initiate a diarization job on the pyannoteAI web API
    >>> job_id = client.diarize(media_url)

    # retrieve prediction from pyannoteAI web API
    >>> prediction = client.retrieve(job_id)
    zhttps://api.pyannote.ai/v1NÚtokenc                 ód   — || _         |xs  t        j                  j                  dd«      | _        y )NÚPYANNOTEAI_API_KEYÚ )r1   ÚosÚenvironÚgetÚapi_key)r!   r1   Úkwargss      r   r    zClient.__init__t   s%   € ØˆŒ
ØÒH¤§
¡
§¡Ð/CÀRÓ Hˆ�r   Úresponsec                 óX   — |j                   dk(  rt        d«      ‚|j                  «        y)z9Raise an exception if the response status code is not 2xxi‘  zÄ
Failed to authenticate to pyannoteAI API. Please create an API key on https://dashboard.pyannote.ai/ and
provide it either via `PYANNOTEAI_API_KEY` environment variable or with `token` parameter.N)Ústatus_coder
   Úraise_for_status)r!   r:   s     r   Ú_raise_for_statuszClient._raise_for_statusx   s3   € ð ×Ñ 3Ò&Üð^óð ð 	×!Ñ!Õ#r   Úrouter#   c                 ó¸   — 	 t        j                  | j                  › |› �| j                  ¬«      }| j                  |«       |S # t        $ r t	        d«      ‚w xY w)a,  Send GET authenticated request to pyannoteAI API

        Parameters
        ----------
        route : str
            API route to send the GET request to.

        Returns
        -------
        response : Response

        Raises
        ------
        ConnectionError
        HTTPError
        )Úheadersú¨
Failed to connect to pyannoteAI web API. Please check your internet connection
or visit https://pyannote.openstatus.dev/ to check the status of the pyannoteAI web API.)Úrequestsr7   ÚAPI_URLÚ_headersr	   r>   )r!   r?   r:   s      r   Ú_authenticated_getzClient._authenticated_get‡   sa   € ð$	Ü—|‘| t§|¡| n°U°GÐ$<ÀdÇmÁmÔTˆHð 	×Ñ˜xÔ(àˆøô ò 	Ü!ð\óð ð	ús   ‚/A ÁAÚjsonc                 óº   — 	 t        j                  | j                  › |› �|| j                  ¬«      }| j                  |«       |S # t        $ r t	        d«      ‚w xY w)a‡  Send POST authenticated request to pyannoteAI web API

        Parameters
        ----------
        route : str
            API route to send the GET request to.
        json : dict, optional
            Request body to send with the POST request.

        Returns
        -------
        response : Response

        Raises
        ------
        ConnectionError
        HTTPError
        )rG   rA   rB   )rC   ÚpostrD   rE   r	   r>   )r!   r?   rG   r:   s       r   Ú_authenticated_postzClient._authenticated_post¦   sf   € ð(		Ü—}‘}Ø—<‘<�.  Ð(¨t¸T¿]¹]ôˆHð 	×Ñ˜xÔ(àˆøô ò 	Ü!ð\óð ð	ús   ‚0A ÁAc                 ó   — | j                   S ©N)Ú_api_key)r!   s    r   r8   zClient.api_keyÉ   s   € à�}‰}Ðr   r8   c                 óŒ   — |st        d«      ‚|| _        d| j                  › �dt        › �ddœ| _        | j	                  d«       y )NzÈ
Failed to authenticate to pyannoteAI web API. Please create an API key on https://dashboard.pyannote.ai/ and
provide it either via `PYANNOTEAI_API_KEY` environment variable or with `token` parameter.zBearer zpyannoteAI-sdk-python/zapplication/json)ÚAuthorizationz
User-AgentzContent-Typez/test)Ú
ValueErrorrM   Ú__version__rE   rF   )r!   r8   s     r   r8   zClient.api_keyÍ   sU   € áÜð^óð ð  ˆŒà& t§}¡} oÐ6Ø2´;°-Ð@Ø.ñ
ˆŒð 	×Ñ Õ(r   Ú	media_urlc                 óR   — | j                  dd|i¬«      }|j                  «       d   S )aZ  Create a presigned URL to upload audio file to pyannoteAI platform

        Parameters
        ----------
        media_url : str
            Unique identifier used to retrieve the uploaded audio file on the pyannoteAI platform.
            Any combination of letters (a-z, A-Z), digits (0-9), and the characters -./  prefixed
            with media:// is allowed. One would usually use a string akin to a path on filesystem
            (e.g. "media://path/to/audio.wav").

        Returns
        -------
        url : str
            Presigned URL to upload audio file to pyannoteAI platform
        z/media/inputÚurl©rG   )rJ   rG   )r!   rR   r:   s      r   Ú_create_presigned_urlzClient._create_presigned_urlà   s/   € ð" ×+Ñ+¨NÀ%ÈÐASÐ+ÓTˆØ�}‰}‹˜uÑ%Ð%r   Úfilec                 óø   ‡— t        j                  «       }t        |d«      5 Št        ˆfd„d«      D ]  }|j	                  |«       Œ 	 ddd«       |j                  «       S # 1 sw Y   |j                  «       S xY w)zACompute MD5 hash of a file (used for media_url when not provided)Úrbc                  ó&   •— ‰ j                  d«      S )Ni   )r'   )Úfs   €r   ú<lambda>z"Client._hash_md5.<locals>.<lambda>ù   s   ø€  a§f¡f¨T£l€ r   r   N)ÚhashlibÚmd5ÚopenÚiterÚupdateÚ	hexdigest)r!   rW   Úhash_md5Úchunkr[   s       @r   Ú	_hash_md5zClient._hash_md5ô   sq   ø€ ô —;‘;“=ˆÜ�$˜Óð 	' ÜÓ2°CÓ8ò '�Ø—‘ Õ&ñ'÷	'ð ×!Ñ!Ó#Ð#÷	'ð ×!Ñ!Ó#Ð#ús   ¢&A!Á!A9Úaudior   c                 ó  — d}t        |t        «      rÊd|v r|d   }nÀd|v r±d}	 ddl}|d   }|d   }t	        |d   d	«      r|d   j                  d¬
«      }t        j                  dd¬«      5 }|j                  j                  j                  |j                  ||j                  «       «       |j                  «        |j                  }ddd«       nt        d«      ‚t        j                   j#                  |«      }	|€d| j%                  |«      › �}t'        |d«      5 }t)        ||	|j+                  «       «      }
ddd«       t        |t,        «      r|j/                  d«      st        d|› d�«      ‚| j1                  |«      }	 t3        j4                  |
¬«      }	 |r5t        j                   j9                  |«      rt        j:                  |«       	 |j=                  «        t?        j@                  d«       |S # t        $ r t        d«      ‚w xY w# 1 sw Y   �Œ?xY w# 1 sw Y   ŒæxY w# t6        $ r t7        d|› d�«      ‚w xY w# |r6t        j                   j9                  |«      rt        j:                  |«       w w w xY w)a˜  Upload audio file to pyannoteAI platform

        Parameters
        ----------
        audio : str or Path or dict
            Path to audio file to be uploaded. Can be a "str" or "Path" instance, or a dict with an
            "audio" key (e.g. {"audio": "/path/to/audio.wav"}).
        media_url : str, optional
            Unique identifier used to retrieve the uploaded audio file on the pyannoteAI platform.
            Any combination of letters {a-z, A-Z}, digits {0-9}, and {-./} characters prefixed
            with 'media://' is allowed. One would usually use a string akin to a path on filesystem
            (e.g. "media://path/to/audio.wav"). Defaults to media://{md5-hash-of-audio-file}.
        callback : Callable, optional
            When provided, `callback` is called during the uploading process with the following signature:
                callback(total=...,     # number of bytes to upload
                         completed=...) # number of bytes uploaded)

        Returns
        -------
        media_url : str
            Same as the input `media_url` parameter when provided,
            or "media://{md5-hash-of-audio-file}" otherwise.
        Frf   ÚwaveformTr   Nz>To process the waveform directly, you need to install `scipy`.Úsample_rateÚnumpy)Úforcez.wav)ÚsuffixÚdeletezRWhen `audio` is a dict, it must provide the path to the audio file in 'audio' key.zmedia://rY   z
Invalid media URI: zp. Any combination of letters {a-z, A-Z}, digits {0-9},
and {-./} characters prefixed with 'media://' is allowed.)r*   z)
Failed to upload audio to presigned URL z|.
Please check your internet connection or visit https://pyannote.openstatus.dev/ to check the status of the pyannoteAI API.aR  
You are using pyannoteAI's temporary storage solution. Your file will be permanently deleted from our servers within 24hs. 
If you are running in production, we highly recommend to use your own storage to reduce network latency and obtain results faster. 
Please check our documentation at https://docs.pyannote.ai/ for more information.)!Ú
isinstancer   Úscipy.ioÚImportErrorÚhasattrrj   ÚtempfileÚNamedTemporaryFileÚioÚwavfileÚwriteÚnameÚsqueezeÚflushrP   r5   ÚpathÚgetsizere   r_   r   r'   ÚstrÚ
startswithrV   rC   Úputr	   ÚexistsÚremover=   ÚwarningsÚwarn)r!   rf   rR   r   rm   Úscipyri   rh   r[   r   r*   Úpresigned_urlr:   s                r   ÚuploadzClient.uploadý   s‰  € ð@ ˆä�eœWÔ%Ø˜%ÑØ˜g™‘à˜uÑ$Ø�ðÛ#ð $ MÑ2�Ø  Ñ,�ô ˜5 Ñ,¨gÔ6Ø$ ZÑ0×6Ñ6¸TÐ6ÓB�Hô ×0Ñ0¸ÀuÔMð #ÐQRØ—H‘H×$Ñ$×*Ñ*¨1¯6©6°;À×@PÑ@PÓ@RÔSØ—G‘G”IØŸF™F�E÷#ð #ô
 !Øhóð ô —W‘W—_‘_ UÓ+ˆ
àÐØ" 4§>¡>°%Ó#8Ð"9Ð:ˆIô �%˜Óð 	M !ô -¨X°zÀ1Ç6Á6Ã8ÓLˆD÷	Mô
 ˜9¤cÔ*¨y×/CÑ/CÀJÔ/OÜðØ�;ð <ð?óð ð ×2Ñ2°9Ó=ˆð
	!Ü—|‘| M¸Ô=‰Hñ œ"Ÿ'™'Ÿ.™.¨Ô/Ü—	‘	˜%Õ ð 	×!Ñ!Ô#ä�‰ð Uô 	Vð
 ÐøôE #ò Ü%ØXóð ðú÷#ñ #ú÷"	Mð 	Mûô$ ò 	Ü!ð)Ø)6¨ð 8{ð~óð ð	ûñ œ"Ÿ'™'Ÿ.™.¨Ô/Ü—	‘	˜%Õ ð 0ˆvús<   ¤G: Á-AHÄHÆH+ Ç:HÈHÈH(È+IÉI É:JÚnum_speakersÚmin_speakersÚmax_speakersÚ
confidenceÚturn_level_confidenceÚ	exclusiveÚmodelÚtranscriptionÚtranscription_configc           
      óš   — |||||||||	dœ	}|
�|
|d<   |j                  |«       | j                  d|¬«      }|j                  «       }|d   S )a,  Initiate a diarization job on the pyannoteAI web API

        Parameters
        ----------
        media_url : str
            media://{...} URL created with the `upload` method or
            any other public URL pointing to an audio file.
        num_speakers : int, optional
            Force number of speakers to diarize. If not provided, the
            number of speakers will be determined automatically.
        min_speakers : int, optional
            Minimum number of speakers.
        max_speakers : int, optional
            Maximum number of speakers.
        confidence : bool, optional
            Enable confidence scores.
        turn_level_confidence: bool, optional
            Enable turn-based confidence scores.
        exclusive: bool, optional
            Enable exclusive speaker diarization.
        model : str, optional
            Defaults to "precision-2"
        transcription : bool, optional
            Enable STT orchestration.
        transcription_config : dict, optional
            STT configuration parameters, including model selection.
        **kwargs : optional
            Extra arguments to send in the body of the request.

        Returns
        -------
        job_id: str

        Raises
        ------
        HTTPError
            If something else went wrong
        )	rT   rŒ   ÚnumSpeakersÚminSpeakersÚmaxSpeakersr‰   ÚturnLevelConfidencer‹   r�   ÚtranscriptionConfigz/diarizerU   ÚjobId©ra   rJ   rG   )r!   rR   r†   r‡   rˆ   r‰   rŠ   r‹   rŒ   r�   rŽ   r9   rG   r:   r*   s                  r   ÚdiarizezClient.diarizek  sr   € ðl ØØ'Ø'Ø'Ø$Ø#8Ø"Ø*ñ

ˆð  Ð+Ø*>ˆDÐ&Ñ'ð 	�‰�FÔà×+Ñ+¨J¸TÐ+ÓBˆØ�}‰}‹ˆØ�G‰}Ðr   c                 ó~   — ||dœ}|j                  |«       | j                  d|¬«      }|j                  «       }|d   S )a)  Initiate a voiceprint job on the pyannoteAI web API

        Parameters
        ----------
        media_url : str
            media://{...} URL created with the `upload` method or
            any other public URL pointing to an audio file.
        model : str, optional
            Defaults to "precision-2".
        **kwargs : optional
            Extra arguments to send in the body of the request.

        Returns
        -------
        job_id: str

        Raises
        ------
        HTTPError
            If something else went wrong
        )rT   rŒ   z/voiceprintrU   r•   r–   )r!   rR   rŒ   r9   rG   r:   r*   s          r   Ú
voiceprintzClient.voiceprint¶  sD   € ð8 !¨5Ñ1ˆà�‰�FÔà×+Ñ+¨MÀÐ+ÓEˆØ�}‰}‹ˆØ�G‰}Ðr   ÚvoiceprintsÚexclusive_matchingÚmatching_thresholdc                 óè   — |||||||	|
|j                  «       D ��cg c]
  \  }}||dœ‘Œ c}}||dœdœ
}|j                  |«       | j                  d|¬«      }|j                  «       }|d   S c c}}w )a  Initiate an identification job on the pyannoteAI web API

        Parameters
        ----------
        media_url : str
            media://{...} URL created with the `upload` method or
            any other public URL pointing to an audio file.
        voiceprints : dict
            Voiceprints.
        exclusive_matching : bool, optional
            Prevent multiple speakers from being matched to the same voiceprint.
            Defaults to True.
        matching_threshold : float, optional
            Prevent matching if confidence score is below this threshold.
            Value is between 0 and 100. Default is 0, meaning all voiceprints are matched.
        num_speakers : int, optional
            Force number of speakers to diarize. If not provided, the
            number of speakers will be determined automatically.
        min_speakers : int, optional
            Minimum number of speakers.
        max_speakers : int, optional
            Maximum number of speakers.
        confidence : bool, optional
            Enable confidence scores.
        turn_level_confidence: bool, optional
            Enable turn-based confidence scores.
        exclusive: bool, optional
            Enable exclusive speaker diarization.
        model : str, optional
            Defaults to "precision-2"
        **kwargs : optional
            Extra arguments to send in the body of the request.

        Returns
        -------
        job_id: str

        Raises
        ------
        HTTPError
            If something else went wrong
        )Úlabelr™   )r‹   Ú	threshold)
rT   rŒ   r�   r‘   r’   r‰   r“   r‹   rš   Úmatchingz	/identifyrU   r•   )Úitemsra   rJ   rG   )r!   rR   rš   r›   rœ   r†   r‡   rˆ   r‰   rŠ   r‹   rŒ   r9   Úspeakerr™   rG   r:   r*   s                     r   ÚidentifyzClient.identifyÚ  s˜   € ðv ØØ'Ø'Ø'Ø$Ø#8Ø"ð ,7×+<Ñ+<Ó+>÷á'�G˜Zð "°Ó<óð
 0Ø/ññ
ˆð& 	�‰�FÔà×+Ñ+¨K¸dÐ+ÓCˆØ�}‰}‹ˆØ�G‰}Ðùós   œA.Újob_idÚevery_secondsc                 ó¦  — d}	 | j                  d|› �«      j                  «       }|d   }|dvrt        j                  |«       ŒB	 |dk(  r6|j	                  dt        «       «      j	                  dd«      }t        ||«      ‚|d	k(  r6|j	                  dt        «       «      j	                  dd«      }t        ||«      ‚t        j                  d
«       |S )aÂ  Retrieve output of a job (once completed) from pyannoteAI web API

        Parameters
        ----------
        job_id : str
            Job ID.

        Returns
        -------
        job_output : dict
            Job output

        Raises
        ------
        PyannoteAIFailedJob
            If the job failed
        PyannoteAICanceledJob
            If the job was canceled
        HTTPError
            If something else went wrong
        Nz/jobs/Ústatus)Ú	succeededÚcanceledÚfailedrª   ÚoutputÚerrorzPlease contact support.r©   a  
You are using periodic polling to retrieve results. 
If you are running in production, we highly recommend to setup a webhook server to obtain results faster, as soon as they are available. 
Please check our documentation at https://docs.pyannote.ai/ for more information.)
rF   rG   ÚtimeÚsleepr7   Údictr   r   r�   r‚   )r!   r¤   r¥   Ú
job_statusÚjobr¬   s         r   ÚretrievezClient.retrieve-  sÔ   € ð. ˆ
àØ×)Ñ)¨F°6°(Ð*;Ó<×AÑAÓCˆCØ˜X™ˆJàÐ!DÑDÜ—
‘
˜=Ô)Øàà˜Ò!Ø—G‘G˜H¤d£fÓ-×1Ñ1°'Ð;TÓUˆEÜ% e¨VÓ4Ð4à˜Ò#Ø—G‘G˜H¤d£fÓ-×1Ñ1°'Ð;TÓUˆEÜ'¨¨vÓ6Ð6ä�‰ð Uô 	Vð
 ˆ
r   rL   )NN)	NNNFFFúprecision-2FN)r³   )	Tg        NNNFFFr³   )é
   )r   r   r   r   rD   r   r|   r    r   r>   rF   r¯   rJ   Úpropertyr8   ÚsetterrV   r   r   re   r   r…   r,   Úboolr—   r™   Úfloatr£   r²   r   r   r   r0   r0   W   sÅ  „ ñð4 +€GñI˜h s™mó Ið$¨(ó $ð¨ð °ó ñ>!¨ð !°H¸T±Nð !Èhó !ðF ñó ðð ‡^�^ð)˜sð ) tò )ó ð)ð$&¨sð &°só &ð($˜e C¨ IÑ.ð $°3ó $ð $(Ø'+ñ	là�T‰z˜D  c¨D¡j Ñ1Ñ1ðlð ˜C‘=ðlð ˜8Ñ$ð	lð
 
ólðb $(Ø#'Ø#'Ø Ø&+ØØ"Ø#Ø,0ñIàðIð ˜D‘jðIð ˜D‘jð	Ið
 ˜D‘jðIð ðIð  $ðIð ðIð ðIð ðIð # T™kðIð 
óIð\ #ñ"àð"ð ð"ð
 
ó"ðP $(Ø$'Ø#'Ø#'Ø#'Ø Ø&+ØØ"ñQàðQð ˜#˜s˜(‘^ðQð !ð	Qð
 "ðQð ˜D‘jðQð ˜D‘jðQð ˜D‘jðQð ðQð  $ðQð ðQð ðQð 
óQñf0˜sð 0°3ð 0Àô 0r   r0   )r]   Úimportlib.metadataÚ	importlibrt   r5   rr   r­   r�   Úpathlibr   Útypingr   r   r   r   rC   r   Úrequests.exceptionsr	   r
   ÚmetadataÚversionrQ   Ú	Exceptionr   r   ÚBytesIOr   r0   r   r   r   ú<module>rÂ      sz   ðó. Û Û 	Û 	Û Û Û Ý ß 5Ó 5ã Ý ß :à× Ñ ×(Ñ(Ð)9Ó:€ô	˜)ô 	ô	˜Iô 	ô  §
¡
ô  ÷FFò Fr   