a
    ø£Beï  ã                   @   sH   d Z ddlZddlmZ ddlmZmZ ddlmZ G dd„ deƒZ	dS )	zF
Module that extracts attachments from notebooks into their own files
é    N)Ú	b64decode)ÚBoolÚUnicodeé   )ÚPreprocessorc                       s\   e Zd ZdZeddd�jdd�Zeddd�jdd�Z‡ fd	d
„Z	‡ fdd„Z
dd„ Z‡  ZS )ÚExtractAttachmentsPreprocessorzú
    Extracts attachments from all (markdown and raw) cells in a notebook.
    The extracted attachments are stored in a directory ('attachments' by default).
    https://nbformat.readthedocs.io/en/latest/format_description.html#cell-attachments
    z{notebook_name}_attachmentsz:Directory to place attachments if use_separate_dir is True)ÚhelpT)ÚconfigFznWhether to use output_files_dir (which ExtractOutput also uses) or create a separate directory for attachmentsc                    s"   t ƒ jf i |¤Ž d| _d| _dS )z$
        Public constructor
        Ú ÚattachmentsN)ÚsuperÚ__init__Ú	path_nameÚresources_item_key)ÚselfÚkw©Ú	__class__© úm/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/nbconvert/preprocessors/extractattachments.pyr   "   s    ÿz'ExtractAttachmentsPreprocessor.__init__c                    sx   | j r4| jj|d d�| _| j|d< i |d< d| _n|d | _d| _t|| j tƒs^i || j< tƒ  ||¡\}}||fS )zL
        Determine some settings and apply preprocessor to notebook
        Z
unique_key)Znotebook_nameZattachment_files_dirr   Zoutput_files_dirÚoutputs)	Úuse_separate_dirÚattachments_directory_templateÚformatr   r   Ú
isinstanceÚdictr   Ú
preprocess)r   ÚnbÚ	resourcesr   r   r   r   /   s    ÿ


z)ExtractAttachmentsPreprocessor.preprocessc           	      C   s¬   d|v r¤|j D ]”}| j d|› �¡ |j | D ]$}|j | |  d¡}t|ƒ} qTq.tj | j|¡}||| j	 |< tjj
dkrŽ| tjj
d¡}|j d| |¡|_q||fS )aB  
        Extract attachments to individual files and
        change references to them.
        E.g.
        '![image.png](attachment:021fdd80.png)'
        becomes
        '![image.png]({path_name}/021fdd80.png)'
        Assumes self.path_name and self.resources_item_key is set properly (usually in preprocess).
        r   zEncountered attachment zutf-8ú/zattachment:)r   ÚlogÚdebugÚencoder   ÚosÚpathÚjoinr   r   ÚsepÚreplaceÚsource)	r   Úcellr   ÚindexÚfnameÚmimetypeÚdataÚdecodedZnew_filenamer   r   r   Úpreprocess_cellG   s    

z.ExtractAttachmentsPreprocessor.preprocess_cell)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Útagr   r   r   r   r   r/   Ú__classcell__r   r   r   r   r      s    þýþür   )
r3   r#   Úbase64r   Z	traitletsr   r   Úbaser   r   r   r   r   r   Ú<module>   s
   