U
    nuf                     @   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 | d| _d| _dS )z$
        Public constructor
         attachmentsN)super__init__	path_nameresources_item_key)selfkw	__class__ N/tmp/pip-unpacked-wheel-nxpdnluh/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|kr|j D ]}| jd| |j | D ]$}|j | | d}t|} qPq*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 %sz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
   