o
    i(                     @  s   d dl mZ d dlZd dlZd dlmZmZmZ d dlm	Z	 d dl
mZmZ d dlmZ ddlmZmZ dd	lmZ d
Ze	G dd dZeddZG dd dZdS )    )annotationsN)Callable	GeneratorSequence)	dataclass)AnyLiteral)context   )llmutils)loggerg      @c                   @  s   e Zd ZU ded< dS )InputDetailszLiteral['text', 'audio']modalityN)__name__
__module____qualname____annotations__ r   r   d/var/www/html/livekit_bhavya/venv/lib/python3.10/site-packages/livekit/agents/voice/speech_handle.pyr      s   
 r   audio)r   c                   @  s  e Zd ZdZ	 dZ	 dZ	 d\ddZedefd]ddZ	e
d^ddZe
d_ddZe
d`ddZe
d_ddZe
daddZe
dbddZe
dbdd Ze
dbd!d"Zejdcd$d"Ze
ddd&d'Zdbd(d)Zd*d+ded-d.Zdfd/d0Zdgd2d3Zdhd6d7Zdhd8d9Zdid<d=Zdjd>d?ZdkdAdBZdkdCdDZdldGdHZdfdIdJZ dfdKdLZ!dfdMdNZ"dmdndQdRZ#dfdSdTZ$dfdUdVZ%dfdWdXZ&dfdYdZZ'd[S )oSpeechHandler      
   	speech_idstrallow_interruptionsboolinput_detailsr   returnNonec                  s   | _ | _| _tjd    _tjd    _tjd    _t  _	g  _
g  _g  _d _d  _d  _t  _t  _d fdd} j| d  _d S )	N   _asyncio.Future[None]r   r    c                   sX   t  jD ]$}z|  W q ty) } ztjd| |d W Y d }~qd }~ww d S )Nzerror in done_callback: exc_info)list_done_callbacks	Exceptionr   warning)r"   cbeselfr   r   _on_done:   s    z'SpeechHandle.__init__.<locals>._on_done)r"   r#   r   r    )_id_allow_interruptions_input_detailsasyncioFuture_interrupt_fut	_done_fut_scheduled_futEvent_authorize_event_generations_tasks_chat_items
_num_steps_agent_turn_context_interrupt_timeout_handleset_item_added_callbacksr'   add_done_callback_maybe_run_final_output)r-   r   r   r   r.   r   r,   r   __init__!   s$   

zSpeechHandle.__init__Tc                 C  s   t td| |dS )Nspeech_)r   r   r   )r   r   	shortuuid)r   r   r   r   r   createD   s
   zSpeechHandle.createintc                 C     | j S N)r<   r,   r   r   r   	num_stepsO      zSpeechHandle.num_stepsc                 C  rH   rI   )r/   r,   r   r   r   idS   rK   zSpeechHandle.idc                 C  rH   rI   )r1   r,   r   r   r   r   W   rK   zSpeechHandle.input_detailsc                 C  s   | j  d| j S )Nr"   )r/   r<   r,   r   r   r   _generation_id[   s   zSpeechHandle._generation_id
str | Nonec                 C  s$   | j dkrd S | j d| j d  S )Nr!   r"   )r<   r/   r,   r   r   r   _parent_generation_id_   s   
z"SpeechHandle._parent_generation_idc                 C  
   | j  S rI   )r6   doner,   r   r   r   	schedulede      
zSpeechHandle.scheduledc                 C  rP   rI   )r4   rQ   r,   r   r   r   interruptedi   rS   zSpeechHandle.interruptedc                 C  rH   rI   )r0   r,   r   r   r   r   m   rK   z SpeechHandle.allow_interruptionsvaluec                 C  s   | j r	|s	td|| _dS )a  Allow or disallow interruptions on this SpeechHandle.

        When set to False, the SpeechHandle will no longer accept any incoming
        interruption requests until re-enabled. If the handle is already
        interrupted, clearing interruptions is not allowed.

        Args:
            value (bool): True to allow interruptions, False to disallow.

        Raises:
            RuntimeError: If attempting to disable interruptions when already interrupted.
        zPCannot set allow_interruptions to False, the SpeechHandle is already interruptedN)rT   RuntimeErrorr0   )r-   rU   r   r   r   r   q   s
   

list[llm.ChatItem]c                 C  rH   rI   )r;   r,   r   r   r   
chat_items   rK   zSpeechHandle.chat_itemsc                 C  rP   rI   )r5   rQ   r,   r   r   r   rQ      s   
zSpeechHandle.doneF)forcerY   c                C  s   |s	| j s	td|   | S )zInterrupt the current speech generation.

        Raises:
            RuntimeError: If this speech handle does not allow interruptions.

        Returns:
            SpeechHandle: The same speech handle that was interrupted.
        z3This generation handle does not allow interruptions)r0   rV   _cancel)r-   rY   r   r   r   	interrupt   s   
	zSpeechHandle.interruptc                   s`   ddl m} t  }r%||}|r%|jr%|j| kr%td|jj dt| j	I dH  dS )as  Waits for the entire assistant turn to complete playback.

        This method waits until the assistant has fully finished speaking,
        including any finalization steps beyond initial response generation.
        This is appropriate to call when you want to ensure the speech output
        has entirely played out, including any tool calls and response follow-ups.r!   )_get_activity_task_infozMcannot call `SpeechHandle.wait_for_playout()` from inside the function tool `u<  ` that owns this SpeechHandle. This creates a circular wait: the speech handle is waiting for the function tool to complete, while the function tool is simultaneously waiting for the speech handle.
To wait for the assistant’s spoken response prior to running this tool, use `RunContext.wait_for_playout()` instead.N)
agentr\   r2   current_taskfunction_callspeech_handlerV   nameshieldr5   )r-   r\   taskinfor   r   r   wait_for_playout   s   	zSpeechHandle.wait_for_playout#Generator[None, None, SpeechHandle]c                   s   d fdd}|   S )Nr   r   c                     s      I d H   S rI   )re   r   r,   r   r   _await_impl   s   z+SpeechHandle.__await__.<locals>._await_implr   r   )	__await__)r-   rg   r   r,   r   ri      s   
zSpeechHandle.__await__callbackCallable[[SpeechHandle], None]c                 C  s,   |   rt ||  d S | j| d S rI   )rQ   r2   get_running_loop	call_soonr'   addr-   rj   r   r   r   rA      s   zSpeechHandle.add_done_callbackc                 C     | j | d S rI   )r'   discardro   r   r   r   remove_done_callback      z!SpeechHandle.remove_done_callbackaw!list[asyncio.futures.Future[Any]]c                   s   t jdd |D ddi}|| jh}t j|t jdI d H \}}||v rFtt j |  |I d H  W d    d S 1 s?w   Y  d S d S )Nc                 S  s   g | ]}t |qS r   )r2   rb   ).0futr   r   r   
<listcomp>   s    z8SpeechHandle.wait_if_not_interrupted.<locals>.<listcomp>return_exceptionsT)return_when)	r2   gatherr4   waitFIRST_COMPLETED
contextlibsuppressCancelledErrorcancel)r-   rt   
gather_futfsr"   pendingr   r   r   wait_if_not_interrupted   s   
"z$SpeechHandle.wait_if_not_interruptedc                   sF      r S  j  s! jd  d fdd}t t| _ S )Nr   r    c                    s6   t jd jtdd  jD ]} |   q   d S )NzNspeech not done in time after interruption, cancelling the speech arbitrarily.)r   timeout)extra)r   errorr/   INTERRUPTION_TIMEOUTr:   r   
_mark_done)rc   r,   r   r   _on_timeout   s   


z)SpeechHandle._cancel.<locals>._on_timeoutr   r    )rQ   r4   
set_resultr2   get_event_loop
call_laterr   r>   )r-   r   r   r,   r   rZ      s   
	zSpeechHandle._cancelCallable[[llm.ChatItem], Any]c                 C  rp   rI   )r@   rn   ro   r   r   r   _add_item_added_callback   rs   z%SpeechHandle._add_item_added_callbackc                 C  rp   rI   )r@   rq   ro   r   r   r   _remove_item_added_callback   rs   z(SpeechHandle._remove_item_added_callbackitemsSequence[llm.ChatItem]c                 C  sn   |D ]2}t | jD ]$}z|| W q	 ty- } ztjd| |d W Y d }~q	d }~ww | j| qd S )Nzerror in item_added_callback: r$   )r&   r@   r(   r   r)   r;   append)r-   r   itemr*   r+   r   r   r   _item_added   s    zSpeechHandle._item_addedc                 C  s&   t jd   }| j| | j  d S rI   )r2   r3   r9   r   r8   r?   )r-   rw   r   r   r   _authorize_generation   s   z"SpeechHandle._authorize_generationc                 C  s   | j   d S rI   )r8   clearr,   r   r   r   _clear_authorization   s   z!SpeechHandle._clear_authorizationc                   s   | j  I d H  d S rI   )r8   r|   r,   r   r   r   _wait_for_authorization   s   z$SpeechHandle._wait_for_authorizationstep_idxc                   s*   | j stdt| j | I d H  d S )Nz@cannot use wait_for_generation: no active generation is running.)r9   rV   r2   rb   )r-   r   r   r   r   _wait_for_generation   s   z!SpeechHandle._wait_for_generationc                   s   t | jI d H  d S rI   )r2   rb   r6   r,   r   r   r   _wait_for_scheduled  s   z SpeechHandle._wait_for_scheduledc                 C  sP   | j stdttj | j d d  W d    d S 1 s!w   Y  d S )NzAcannot use mark_generation_done: no active generation is running.r   )r9   rV   r~   r   r2   InvalidStateErrorr   r,   r   r   r   _mark_generation_done  s
   "z"SpeechHandle._mark_generation_donec                 C  sh   t tj | jd  | jr|   W d    n1 sw   Y  | jd ur2| j	  d | _d S d S rI   )
r~   r   r2   r   r5   r   r9   r   r>   r   r,   r   r   r   r     s   


zSpeechHandle._mark_donec                 C  s>   t tj | jd  W d    d S 1 sw   Y  d S rI   )r~   r   r2   r   r6   r   r,   r   r   r   _mark_scheduled  s   "zSpeechHandle._mark_scheduledN)r   r   r   r   r   r   r   r    )r   r   r   r   r   r   )r   rG   )r   r   )r   r   )r   rN   )r   r   )rU   r   r   r    )r   rW   )rY   r   r   r   r   )r   rf   )rj   rk   r   r    )rt   ru   r   r    rh   )rj   r   r   r    )r   r   r   r    )r   )r   rG   r   r    )(r   r   r   SPEECH_PRIORITY_LOWSPEECH_PRIORITY_NORMALSPEECH_PRIORITY_HIGHrC   staticmethodDEFAULT_INPUT_DETAILSrF   propertyrJ   rL   r   rM   rO   rR   rT   r   setterrX   rQ   r[   re   ri   rA   rr   r   rZ   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      sf    
#


















r   )
__future__r   r2   r~   collections.abcr   r   r   dataclassesr   typingr   r   opentelemetryr	   otel_context r   r   logr   r   r   r   r   r   r   r   r   <module>   s    
