Ë
    ·ªgf!  ã                  ó˜   — U 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
mZ  ee«      Zded<   dd	„Z G d
„ d«      Z G d„ d«      Zy)z@Provides global MediaFileManager object as `media_file_manager`.é    )ÚannotationsN)ÚFinal)Ú
get_logger)ÚMediaFileKindÚMediaFileStorager   Ú_LOGGERc                 ó:   — ddl m}   | «       }|€y|j                  S )z'Get the active AppSession's session_id.r   )Úget_script_run_ctxÚdontcare)Ú7streamlit.runtime.scriptrunner_utils.script_run_contextr
   Ú
session_id)r
   Úctxs     úY/var/www/openai/venv/lib/python3.12/site-packages/streamlit/runtime/media_file_manager.pyÚ_get_session_idr      s%   € õñ Ó
€CØ
€{ð à~‰~Ðó    c                  ó\   — e Zd ZdZej
                  fdd„Zedd„«       Zed	d„«       Z	d
d„Z
y)ÚMediaFileMetadatazBMetadata that the MediaFileManager needs for each file it manages.c                ó    — || _         d| _        y ©NF)Ú_kindÚ_is_marked_for_delete)ÚselfÚkinds     r   Ú__init__zMediaFileMetadata.__init__0   s   € ØˆŒ
Ø%*ˆÕ"r   c                ó   — | j                   S ©N)r   ©r   s    r   r   zMediaFileMetadata.kind4   s   € àz‰zÐr   c                ó   — | j                   S r   ©r   r   s    r   Úis_marked_for_deletez&MediaFileMetadata.is_marked_for_delete8   s   € à×)Ñ)Ð)r   c                ó   — d| _         y )NTr   r   s    r   Úmark_for_deletez!MediaFileMetadata.mark_for_delete<   s
   € Ø%)ˆÕ"r   N)r   r   )Úreturnr   )r#   Úbool©r#   ÚNone)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚMEDIAr   Úpropertyr   r    r"   © r   r   r   r   -   s@   „ ÙLà-:×-@Ñ-@ô +ð òó ðð ò*ó ð*ô*r   r   c                  ó^   — e Zd ZdZd	d„Zd
d„Zdd„Zdd„Zddd„Z	 	 d	 	 	 	 	 	 	 	 	 	 	 dd„Z	y)ÚMediaFileManageraÍ  In-memory file manager for MediaFile objects.

    This keeps track of:
    - Which files exist, and what their IDs are. This is important so we can
      serve files by ID -- that's the whole point of this class!
    - Which files are being used by which AppSession (by ID). This is
      important so we can remove files from memory when no more sessions need
      them.
    - The exact location in the app where each file is being used (i.e. the
      file's "coordinates"). This is is important so we can mark a file as "not
      being used by a certain session" if it gets replaced by another file at
      the same coordinates. For example, when doing an animation where the same
      image is constantly replace with new frames. (This doesn't solve the case
      where the file's coordinates keep changing for some reason, though! e.g.
      if new elements keep being prepended to the app. Unlikely to happen, but
      we should address it at some point.)
    c                óŽ   — || _         i | _        t        j                  t        «      | _        t        j                  «       | _        y r   )	Ú_storageÚ_file_metadataÚcollectionsÚdefaultdictÚdictÚ_files_by_session_and_coordÚ	threadingÚLockÚ_lock)r   Ústorages     r   r   zMediaFileManager.__init__S   s;   € ØˆŒð =?ˆÔô ×#Ñ#¤DÓ)ð 	Ô(ô —^‘^Ó%ˆ
r   c                óÈ   — t        | j                  j                  «       «      }| j                  j	                  «       D ]!  }|j                  |j	                  «       «       Œ# |S )zãCompute the set of files that are stored in the manager, but are
        not referenced by any active session. These are files that can be
        safely deleted.

        Thread safety: callers must hold `self._lock`.
        )Úsetr2   Úkeysr6   ÚvaluesÚdifference_update)r   Úfile_idsÚsession_file_ids_by_coords      r   Ú_get_inactive_file_idsz'MediaFileManager._get_inactive_file_idsc   sY   € ô t×*Ñ*×/Ñ/Ó1Ó2ˆð *.×)IÑ)I×)PÑ)PÖ)RÐ%Ø×&Ñ&Ð'@×'GÑ'GÓ'IÕJð *Sð ˆr   c                ó°  — t         j                  d«       | j                  5  | j                  «       D ]Œ  }| j                  |   }|j
                  t        j                  k(  r| j                  |«       ŒA|j
                  t        j                  k(  sŒ_|j                  r| j                  |«       Œ}|j                  «        ŒŽ 	 ddd«       y# 1 sw Y   yxY w)zuRemove all files that are no longer referenced by any active session.

        Safe to call from any thread.
        zRemoving orphaned files...N)r   Údebugr9   rB   r2   r   r   r+   Ú_delete_fileÚDOWNLOADABLEr    r"   )r   Úfile_idÚfiles      r   Úremove_orphaned_filesz&MediaFileManager.remove_orphaned_filess   sš   € ô
 	‰Ð2Ô3àZ‹ZØ×6Ñ6Ö8Ø×*Ñ*¨7Ñ3Ø—9‘9¤× 3Ñ 3Ò3Ø×%Ñ% gÕ.Ø—Y‘Y¤-×"<Ñ"<Ó<Ø×0Ò0Ø×)Ñ)¨'Õ2à×,Ñ,Õ.ñ 9÷ Z‰Zús   ¢A/CÂ0CÃCc                ó€   — t         j                  d|«       | j                  j                  |«       | j                  |= y)zœDelete the given file from storage, and remove its metadata from
        self._files_by_id.

        Thread safety: callers must hold `self._lock`.
        zDeleting File: %sN)r   rD   r1   Údelete_filer2   )r   rG   s     r   rE   zMediaFileManager._delete_file…   s3   € ô 	‰Ð)¨7Ô3Ø‰×!Ñ! 'Ô*Ø×Ñ Ñ(r   Nc                ó–  — |€
t        «       }t        j                  d|«       | j                  5  || j                  v r| j                  |= ddd«       t        j                  d| j                  j                  «       «       t        j                  dt        | j                  «      t        | j                  «      «       y# 1 sw Y   ŒuxY w)a#  Remove the given session's file references.

        (This does not remove any files from the manager - you must call
        `remove_orphaned_files` for that.)

        Should be called whenever ScriptRunner completes and when a session ends.

        Safe to call from any thread.
        Nz*Disconnecting files for session with ID %szSessions still active: %rz"Files: %s; Sessions with files: %s)r   r   rD   r9   r6   r=   Úlenr2   )r   r   s     r   Úclear_session_refsz#MediaFileManager.clear_session_refs   s    € ð ÐÜ(Ó*ˆJä‰ÐBÀJÔOàZ‹ZØ˜T×=Ñ=Ñ=Ø×4Ñ4°ZÐ@÷ ô 	‰Ø'¨×)IÑ)I×)NÑ)NÓ)Pô	
ô 	‰Ø0Ü×#Ñ#Ó$Ü×0Ñ0Ó1õ	
÷ ˆZús   ¯B?Â?Cc                ój  — t        «       }| j                  5  |rt        j                  nt        j                  }| j
                  j                  ||||«      }t        |¬«      }	|	| j                  |<   || j                  |   |<   | j
                  j                  |«      cddd«       S # 1 sw Y   yxY w)a  Add a new MediaFile with the given parameters and return its URL.

        If an identical file already exists, return the existing URL
        and registers the current session as a user.

        Safe to call from any thread.

        Parameters
        ----------
        path_or_data : bytes or str
            If bytes: the media file's raw data. If str: the name of a file
            to load from disk.
        mimetype : str
            The mime type for the file. E.g. "audio/mpeg".
            This string will be used in the "Content-Type" header when the file
            is served over HTTP.
        coordinates : str
            Unique string identifying an element's location.
            Prevents memory leak of "forgotten" file IDs when element media
            is being replaced-in-place (e.g. an st.image stream).
            coordinates should be of the form: "1.(3.-14).5"
        file_name : str or None
            Optional file_name. Used to set the filename in the response header.
        is_for_static_download: bool
            Indicate that data stored for downloading as a file,
            not as a media for rendering at page. [default: False]

        Returns
        -------
        str
            The url that the frontend can use to fetch the media.

        Raises
        ------
        If a filename is passed, any Exception raised when trying to read the
        file will be re-raised.
        )r   N)r   r9   r   rF   r+   r1   Úload_and_get_idr   r2   r6   Úget_url)
r   Úpath_or_dataÚmimetypeÚcoordinatesÚ	file_nameÚis_for_static_downloadr   r   rG   Úmetadatas
             r   ÚaddzMediaFileManager.add¬   sž   € ô\ %Ó&ˆ
àZ‹Zñ *ô ×*Ò*ä"×(Ñ(ð ð
 —m‘m×3Ñ3Ø˜h¨¨ióˆGô )¨dÔ3ˆHà+3ˆD×Ñ Ñ(ØHOˆD×,Ñ,¨ZÑ8¸ÑEà—=‘=×(Ñ(¨Ó1÷ ZŠZús   —BB)Â)B2)r:   r   )r#   zset[str]r%   )rG   Ústrr#   r&   r   )r   ú
str | Noner#   r&   r   )rR   zbytes | strrS   rY   rT   rY   rU   rZ   rV   r$   r#   rY   )
r'   r(   r)   r*   r   rB   rI   rE   rN   rX   r-   r   r   r/   r/   @   sh   „ ñó$&ó ó /ó$)ô
ðD !%Ø',ð>2à!ð>2ð ð>2ð ð	>2ð
 ð>2ð !%ð>2ð 
ô>2r   r/   )r#   rY   )r*   Ú
__future__r   r3   r7   Útypingr   Ústreamlit.loggerr   Ú$streamlit.runtime.media_file_storager   r   r'   r   Ú__annotations__r   r   r/   r-   r   r   Ú<module>r`      sG   ðò Gå "ã Û Ý å 'ß Pá˜HÓ%€ˆÓ %ó÷ *ñ *÷&j2ò j2r   