B
    Z[K                 @   s  d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	m
Z
 ddlmZmZ ddlmZmZmZmZmZmZ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m Z m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' G dd deZ(i Z)e)*e	 e)*ddddddddd i Z+e+*e
 e+*dddiidfdddiidfdd diid!fdd"d#iid$fd%d&d'd(d)id*d+fd%d&d'd(d)iddid,d-fd.ddd/id0fd.ddd1id2fd3 G d4d deZ,e,j- Z.Z/dS )5zuNbConvert is a utility for conversion of .ipynb files.

Command-line interface for the NbConvert conversion utility.
    )print_functionN)
JupyterAppbase_aliases
base_flags)catch_config_errorConfigurable)UnicodeListInstanceDottedObjectNameTypeBooldefaultobserve)import_item   )get_export_namesget_exporter)	exporterspreprocessorswriterspostprocessors__version__)NbConvertBase)ConversionException)unicode_stdin_streamc                   s$   e Zd ZdZdZ fddZ  ZS )DottedOrNonezjA string holding a valid dotted object name in Python, such as A.b3._c
    Also allows for None type.
     c                s.   |d k	r&t |dkr&tt| ||S |S d S )Nr   )lensuperr   validate)selfobjvalue)	__class__ 5lib/python3.7/site-packages/nbconvert/nbconvertapp.pyr    *   s    zDottedOrNone.validate)__name__
__module____qualname____doc__Zdefault_valuer    __classcell__r%   r%   )r$   r&   r   $   s   r   zNbConvertApp.export_formatzTemplateExporter.template_filezNbConvertApp.writer_classz NbConvertApp.postprocessor_classzNbConvertApp.output_basezFilesWriter.build_directoryz SlidesExporter.reveal_url_prefixz!NotebookExporter.nbformat_version)totemplatewriterZpostoutputz
output-dirzreveal-prefixZnbformatZExecutePreprocessorZenabledTz%Execute the notebook prior to export.Zallow_errorszContinue notebook execution even if one of the cells throws an error and include the error message in the cell output (the default behaviour is to abort conversion). This flag is only relevant if '--execute' was specified, too.NbConvertApp
from_stdinzgread a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'writer_classZStdoutWriterz1Write notebook output to stdout instead of files.FZnotebook)use_output_suffixexport_formatbuild_directoryr   )r0   FilesWriterzuRun nbconvert in place, overwriting the existing notebook (only 
        relevant when converting to notebook format))r0   r6   ZClearOutputPreprocessorz\Clear output of current file and save in place, 
        overwriting the existing notebook. ZTemplateExporter)Zexclude_input_promptexclude_output_promptz9Exclude input and output prompts from converted document.)r7   Zexclude_inputz}Exclude input cells and output prompts from converted document. 
        This mode is ideal for generating code-free reports.)Zexecutezallow-errorsstdinstdoutZinplacezclear-outputz	no-promptzno-inputc                   s  e Zd ZdZeZdZeZe	Z
eddd Ze Zeddd Zed	Zed
ddjddZedddjddZedddjddZede ZeddddZedddjddZddddZeddZ e!ddd Z"ed d!ddZ#e$d"djddZ%d#d$iZ&ed%ddZ'e!d&d'd( Z(ed)d*djddZ)ed+d,d-d.jddZ*eg d/djddZ+ed,d0djddZ,e-dI fd1d2	Z.d3d4 Z/d5d6 Z0d7d8 Z1d9d: Z2 fd;d<Z3d=d> Z4dJd?d@Z5dAdB Z6dCdD Z7dKdEdFZ8dGdH Z9  Z:S )Lr0   zAApplication used to convert from notebook file type (``*.ipynb``)zjupyter-nbconvertZ	log_levelc             C   s   t jS )N)loggingINFO)r!   r%   r%   r&   _log_level_default   s    zNbConvertApp._log_level_defaultclassesc             C   sZ   t g}xNttttfD ]>}x8t|D ],}t||}t|tr"t	|t
r"|| q"W qW |S )N)r   r   r   r   r   dirgetattr
isinstancetype
issubclassr   append)r!   r=   pkgnameclsr%   r%   r&   _classes_default   s    
zNbConvertApp._classes_defaultzThis application is used to convert notebook files (*.ipynb)
        to various other formats.

        WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.r   z{overwrite base name use for output files.
            can only be used when converting one notebook at a time.
            )helpT)configzWhether to apply a suffix prior to the extension (only relevant
            when converting to notebook format). The suffix is determined by
            the exporter, and is usually '.nbconvert'.z{notebook_name}_fileszDirectory to copy extra files (figures) to.
               '{notebook_name}' in the string will be converted to notebook
               basenamea  
        The simplest way to use nbconvert is
        
        > jupyter nbconvert mynotebook.ipynb
        
        which will convert mynotebook.ipynb to the default format (probably HTML).
        
        You can specify the export format with `--to`.
        Options include {0}
        
        > jupyter nbconvert --to latex mynotebook.ipynb

        Both HTML and LaTeX support multiple output templates. LaTeX includes
        'base', 'article' and 'report'.  HTML includes 'basic' and 'full'. You
        can specify the flavor of the format used.

        > jupyter nbconvert --to html --template basic mynotebook.ipynb
        
        You can also pipe the output to stdout, rather than a file
        
        > jupyter nbconvert mynotebook.ipynb --stdout

        PDF is generated via latex

        > jupyter nbconvert mynotebook.ipynb --to pdf
        
        You can get (and serve) a Reveal.js-powered slideshow
        
        > jupyter nbconvert myslides.ipynb --to slides --post serve
        
        Multiple notebooks can be given at the command line in a couple of 
        different ways:
  
        > jupyter nbconvert notebook*.ipynb
        > jupyter nbconvert notebook1.ipynb notebook2.ipynb
        
        or you can specify the notebooks list in a config file, containing::
        
            c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
        
        > jupyter nbconvert --config mycfg.py
        z!nbconvert.writers.base.WriterBasez`Instance of the writer class used to write the 
                      results of the conversion.)rH   
allow_noner6   z]Writer class used to write the 
                                    results of the conversionz#nbconvert.writers.files.FilesWriterz#nbconvert.writers.debug.DebugWriterz%nbconvert.writers.stdout.StdoutWriter)ZfileswriterZdebugwriterZstdoutwriter)rJ   r2   c             C   s2   |d }|  | jkr$| j|   }t|| _d S )Nnew)lowerwriter_aliasesr   writer_factory)r!   changerK   r%   r%   r&   _writer_class_changed   s    z"NbConvertApp._writer_class_changedz/nbconvert.postprocessors.base.PostProcessorBasezfInstance of the PostProcessor class used to write the
                      results of the conversion.zcPostProcessor class used to write the
                                    results of the conversionZservez1nbconvert.postprocessors.serve.ServePostProcessorNpostprocessor_classc             C   s6   |d }|  | jkr$| j|   }|r2t|| _d S )NrK   )rL   postprocessor_aliasesr   postprocessor_factory)r!   rO   rK   r%   r%   r&   _postprocessor_class_changed   s
    z)NbConvertApp._postprocessor_class_changedzhttps://unpkg.com/zURL base for ipywidgets packageZhtmlFzThe export format to be used, either one of the built-in formats,
        or a dotted object name that represents the import path for an
        `Exporter` class)rJ   rH   zList of notebooks to convert.
                     Wildcards are supported.
                     Filenames passed positionally will be added to the list.
                     z"read a single notebook from stdin.c                s4   |    tt| | |   |   |   dS )z<Initialize application, notebooks, writer, and postprocessorN)init_syspathr   r0   
initializeinit_notebooksinit_writerinit_postprocessor)r!   argv)r$   r%   r&   rV     s
    zNbConvertApp.initializec             C   s   t jdt  dS )z)Add the cwd to the sys.path ($PYTHONPATH)r   N)syspathinsertosgetcwd)r!   r%   r%   r&   rU     s    zNbConvertApp.init_syspathc             C   s   | j r| j }n| j}g }x\|D ]T}t|}|t|d  |sR| jd| x|D ]}||krX|| qXW qW || _dS )zConstruct the list of notebooks.

        If notebooks are passed on the command-line,
        they override (rather than add) notebooks specified in config files.
        Glob each notebook to replace notebook patterns with filenames.
        z.ipynbzpattern %r matched no filesN)Z
extra_args	notebooksglobextendlogZwarningrC   )r!   Zpatterns	filenamespatternZglobbed_filesfilenamer%   r%   r&   rW   "  s    



zNbConvertApp.init_notebooksc             C   s@   |  d| ji | j| d| _t| jdr<| jjdkr<d| _dS )z*Initialize the writer (which is stateless)rK   )parentr5   r   FN)rP   r2   rN   r.   hasattrr5   r3   )r!   r%   r%   r&   rX   A  s    zNbConvertApp.init_writerc             C   s(   |  d| ji | jr$| j| d| _dS )z1Initialize the postprocessor (which is stateless)rK   )rg   N)rT   rQ   rS   postprocessor)r!   r%   r%   r&   rY   H  s    zNbConvertApp.init_postprocessorc                s   t t|   |   dS )z4Run start after initialization process has completedN)r   r0   startconvert_notebooks)r!   )r$   r%   r&   rj   N  s    zNbConvertApp.startc             C   s   t j|}|d|d }| jr\t| jddrVt j| j\}}|| jjkrV|| _| j}| j	
d| i }| j|d< ||d< | jj|d}||d	< | j|d
< |S )a  Step 1: Initialize resources

        This initializes the resources dictionary for a single notebook.

        Returns
        -------

        dict
            resources dictionary for a single notebook that MUST include the following keys:
                - config_dir: the location of the Jupyter config directory
                - unique_key: the notebook name
                - output_files_dir: a directory where output files (not
                  including the notebook itself) should be saved
        N.file_extensionFzNotebook name is '%s'
config_dir
unique_key)notebook_nameoutput_files_diripywidgets_base_url)r^   r\   basenamerfindoutput_baser?   exportersplitextrm   rc   debugrn   rq   formatrr   )r!   notebook_filenamers   rp   baseZext	resourcesrq   r%   r%   r&   init_single_notebook_resourcesS  s"    

z+NbConvertApp.init_single_notebook_resourcesc             C   sp   y6|dk	r | j j||d\}}n| j j||d\}}W n0 tk
rf   | jjd|dd | d Y nX ||fS )aU  Step 2: Export the notebook

        Exports the notebook to a particular format according to the specified
        exporter. This function returns the output and (possibly modified)
        resources from the exporter.

        Parameters
        ----------
        notebook_filename : str
            name of notebook file.
        resources : dict
        input_buffer :
            readable file-like object returning unicode.
            if not None, notebook_filename is ignored

        Returns
        -------
        output

        dict
            resources (possibly modified)
        N)r|   zError while converting '%s'T)exc_infor   )rv   Z	from_fileZfrom_filenamer   rc   errorexit)r!   rz   r|   input_bufferr/   r%   r%   r&   export_single_notebook|  s    z#NbConvertApp.export_single_notebookc             C   sJ   d|krt d|d }| jr4| js4||dd7 }| jj|||d}|S )a  Step 3: Write the notebook to file

        This writes output from the exporter to file using the specified writer.
        It returns the results from the writer.

        Parameters
        ----------
        output :
        resources : dict
            resources for a single notebook including name, config directory
            and directory to save output

        Returns
        -------
        file
            results from the specified writer output of exporter
        ro   z<unique_key MUST be specified in the resources, but it is notZoutput_suffixr   )rp   )KeyErrorr3   ru   getr.   write)r!   r/   r|   rp   write_resultsr%   r%   r&   write_single_notebook  s    z"NbConvertApp.write_single_notebookc             C   s   t | dr| jr| | dS )zStep 4: Post-process the written file

        Only used if a postprocessor has been specified. After the
        converted notebook is written to a file in Step 3, this post-processes
        the notebook.
        ri   N)rh   ri   )r!   r   r%   r%   r&   postprocess_single_notebook  s    z(NbConvertApp.postprocess_single_notebookc             C   sd   |dkr| j d|| j n| j d| j | |}| j|||d\}}| ||}| | dS )a%  Convert a single notebook.

        Performs the following steps:

            1. Initialize notebook resources
            2. Export the notebook to a particular format
            3. Write the exported notebook to file
            4. (Maybe) postprocess the written file

        Parameters
        ----------
        notebook_filename : str
        input_buffer :
            If input_buffer is not None, conversion is done and the buffer is
            used as source into a file basenamed by the notebook_filename
            argument.
        NzConverting notebook %s to %szConverting notebook into %s)r   )rc   infor4   r}   r   r   r   )r!   rz   r   r|   r/   r   r%   r%   r&   convert_single_notebook  s    
z$NbConvertApp.convert_single_notebookc             C   s   | j dkr.t| jdkr.| jd | d t| j}|| jd| _	t| jdkrl| j
sl|   td | j
sx.| jD ]}| | qzW nt }| jd|d d	S )
z4Convert the notebooks in the self.notebook traitlet r   r   z
                UsageError: --output flag or `NbConvertApp.output_base` config option
                cannot be used when converting multiple notebooks.
                )rI   r   znotebook.ipynb)r   N)ru   r   r`   rc   r   r   r   r4   rI   rv   r1   Z
print_helpr[   r   r   )r!   rF   rz   r   r%   r%   r&   rk     s    


zNbConvertApp.convert_notebooks)N)N)N);r'   r(   r)   r*   r   versionrE   nbconvert_aliasesaliasesnbconvert_flagsflagsr   r<   r	   r=   rG   r   Zdescriptiontagru   r   r3   rq   ry   r   Zexamplesr
   r.   r   r2   rM   r   rN   r   rP   ri   r   rQ   rR   rS   rT   rr   r4   r`   r1   r   rV   rU   rW   rX   rY   rj   r}   r   r   r   r   rk   r+   r%   r%   )r$   r&   r0      s|   )


)
"
)0r*   Z
__future__r   r:   r[   r^   ra   Zjupyter_core.applicationr   r   r   Ztraitlets.configr   r   Z	traitletsr   r	   r
   r   r   r   r   r   Ztraitlets.utils.importstringr   Zexporters.baser   r   Z	nbconvertr   r   r   r   r   Z
utils.baser   Zutils.exceptionsr   Zutils.ior   r   r   updater   r0   Zlaunch_instancemainZlaunch_new_instancer%   r%   r%   r&   <module>   sx   (







   