o
    qmiI                     @   s~   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	 ej
r/ddlmZmZ G dd dZG d	d
 d
ZdS )    N)
HTTPStatus   )JobStatusV1Response   )#AsyncSpeechToTextTranslateJobClientSpeechToTextTranslateJobClientc                   @     e Zd ZdeddfddZedefddZ		d'd
eje de	de
fddZ	d(dededefddZdejejeef  fddZdejeejejeejf  f fddZdede
fddZdefddZdefddZde
fddZde
fd d!Zde
fd"d#Zde
fd$d%Zd&S ))AsyncSpeechToTextTranslateJobjob_idclientr   c                 C      || _ || _dS )aa  
        Initialise the asynchronous speech-to-text-translate-translate job.

        Parameters
        ----------
        job_id : str
            The unique job identifier returned from a previous job initialisation.

        client : AsyncSpeechToTextTranslateJobClient
            The async client instance used to create the job.

            !!! important
                This must be the **same client instance** that was used to initialise
                the job originally, as it contains the subscription key and configuration
                required to authenticate and manage the job.

        N_job_id_clientselfr
   r    r   ]/home/ubuntu/.local/lib/python3.10/site-packages/sarvamai/speech_to_text_translate_job/job.py__init__   s   
z&AsyncSpeechToTextTranslateJob.__init__returnc                 C      | j S zt
        Returns the job ID associated with this job instance.

        Returns
        -------
        str
        r   r   r   r   r   r
   ,      	z$AsyncSpeechToTextTranslateJob.job_id      N@
file_pathstimeoutc              
      s  | j j| jdd |D dI dH }tj|d}tj|d4 I dH Y}|D ]J}tj|}|j	| j
}t|d}	|j||	 ddd	d
I dH }
W d   n1 sSw   Y  |
jtjksd|
jtjk rotd| d|
j q%W d  I dH  dS 1 I dH sw   Y  dS )a  
        Upload input audio files for the speech-to-text-translate job.

        Parameters
        ----------
        file_paths : Sequence[str]
            List of full paths to local audio files.

        timeout : float, optional
            The maximum time to wait for the upload to complete (in seconds),
            by default 60.0
        Returns
        -------
        bool
            True if all files are uploaded successfully.
        c                 S      g | ]}t j|qS r   ospathbasename.0pr   r   r   
<listcomp>L       z>AsyncSpeechToTextTranslateJob.upload_files.<locals>.<listcomp>r
   filesNr   rb	BlockBlob	audio/wavzx-ms-blob-typezContent-TypecontentheadersUpload failed for : T)r   get_upload_linksr   httpxTimeoutAsyncClientr    r!   r"   upload_urlsfile_urlopenputreadstatus_coder   IM_USEDOKRuntimeError)r   r   r   upload_linksclient_timeoutsessionr!   	file_nameurlfresponser   r   r   upload_files7   s<   
z*AsyncSpeechToTextTranslateJob.upload_files   X  poll_intervalc                    sr   t   }	 |  I dH }|j }|dv r|S t   | |kr0td| j d| dt |I dH  q)  
        Polls job status until it completes or fails.

        Parameters
        ----------
        poll_interval : int, optional
            Time in seconds between polling attempts (default is 5).

        timeout : int, optional
            Maximum time to wait for completion in seconds (default is 600).

        Returns
        -------
        JobStatusV1Response
            Final job status.

        Raises
        ------
        TimeoutError
            If the job does not complete within the given timeout.
        TN>   failed	completedJob  did not complete within 	 seconds.)	asyncioget_event_looptime
get_status	job_statelowerTimeoutErrorr   sleepr   rK   r   startstatusstater   r   r   wait_until_completee   s   
z1AsyncSpeechToTextTranslateJob.wait_until_completec                    s$   |   I dH }dd |jpg D S )
        Get the mapping of input files to their corresponding output files.

        Returns
        -------
        List[Dict[str, str]]
            List of mappings with keys 'input_file' and 'output_file'.
        Nc                 S   <   g | ]}|j r|jr|jd kr|j d j|jd jdqS Successr   )
input_fileoutput_fileinputsoutputsr]   rD   r$   detailr   r   r   r&          


zEAsyncSpeechToTextTranslateJob.get_output_mappings.<locals>.<listcomp>rU   job_detailsr   
job_statusr   r   r   get_output_mappings   s
   	z1AsyncSpeechToTextTranslateJob.get_output_mappingsc              
      s   |   I dH }g g d}|jpg D ]K}|jrt|jdkrqz3|jd j|j|j|jr9t|jdkr9|jd jndd}|jdkrJ|d | n|d | W q t	t
fy]   Y qw |S )-  
        Get detailed results for each file in the batch job.

        Returns
        -------
        Dict[str, List[Dict[str, Any]]]
            Dictionary with 'successful' and 'failed' keys, each containing a list of file details.
            Each file detail includes:
            - 'file_name': Name of the input file
            - 'status': Status of processing ('Success' or 'Failed')
            - 'error_message': Error message if failed (None if successful)
            - 'output_file': Name of output file if successful (None if failed)
        N
successfulrM   r   rD   r\   error_messagerd   rb   rr   rM   rU   rl   rf   lenrD   r]   rt   rg   append
IndexErrorAttributeErrorr   rn   resultsri   	file_infor   r   r   get_file_results   s4   

z.AsyncSpeechToTextTranslateJob.get_file_results
output_dirc              
      s0  |   I dH }dd |D }| jj| j|dI dH }tj|dd t 4 I dH a}|D ]R}|j|d  j	}|
|I dH }|jtjksK|jtjk rXtd|d  d	|j tj||d
  d}	t|	d}
|
|j W d   n1 szw   Y  q-W d  I dH  dS 1 I dH sw   Y  dS )~  
        Download output files to the specified directory.

        Parameters
        ----------
        output_dir : str
            Local directory where outputs will be saved.

        Returns
        -------
        bool
            True if all files downloaded successfully.

        Raises
        ------
        RuntimeError
            If a file fails to download.
        Nc                 S      g | ]}|d  qS rd   r   r$   mr   r   r   r&          zBAsyncSpeechToTextTranslateJob.download_outputs.<locals>.<listcomp>r(   Texist_okrd   Download failed for r3   rc   .jsonwb)ro   r   get_download_linksr   r    makedirsr5   r7   download_urlsr9   getr=   r   r>   r?   r@   r!   joinr:   writer0   )r   r~   mappings
file_namesdownload_linksrC   r   rE   rG   output_pathrF   r   r   r   download_outputs   s4   z.AsyncSpeechToTextTranslateJob.download_outputsc                    s   | j | jI dH S )v
        Retrieve the current status of the job.

        Returns
        -------
        JobStatusV1Response
        Nr   rU   r   r   r   r   r   rU      s   z(AsyncSpeechToTextTranslateJob.get_statusc                    s   | j j| jdI dH S )
        Start the speech-to-text-translate job processing.

        Returns
        -------
        JobStatusV1Response
        r
   Nr   r[   r   r   r   r   r   r[     s   z#AsyncSpeechToTextTranslateJob.startc                    s.   z
|   I dH  W dS  tjy   Y dS w )f
        Check if the job exists in the system.

        Returns
        -------
        bool
        NTFrU   r5   HTTPStatusErrorr   r   r   r   exists  s   z$AsyncSpeechToTextTranslateJob.existsc                    s   |   I dH j }|dv S )o
        Check if the job is either completed or failed.

        Returns
        -------
        bool
        N>   rM   rN   rU   rV   rW   )r   r]   r   r   r   is_complete  s   z)AsyncSpeechToTextTranslateJob.is_completec                       |   I dH j dkS )h
        Check if the job completed successfully.

        Returns
        -------
        bool
        NrN   r   r   r   r   r   is_successful$     z+AsyncSpeechToTextTranslateJob.is_successfulc                    r   )\
        Check if the job has failed.

        Returns
        -------
        bool
        NrM   r   r   r   r   r   	is_failed.  r   z'AsyncSpeechToTextTranslateJob.is_failedNr   rI   rJ   __name__
__module____qualname__strr   propertyr
   typingSequencefloatboolrH   intr   r^   ListDictro   Anyr}   r   rU   r[   r   r   r   r   r   r   r   r   r	      sF    

/
$
1*


r	   c                   @   r   ))SpeechToTextTranslateJobr
   r   r   c                 C   r   )aK  
        Initialise the synchronous speech-to-text-translate job.

        Parameters
        ----------
        job_id : str
            The unique job identifier returned from a previous job initialisation.

        client : SpeechToTextTranslateJobClient
            The client instance used to create the job.

            !!! important
                This must be the **same client instance** that was used to initialise
                the job originally, as it contains the subscription key and configuration
                required to authenticate and manage the job.

        Nr   r   r   r   r   r   :  s   
z!SpeechToTextTranslateJob.__init__r   c                 C   r   r   r   r   r   r   r   r
   O  r   zSpeechToTextTranslateJob.job_idr   r   r   c              
   C   s  | j j| jdd |D d}tj|d}tj|d^}|D ]R}tj|}|j	| j
}t|\}	}
|	du r8d}	t|d}|j||d|	d	d
}W d   n1 sSw   Y  |jtjksd|jtjk rotd| d|j qW d   dS 1 s{w   Y  dS )a  
        Upload input audio files for the speech-to-text-translate job.

        Parameters
        ----------
        file_paths : Sequence[str]
            List of full paths to local audio files.

        timeout : float, optional
            The maximum time to wait for the upload to complete (in seconds),
            by default 60.0

        Returns
        -------
        bool
            True if all files are uploaded successfully.
        c                 S   r   r   r   r#   r   r   r   r&   o  r'   z9SpeechToTextTranslateJob.upload_files.<locals>.<listcomp>r(   r*   Nr-   r+   r,   r.   r/   r2   r3   T)r   r4   r   r5   r6   Clientr    r!   r"   r8   r9   	mimetypes
guess_typer:   r;   r=   r   r>   r?   r@   )r   r   r   rA   rB   r   r!   rD   rE   content_type_rF   rG   r   r   r   rH   Z  s>   

z%SpeechToTextTranslateJob.upload_filesrI   rJ   rK   c                 C   s\   t  }	 |  }|j }|dv r|S t  | |kr(td| j d| dt | q)rL   T>   rM   rN   rO   rP   rQ   )rT   	monotonicrU   rV   rW   rX   r   rY   rZ   r   r   r   r^     s   

z,SpeechToTextTranslateJob.wait_until_completec                 C   s   |   }dd |jpg D S )r_   c                 S   r`   ra   re   rh   r   r   r   r&     rj   z@SpeechToTextTranslateJob.get_output_mappings.<locals>.<listcomp>rk   rm   r   r   r   ro     s   	z,SpeechToTextTranslateJob.get_output_mappingsc              
   C   s   |   }g g d}|jpg D ]K}|jrt|jdkrqz3|jd j|j|j|jr5t|jdkr5|jd jndd}|jdkrF|d | n|d | W q t	t
fyY   Y qw |S )rp   rq   r   Nrs   rb   rr   rM   ru   rz   r   r   r   r}     s2   

z)SpeechToTextTranslateJob.get_file_resultsr~   c              
   C   s  |   }dd |D }| jj| j|d}tj|dd t [}|D ]O}|j|d  j	}|
|}|jtjks=|jtjk rJtd|d  d|j tj||d	  d
}	t|	d}
|
|j W d   n1 slw   Y  q"W d   dS 1 s}w   Y  dS )r   c                 S   r   r   r   r   r   r   r   r&     r   z=SpeechToTextTranslateJob.download_outputs.<locals>.<listcomp>r(   Tr   rd   r   r3   rc   r   r   N)ro   r   r   r   r    r   r5   r   r   r9   r   r=   r   r>   r?   r@   r!   r   r:   r   r0   )r   r~   r   r   r   r   r   rE   rG   r   rF   r   r   r   r     s2   


z)SpeechToTextTranslateJob.download_outputsc                 C   s   | j | jS )r   r   r   r   r   r   rU     s   z#SpeechToTextTranslateJob.get_statusc                 C   s   | j j| jdS )r   r   r   r   r   r   r   r[   '  s   zSpeechToTextTranslateJob.startc                 C   s&   z|    W dS  tjy   Y dS w )r   TFr   r   r   r   r   r   1  s   zSpeechToTextTranslateJob.existsc                 C   s   |   j dv S )r   >   rM   rN   r   r   r   r   r   r   ?     z$SpeechToTextTranslateJob.is_completec                 C      |   j dkS )r   rN   r   r   r   r   r   r   I  r   z&SpeechToTextTranslateJob.is_successfulc                 C   r   )r   rM   r   r   r   r   r   r   S  r   z"SpeechToTextTranslateJob.is_failedNr   r   r   r   r   r   r   r   9  s>    
2
$
1*



r   )rR   r   r    rT   r   r5   httpr   typesr   TYPE_CHECKINGr   r   r   r	   r   r   r   r   r   <module>   s      )