a
    pDfk                  -   @  sV  d Z ddlmZ ddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZmZmZmZmZ ddlmZ ddl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'm(Z(m)Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7 ddlm8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z? erddl@mAZA ddlBmCZC ddlDmEZE eeFeeGe/f ZHeeFeHf ZIdZJdZKdZLdZMd ZNd!ZOd"ZPd#ZQd$ZRd%ZSd&ZTd'ZUeJeJeJeJeJeJeKeKeKeKeKeKeKeLeMeMeNdd(d)d*d+d,d-eOeOePePePd.d/d0d1d2d3eQeQd4d5d6eReSeTeUd7,ZVeG d8d9 d9ZWG d:d; d;e'ZXdS )<zJ
The message module provides a low-level API for rendering chat messages.
    )annotationsN)	ExitStack)	dataclass)partial)BytesIO)NamedTemporaryFile)indent)	TYPE_CHECKINGAnyCallableClassVarDictIterableListOptionalUnion)ZoneInfo   )CDN_DISTget_dist_path)state)ColumnRow)PaneBaseReplacementPanepanel)PDFFileBaseImage	ImageBase)HTML	DataFrameHTMLBasePaneMarkdown)AudioVideo)ParamFunction)Viewable)Widget   )ChatCopyIconChatReactionIcons)Document)Model)Commu   🧑u   🤖u   ⚙️u   ❌u   ❓z {dist_path}assets/logo/gpt-3.svgz {dist_path}assets/logo/gpt-4.svgz"{dist_path}assets/logo/wolfram.svgz {dist_path}assets/logo/lumen.svgz${dist_path}assets/logo/holoviews.svgz!{dist_path}assets/logo/hvplot.svgz!{dist_path}images/icon-vector.svgu   👶u   👦u   🧒u   👧u   👨u   👩u   🤗u   🧮u   🦜u   📄u   🛠️u   🌐u   🦙u   🐪u   📊),clientZcustomerZemployeeZhumanZpersonuserZagentZaiZ	assistantZbotZchatbotmachineZrobotsystem	exceptionerrorhelpZadultZbabyZboychildZgirlZmanZwomanZchatgptZgpt3Zgpt4ZdalleZopenaiZhuggingfaceZ
calculatorZ	langchainZ	retrieverZtoolZ
translatorZwolframzwolfram alphaZllamaZllama2ZplotZlumenZ	holoviewsZhvplotr   c                   @  s*   e Zd ZU dZded< ded< ded< dS )_FileInputMessagea  
    A dataclass to hold the contents of a file input message.

    Parameters
    ----------
    contents : bytes
        The contents of the file.
    file_name : str
        The name of the file.
    mime_type : str
        The mime type of the file.
    bytescontentsstr	file_name	mime_typeN)__name__
__module____qualname____doc____annotations__ rB   rB   _/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/panel/chat/message.pyr7   t   s   
r7   c                      s  e Zd ZU dZejdeeee	fddZ
ejdddZejdgd	dZejed
dZejddZejddZejdddZejdddZejddZejedddZejddZejdddZejdddZej dddZ!ej dddZ"ej dddZ#ej dddZ$ej dd dZ%ej dd!dZ&ej'd"dZ(ejd#d$dZ)e* d%gZ+d&e,d'< dZ-d(e,d)< dz fd*d+	Z.d,d- Z/d.d/ Z0d{d0d1d1d2d3d4d5Z1d2d6d7d8Z2e3d9d6d:d;Z4d|d<d=d=d>d?d@dAdBZ5e6d2d2dCdDdEZ7d2dFdCdGdHZ8d0d2dIdJdKZ9dLdM Z:dNdO Z;dPdQ Z<e6dRdS Z=d}dTdUZ>dVd6dWdXZ?d~dYdZZ@d[d\ ZAdd]d^ZBejCd_d`ddadbdc ZDddde ZEddfd6 fdgdhZFdd2d1didjdkZGddldmdndodpdqZHddrdsdt fdudvZIdd1d1d2dwdxdyZJ  ZKS )ChatMessageu  
    A widget for displaying chat messages with support for various content types.

    This widget provides a structured view of chat messages, including features like:
    - Displaying user avatars, which can be text, emoji, or images.
    - Showing the user's name.
    - Displaying the message timestamp in a customizable format.
    - Associating reactions with messages and mapping them to icons.
    - Rendering various content types including text, images, audio, video, and more.

    Reference: https://panel.holoviz.org/reference/chat/ChatMessage.html

    :Example:

    >>> ChatMessage(object="Hello world!", user="New User", avatar="😊")
     a  
        The avatar to use for the user. Can be a single character
        text, an emoji, or anything supported by `pn.pane.Image`. If
        not set, checks if the user is available in the
        default_avatars mapping; else uses the first character of the
        name.)defaultclass_docNz
        A function that can lookup an `avatar` from a user name. The
        function signature should be `(user: str) -> Avatar`. If this
        is set, `default_avatars` is disregarded.)rF   rH   zchat-messagez0
        The CSS classes to apply to the widget.z
        A default mapping of user names to their corresponding avatars
        to use when the user is specified but the avatar is. You can
        modify, but not replace the dictionary.zQ
        A list of objects to display in the column of the footer of the message.)rH   zN
        A list of objects to display in the row of the header of the message.i  )r   N)rF   ZboundsFzO
        The message contents. Can be any Python object that panel can display.)
allow_refsrH   z1
        Reactions to associate with the message.zu
        A mapping of reactions to their reaction icons; if not provided
        defaults to `{"favorite": "heart"}`.)rG   rH   rI   zA
        Timestamp of the message. Defaults to the creation time.z%H:%MzThe timestamp format.a*  
        The timezone to used for the creation timestamp; only applicable
        if timestamp is not set. If None, tries to use pn.state.browser_info.timezone,
        else, the default tz of datetime.datetime.now(); see `zoneinfo.available_timezones()`
        for a list of valid timezones.
    Tz4
         Whether to display the avatar of the user.z1
        Whether to display the name of the user.z9
        Whether to display the timestamp of the message.z/
        Whether to display the reaction icons.z*
        Whether to display the copy icon.z*
        Whether to show the activity dot.a,  
        A callable or list of callables that accept the object and return a
        Panel object to render the object. If a list is provided, will
        attempt to use the first renderer that does not raise an
        exception. If None, will attempt to infer the renderer
        from the object.ZUserz/
        Name of the user who sent the message.zcss/chat_message.csszClassVar[List[str]]_stylesheetszClassVar[bool]_updatesc                   s8  t  | _tddddgd| _|dd u rr|d}|d urFt|}ntjr`tjjr`ttjj}t	j	j
|d|d< |dd	d
i}t|trt|dd|dg d|d< d| _t jf d|i| tddddg| j| jj  d| _| j| jj  | j_| jj| ddd | jj| j_| js,|   |   d S )NF   z	copy-icon)visiblewidthheightcss_classes	timestamptimestamp_tz)tzreaction_iconsZfavoriteZheart	reactions)optionsrN   rO   valueTobject)rM   rN   rO   rP   stylesheets)rW   bidirectional)r   _exit_stackr*   chat_copy_icongetr   r   Zbrowser_infotimezonedatetimenow
isinstancedictr+   	_internalsuper__init__rJ   paramrY   rxrT   linkshow_reaction_iconsrM   avatar_update_avatar_build_layout)selfrX   paramsrS   rT   	__class__rB   rC   re      s:    






zChatMessage.__init__c              	     s  t ddg jj j jj  d _t  dddg j jj   jj	d d  _
} j jd   j _   t j jd	g j jj  d d
 _ j jd t  jjddg jj jd _ jg jj   j jg }t| j jj  ddgd}t  jj  jjdg jjd _t jj  jg  j jj  ddgd}t| j|dg j jj  d d
  _ } fdd jD } j jj  |d< t||fi | _!d S )Nu   ●zactivity-dot)rP   rM   rY   <   d   left)	max_widthrO   rP   rY   rM   sizing_moderj   center)rP   rY   ru   rX      name)rO   rP   rM   rY   stretch_widthheader)objectsrY   ru   rP   rQ   )rP   rM   footerrightc                   s4   i | ],}|t jv r|t jv r|d kr| j| qS )rx   )r'   rf   ).0prm   rB   rC   
<dictcomp>P  s   z-ChatMessage._build_layout.<locals>.<dictcomp>rY   )"r    rf   show_activity_dotrJ   rY   rg   Z_activity_dotr   _render_avatarshow_avatar	_left_colwatch_update_avatar_pane_create_panelrX   _object_panel_update_chat_copy_iconr   rT   _center_row_update_object_paner0   	show_userZ
_user_htmlheader_objectsr\   rQ   strftimetimestamp_formatshow_timestampZ_timestamp_htmlfooter_objectsZ
_right_col
_composite)rm   Zleft_colr   Z
header_rowZ
footer_colZ	right_colZviewable_paramsrB   r   rC   rl     s    	



zChatMessage._build_layoutc                 C  s&   |j }t|j}||s|s"|}|S )z
        Get the label for the object; defaults to specified object name;
        if unspecified, defaults to the type name.
        )rx   typer=   
startswith)rm   objlabel	type_namerB   rB   rC   _get_obj_labelW  s
    
zChatMessage._get_obj_labelr
   boolr:   )r   prefix_with_viewable_labelprefix_with_container_labelreturnc                   s  t |trt |tst fdd|D } rt|dkrX| d|d  dS td|dd	}| d
| dS ndd| dS |}t|dr|j	}nt|dr|j
}t|dst |trjd|  |S rt |tr|}| d|}|S )z?
        Recursively serialize the object to a string.
        c                 3  s   | ]}j | d V  qdS )r   r   N)_serialize_recursivelyr~   or   r   rm   rB   rC   	<genexpr>n  s   z5ChatMessage._serialize_recursively.<locals>.<genexpr>r)   (r   )z,
z    )prefixz(
z
)z, rW   rX   decodezhSerializing byte-like objects are not supported yet; using the label of the object as a placeholder for =)ra   r   r:   tuplelenr   r   joinhasattrrW   rX   r   rf   warningr'   )rm   r   r   r   contentZindented_contentstringr   rB   r   rC   r   d  s4    	



z"ChatMessage._serialize_recursively)r   c                 C  s   |   S )z;
        Serialize the message object to a string.
        )	serializer   rB   rB   rC   __str__  s    zChatMessage.__str__z	List[str]c                 C  s   g S NrB   r   rB   rB   rC   _synced_params  s    zChatMessage._synced_paramsr,   zModel | NonezComm | Noner-   )rH   rootparentcommr   c                 C  sX   | j ||||}|s8|jd jd }|jtt |_|p>|jd }||f| j|< |S )Nr   id)	r   
_get_modelchildrentextreplacer   r   refZ_models)rm   rH   r   r   r   modelrj   r   rB   rB   rC   r     s    zChatMessage._get_model)r0   r   c                 C  s   t dd|  S )zu
        Convert the user name to an alpha numeric string,
        removing all non-alphanumeric characters.
        z\W+rE   )resublower)r0   rB   rB   rC   _to_alpha_numeric  s    zChatMessage._to_alpha_numericAvatarc                   sJ     |}t }| j  fdd| D }|| jjt	dS )z1
        Lookup the avatar for the user.
        c                   s   i | ]\}}  ||qS rB   )r   )r~   keyrW   r   rB   rC   r     s   z.ChatMessage._avatar_lookup.<locals>.<dictcomp>)	dist_path)
r   DEFAULT_AVATARScopyupdatedefault_avatarsitemsr]   rj   formatr   )rm   r0   Zalpha_numeric_keyZupdated_avatarsrB   r   rC   _avatar_lookup  s    

zChatMessage._avatar_lookup)r9   r<   c                 C  s  t }|dkr*| jt|}ttdd}n|drh| jtddd}|| |	d |j
}t}n|d	r| jt|}t}n|d
r| jt|}t}nl|drddl}t|}||}W d   n1 s0    Y  t}n"|drt|tr|d}||fS )zG
        Determine the renderer to use based on the mime type.
        zapplication/pdfT)embedzaudio/z.mp3F)suffixdeleter   zvideo/zimage/z/csvNr   zutf-8)_panelr[   enter_contextr   r   r   r   r   writeseekrx   r$   r%   r   endswithZpandasZread_csvr!   ra   r8   r   )rm   r9   r<   rendererfilepdbufrB   rB   rC   _select_renderer  s6    







(
zChatMessage._select_rendererc                   sX   t  dr*fdd jD  jd d < nt   fddjj D  j  _ S )Nr{   c                   s   g | ]}  |qS rB   )_include_stylesheets_inplacer   r   rB   rC   
<listcomp>  s   z<ChatMessage._include_stylesheets_inplace.<locals>.<listcomp>c                   s   g | ]}| j vr|qS rB   )rY   )r~   Z
stylesheet)r   rB   rC   r     s   
)r   r{   r   rJ   rY   )rm   r   rB   )r   rm   rC   r     s    



z(ChatMessage._include_stylesheets_inplacec                   s   t |dr* fdd|jD |jd d < nt|}t|toFt|t }|jsR|sV|S tt|j	dkrg dd |jD d|_d |_
|S )Nr{   c                   s   g | ]}  |qS rB   )"_include_message_css_class_inplacer   r   rB   rC   r     s   zBChatMessage._include_message_css_class_inplace.<locals>.<listcomp>r   c                 s  s   | ]}|d kr|V  qdS )messageNrB   )r~   cssrB   rB   rC   r         zAChatMessage._include_message_css_class_inplace.<locals>.<genexpr>r   )r   r{   r   ra   r"   r   rP   r   r:   rX   ru   )rm   r   	is_markuprB   r   rC   r     s    


z.ChatMessage._include_message_css_class_inplacec                 K  st   |  | t|tot|t }|r0| | n4|jdu rH|jsHd|d< |jdu rdt|tsdd|d< |j	
| dS )z?
        Set the sizing mode and height of the object.
        Nry   ru   i  rO   )r   ra   r"   r   r   ru   rN   rO   r&   rf   r   )rm   r   rn   r   rB   rB   rC   _set_params
  s    
zChatMessage._set_paramsc                 C  s   t | tot| tS r   )ra   r   
issubclassr(   )r   rB   rB   rC   _is_widget_renderer  s    zChatMessage._is_widget_rendererc           	   	   C  sv  t |tr(d| _| | | | |S d}t |trT|j}|j}| ||\}}n>z*ddl	}|j
|dd}| ||\}}W n ty   Y n0 | j pg }|dur|| |D ]N}z4| |r||d}n||}t |trW  q8W q ty   Y q0 qt |tr0t |tr0| j||d |S t|}| | t|t|u rl| jrlt|| |S d| _|S )z7
        Create a panel object from the value.
        FNr   T)mime)rW   )rX   )ra   r'   rc   r   r   r7   r9   r<   r   magicfrom_buffer	Exception	renderersr   appendr   r#   r:   r   r   r   r   Z_recursive_update)	rm   rW   oldr   r9   r<   r   r   object_panelrB   rB   rC   r     sL    







zChatMessage._create_panelzHTML | Imagec                 C  s   | j }|s| jr| jd }ddgi}t|trd|}|dg |j |d< |jddd |j| njt|tt	fst
|dkrt|fi |}n>zt|fddd|}W n" ty   t|fi |}Y n0 |S )zI
        Render the avatar pane as some HTML text or Image pane.
        r   rP   rj   #   )rN   rO   r)   )rj   r0   ra   r   r]   rP   r   rf   r   r8   r   r    r   
ValueError)rm   rj   Zavatar_paramsZavatar_panerB   rB   rC   r   Q  s2    





zChatMessage._render_avatarc                 C  st   |   }t| jd }t|}t|jttfs6||urH|g| jd d < n(|j }|d= | jd jj	f i | d S )Nr   rx   )
r   r   r   ra   r   r    r   rf   valuesr   )rm   eventZ
new_avatarZold_typenew_typern   rB   rB   rC   r   o  s    
zChatMessage._update_avatar_panec                 C  s   dS )z4
        Internals will be updated inplace.
        NrB   )rm   r   Z
old_modelsrB   rB   rC   _updatez  s    zChatMessage._updatec                 C  s:   | j }| j| j|d | _ }||ur.|| jd< |   d S )N)r   r   )r   r   rX   r   r   )rm   r   r   newrB   rB   rC   r     s
    
zChatMessage._update_object_paneavatar_lookupr0   )r   c                 C  s(   | j r|  | j| _n| | j| _dS )z
        Update the avatar based on the user name.

        We do not use on_init here because if avatar is set,
        we don't want to override the provided avatar.

        However, if the user is updated, we want to update the avatar.
        N)r   r0   rj   r   r   rB   rB   rC   rk     s    
zChatMessage._update_avatarc                 C  s^   | j }t|tr|j}nt|tr(|j}t|trJ| jrJ|| j_d| j_	nd| j_d| j_	d S )NTrE   F)
r   ra   r"   rX   r(   rW   r:   show_copy_iconr\   rM   )rm   r   rB   rB   rC   r     s    


z"ChatMessage._update_chat_copy_iconNonec                   s   | j | t |S )z)
        Cleanup the exit stack.
        )r   _cleanuprd   )rm   r   ro   rB   rC   r     s    zChatMessage._cleanup)tokenr   c           	      C  s   d}d}| }d}| j }|du r"d}t|tr6t|tr|}t|dr\|}d}|j| }d}q"t|drrd}|j }q"t|drd}|j}q"|dur"|}d}|d8 }q"|r|n|| }t||| dS )a  
        Updates the message with the new token traversing the object to
        allow updating nested objects. When traversing a nested Panel
        the last object that supports rendering strings is updated, e.g.
        in a layout of `Column(Markdown(...), Image(...))` the Markdown
        pane is updated.

        Arguments
        ---------
        token: str
          The token to stream to the text pane.
        replace: bool (default=False)
            Whether to replace the existing text.
        NrX   rE   r{   rW   r)   )rX   ra   r:   r   r   r{   rW   setattr)	rm   r   r   iZparent_panelr   attrr   r9   rB   rB   rC   stream  s4    




zChatMessage.streamzdict | ChatMessage | Anyz
str | Nonezstr | bytes | BytesIO | None)rW   r0   rj   c                 C  s~   i }t |tr2|| |r$||d< |rh||d< n6t |tr`|dusL|durTtd|j }n||d< | jjf i | dS )a  
        Updates the message with a new value, user and avatar.

        Arguments
        ---------
        value : ChatMessage | dict | Any
            The message contents to send.
        user : str | None
            The user to send as; overrides the message message's user if provided.
        avatar : str | bytes | BytesIO | None
            The avatar to use; overrides the message message's avatar if provided.
        r0   rj   NzfCannot set user or avatar when explicitly sending a ChatMessage. Set them directly on the ChatMessage.rX   )ra   rb   r   rD   r   rf   r   )rm   rW   r0   rj   ZupdatesrB   rB   rC   r     s    



zChatMessage.updatez+Optional[type | Callable[[Viewable], bool]]zList[Viewable])selectorr   c                   s   t  || j| S r   )rd   selectr   )rm   r   ro   rB   rC   r     s    zChatMessage.select)r   r   r   c                 C  s   | j | j||dS )a  
        Format the object to a string.

        Arguments
        ---------
        obj : Any
            The object to format.
        prefix_with_viewable_label : bool
            Whether to include the name of the Viewable, or type
            of the viewable if no name is specified.
        prefix_with_container_label : bool
            Whether to include the name of the container, or type
            of the container if no name is specified.

        Returns
        -------
        str
            The serialized string.
        r   )r   rX   )rm   r   r   rB   rB   rC   r     s
    zChatMessage.serialize)N)TT)NNN)N)N)N)N)F)NN)N)TT)Lr=   r>   r?   r@   rf   ZClassSelectorr:   r   r8   r   rj   r   r   r   rP   r   r   r   r   r   ZIntegerrt   	ParameterrX   rU   r+   rT   DaterQ   Stringr   rR   Booleanr   r   r   ri   r   r   ZHookListr   r0   r   rJ   rA   rK   re   rl   r   r   r   propertyr   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   dependsrk   r   r   r   r   r   r   __classcell__rB   rB   ro   rC   rD      s   
J  3  %

3


.  %   rD   )Yr@   
__future__r   r_   r   
contextlibr   Zdataclassesr   	functoolsr   ior   tempfiler   textwrapr   typingr	   r
   r   r   r   r   r   r   r   Zzoneinfor   rf   Zio.resourcesr   r   Zio.stater   Zlayoutr   r   Z	pane.baser   r   r   r   Z
pane.imager   r   r   r   Zpane.markupr    r!   r"   r#   Z
pane.mediar$   r%   r&   Zviewabler'   Zwidgets.baser(   Ziconr*   r+   Zbokeh.documentr,   Zbokeh.modelr-   Zpyviz_commsr.   r:   r8   r   Z
AvatarDictZ	USER_LOGOZASSISTANT_LOGOZSYSTEM_LOGOZ
ERROR_LOGOZ	HELP_LOGOZ
GPT_3_LOGOZ
GPT_4_LOGOZWOLFRAM_LOGOZ
LUMEN_LOGOZHOLOVIEWS_LOGOZHVPLOT_LOGOZ
PANEL_LOGOr   r7   rD   rB   rB   rB   rC   <module>   s   ,7