
    qi                         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	m
Z
mZmZ ddlmZ ddlmZmZ e G d d	             Z G d
 de      Zy)a  Base object class providing event handling and lifecycle management.

This module provides the foundational BaseObject class that offers common
functionality including unique identification, naming, event handling,
and async cleanup for all Pipecat components.
    N)ABC)	dataclass)AnyDictListOptional)logger)	obj_countobj_idc                   6    e Zd ZU dZeed<   ee   ed<   eed<   y)EventHandlera  Data class to store event handlers information.

    This data class stores the event name, a list of handlers to run for this
    event, and whether these handlers will be executed in a task.

    Parameters:
        name (str): The name of the event handler.
        handlers (List[Any]): A list of functions to be called when this event is triggered.
        is_sync (bool): Indicates whether the functions are executed in a task.

    namehandlersis_syncN)	__name__
__module____qualname____doc__str__annotations__r   r   bool     K/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/utils/base_object.pyr   r      s    
 I3iMr   r   c                       e Zd ZdZdddee   fdZedefd       Z	edefd       Z
d	 Zd
efdZd
efdZdd
edefdZd
efdZd
efdZdej&                  fdZd Zy)
BaseObjecta!  Abstract base class providing common functionality for Pipecat objects.

    Provides unique identification, naming, event handling capabilities,
    and async lifecycle management for all Pipecat components. All major
    classes in the framework should inherit from this base class.
    Nr   r   c                    t               | _        |xs$ | j                  j                   dt	        |        | _        i | _        t               | _        y)a  Initialize the base object.

        Args:
            name: Optional custom name for the object. If not provided,
                generates a name using the class name and instance count.
            **kwargs: Additional arguments passed to parent class.
        #N)	r   _id	__class__r   r
   _name_event_handlersset_event_tasks)selfr   kwargss      r   __init__zBaseObject.__init__5   sJ     K 7 78)D/9JK
 9;
  Er   returnc                     | j                   S )zGet the unique identifier for this object.

        Returns:
            The unique integer ID assigned to this object instance.
        )r    r&   s    r   idzBaseObject.idH   s     xxr   c                     | j                   S )zGet the name of this object.

        Returns:
            The object's name, either custom-provided or auto-generated.
        )r"   r+   s    r   r   zBaseObject.nameQ   s     zzr   c                    K   | j                   rWt        | j                    \  }}t        j                  |  dt	        |       d       t        j                  |       d{    yy7 w)zClean up resources and wait for running event handlers to complete.

        This method should be called when the object is no longer needed.
        It waits for all currently executing event handler tasks to finish
        before returning.
        z&: waiting on event handlers to finish z...N)r%   zipr	   debuglistasynciowait)r&   event_namestaskss      r   cleanupzBaseObject.cleanupZ   sc      !$d&7&7!8KLLD6!G[HYGZZ]^_,,u%%%  &s   AA) A'!A)
event_namec                       fd}|S )zDecorator for registering event handlers.

        Args:
            event_name: The name of the event to handle.

        Returns:
            The decorator function that registers the handler.
        c                 ,    j                  |        | S )N)add_event_handler)handlerr7   r&   s    r   	decoratorz+BaseObject.event_handler.<locals>.decoratorp   s    "":w7Nr   r   )r&   r7   r<   s   `` r   event_handlerzBaseObject.event_handlerf   s    	 r   c                     || j                   v r)| j                   |   j                  j                  |       yt        j                  |  d| d       y)zAdd an event handler for the specified event.

        Args:
            event_name: The name of the event to handle.
            handler: The function to call when the event occurs.
                Can be sync or async.
        : event handler z not registeredN)r#   r   appendr	   warning)r&   r7   r;   s      r   r:   zBaseObject.add_event_handlerv   sK     ---  ,55<<WENNdV#3J<OPr   syncc                     || j                   vrt        |g |      | j                   |<   yt        j                  |  d| d       y)zRegister an event handler type.

        Args:
            event_name: The name of the event type to register.
            sync: Whether this event handler will be executed in a task.
        )r   r   r   r?   z already registeredN)r#   r   r	   rA   )r&   r7   rB   s      r   _register_event_handlerz"BaseObject._register_event_handler   sK     T111/;"d0D  , NNdV#3J<?RSTr   c                   K   || j                   vry| j                   |   }|j                  D ]  }|j                  r* | j                  |j                  |g|i | d{    9t        j                   | j                  |j                  |g|i |      }| j                  j                  ||f       |j                  | j                          y7 tw)a  Call all registered handlers for the specified event.

        Args:
            event_name: The name of the event to trigger.
            *args: Positional arguments to pass to event handlers.
            **kwargs: Keyword arguments to pass to event handlers.
        N)r#   r   r   _run_handlerr   r2   create_taskr%   addadd_done_callback_event_task_finished)r&   r7   argsr'   r=   r;   tasks          r   _call_event_handlerzBaseObject._call_event_handler   s      T111,,Z8$-- 	BG$$'d''(:(:GUdUfUUU
 **%D%%m&8&8'SDSFS
 !!%%z4&89 &&t'@'@A!	B Vs   AC C!A5Cc                 `  K   	 t        j                  |      r || g|i | d{    y || g|i | y7 # t        $ re}t        j                  |j
                        }|d   }t        j                  |  d| d|j                   d|j                   d| 	       Y d}~yd}~ww xY ww)a  Execute all handlers for an event.

        Args:
            event_name: The event name for this handler.
            handler: The handler function to run.
            *args: Positional arguments to pass to handlers.
            **kwargs: Keyword arguments to pass to handlers.
        Nz': uncaught exception in event handler 'z' (:z): )
inspectiscoroutinefunction	Exception	traceback
extract_tb__traceback__r	   errorfilenamelineno)r&   r7   r;   rK   r'   etblasts           r   rF   zBaseObject._run_handler   s     
	**73d4T4V444.t.v. 5  	%%aoo6Bb6DLL&?
|3t}}o]^_c_j_j^kknopnqr 	sA   B.$= ;= B.= B.= 	B+AB&!B.&B++B.rL   c                     t        fd| j                  D        d      }|r| j                  j                  |       yy)zClean up completed event handler tasks.

        Args:
            task: The completed asyncio Task to remove from tracking.
        c              3   4   K   | ]  }|d    k(  s|  yw)   Nr   ).0trL   s     r   	<genexpr>z2BaseObject._event_task_finished.<locals>.<genexpr>   s     Ma!Ms   N)nextr%   discard)r&   rL   tuple_to_removes    ` r   rJ   zBaseObject._event_task_finished   s9     M4+<+<MtT%%o6 r   c                     | j                   S )zReturn the string representation of this object.

        Returns:
            The object's name as its string representation.
        r   r+   s    r   __str__zBaseObject.__str__   s     yyr   )F)r   r   r   r   r   r   r(   propertyintr,   r   r6   r=   r:   r   rD   rM   rF   r2   TaskrJ   rg   r   r   r   r   r   -   s     15 " "& C   c  
&  QC QU# UT UBC B>S *7 7r   r   )r   r2   rQ   rT   abcr   dataclassesr   typingr   r   r   r   logurur	   pipecat.utils.utilsr
   r   r   r   r   r   r   <module>rp      sN        ! , ,  1   $h hr   