o
    qmi?I                     @   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   )AsyncSpeechToTextJobClientSpeechToTextJobClientc                   @     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 ))AsyncSpeechToTextJobjob_idclientr   c                 C      || _ || _dS )aD  
        Initialize the asynchronous speech-to-text job.

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

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

            !!! important
                This must be the **same client instance** that was used to initialize
                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   S/home/ubuntu/.local/lib/python3.10/site-packages/sarvamai/speech_to_text_job/job.py__init__      
zAsyncSpeechToTextJob.__init__returnc                 C      | j S zt
        Returns the job ID associated with this job instance.

        Returns
        -------
        str
        r   r   r   r   r   r
   %      	zAsyncSpeechToTextJob.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 f}|D ]W}tj|}|j	| j
}t|d%}	t|\}
}|
du rFd}
|j||	 d|
d	d
I dH }W d   n1 s`w   Y  |jtjksq|jtjk r|td| d|j q%W d  I dH  dS 1 I dH sw   Y  dS )  
        Upload input audio files for the speech-to-text 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>E       z5AsyncSpeechToTextJob.upload_files.<locals>.<listcomp>r
   filesNr   rb	audio/wav	BlockBlob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	mimetypes
guess_typeputreadstatus_coder   IM_USEDOKRuntimeError)r   r   r   upload_linksclient_timeoutsessionr#   	file_nameurlfcontent_type_responser   r   r   upload_files0   sB   z!AsyncSpeechToTextJob.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   rQ   r   startstatusstater   r   r   wait_until_completea   s   
z(AsyncSpeechToTextJob.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outputsrc   rH   r&   detailr   r   r   r(          


z<AsyncSpeechToTextJob.get_output_mappings.<locals>.<listcomp>r[   job_detailsr   
job_statusr   r   r   get_output_mappings   s
   	z(AsyncSpeechToTextJob.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
successfulrS   r   rH   rb   error_messagerj   rh   rx   rS   r[   rr   rl   lenrH   rc   rz   rm   append
IndexErrorAttributeErrorr   rt   resultsro   	file_infor   r   r   get_file_results   s4   

z%AsyncSpeechToTextJob.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 rj   r   r&   mr   r   r   r(          z9AsyncSpeechToTextJob.download_outputs.<locals>.<listcomp>r*   Texist_okrj   Download failed for r5   ri   .jsonwb)ru   r   get_download_linksr   r"   makedirsr7   r9   download_urlsr;   getrA   r   rB   rC   rD   r#   joinr<   writer2   )r   r   mappings
file_namesdownload_linksrG   r   rI   rM   output_pathrJ   r   r   r   download_outputs   s4   z%AsyncSpeechToTextJob.download_outputsc                    s   | j | jI dH S )v
        Retrieve the current status of the job.

        Returns
        -------
        JobStatusV1Response
        Nr   r[   r   r   r   r   r   r[      s   zAsyncSpeechToTextJob.get_statusc                    s   | j j| jdI dH S )w
        Start the speech-to-text job processing.

        Returns
        -------
        JobStatusV1Response
        r
   Nr   ra   r   r   r   r   r   ra      s   zAsyncSpeechToTextJob.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r[   r7   HTTPStatusErrorr   r   r   r   exists  s   zAsyncSpeechToTextJob.existsc                    s   |   I dH j }|dv S )o
        Check if the job is either completed or failed.

        Returns
        -------
        bool
        N>   rS   rT   r[   r\   r]   )r   rc   r   r   r   is_complete  s   z AsyncSpeechToTextJob.is_completec                       |   I dH j dkS )h
        Check if the job completed successfully.

        Returns
        -------
        bool
        NrT   r   r   r   r   r   is_successful      z"AsyncSpeechToTextJob.is_successfulc                    r   )\
        Check if the job has failed.

        Returns
        -------
        bool
        NrS   r   r   r   r   r   	is_failed*  r   zAsyncSpeechToTextJob.is_failedNr   rO   rP   __name__
__module____qualname__strr   propertyr
   typingSequencefloatboolrN   intr   rd   ListDictru   Anyr   r   r[   ra   r   r   r   r   r   r   r   r   r	      s>    
2
$
1*


r	   c                   @   r   ))SpeechToTextJobr
   r   r   c                 C   r   )a8  
        Initialize the synchronous speech-to-text job.

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

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

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

        Nr   r   r   r   r   r   6  r   zSpeechToTextJob.__init__r   c                 C   r   r   r   r   r   r   r   r
   K  r   zSpeechToTextJob.job_idr   r   r   c              
   C   s   | j j| jdd |D d}tj|d}tj|dQ}|D ]E}tj|}|j	| j
}t|d}	|j||	dddd	}
W d
   n1 sFw   Y  |
jtjksW|
jtjk rbtd| d|
j qW d
   dS 1 snw   Y  dS )r   c                 S   r    r   r!   r%   r   r   r   r(   j  r)   z0SpeechToTextJob.upload_files.<locals>.<listcomp>r*   r,   r-   r/   r.   r0   r1   Nr4   r5   T)r   r6   r   r7   r8   Clientr"   r#   r$   r:   r;   r<   r?   rA   r   rB   rC   rD   )r   r   r   rE   rF   r   r#   rH   rI   rJ   rM   r   r   r   rN   V  s8   

zSpeechToTextJob.upload_filesrO   rP   rQ   c                 C   s\   t  }	 |  }|j }|dv r|S t  | |kr(td| j d| dt | q)rR   T>   rS   rT   rU   rV   rW   )rZ   	monotonicr[   r\   r]   r^   r   r_   r`   r   r   r   rd     s   

z#SpeechToTextJob.wait_until_completec                 C   s   |   }dd |jpg D S )re   c                 S   rf   rg   rk   rn   r   r   r   r(     rp   z7SpeechToTextJob.get_output_mappings.<locals>.<listcomp>rq   rs   r   r   r   ru     s   	z#SpeechToTextJob.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 )rv   rw   r   Nry   rh   rx   rS   r{   r   r   r   r   r     s2   

z SpeechToTextJob.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   z4SpeechToTextJob.download_outputs.<locals>.<listcomp>r*   Tr   rj   r   r5   ri   r   r   N)ru   r   r   r   r"   r   r7   r   r   r;   r   rA   r   rB   rC   rD   r#   r   r<   r   r2   )r   r   r   r   r   r   r   rI   rM   r   rJ   r   r   r   r     s2   


z SpeechToTextJob.download_outputsc                 C   s   | j | jS )r   r   r   r   r   r   r[     s   zSpeechToTextJob.get_statusc                 C   s   | j j| jdS )r   r   r   r   r   r   r   ra     s   zSpeechToTextJob.startc                 C   s&   z|    W dS  tjy   Y dS w )r   TFr   r   r   r   r   r   )  s   zSpeechToTextJob.existsc                 C   s   |   j dv S )r   >   rS   rT   r   r   r   r   r   r   7     zSpeechToTextJob.is_completec                 C      |   j dkS )r   rT   r   r   r   r   r   r   A  r   zSpeechToTextJob.is_successfulc                 C   r   )r   rS   r   r   r   r   r   r   K  r   zSpeechToTextJob.is_failedNr   r   r   r   r   r   r   r   5  s>    
.
$
1*



r   )rX   r=   r"   rZ   r   r7   httpr   typesr   TYPE_CHECKINGr   r   r   r	   r   r   r   r   r   <module>   s      (