示例#1
0
def get_converted_script(input_notebook_path: str, conf: MlVToolConf) -> str:
    """
        Extract notebook python content using nbconvert
    """
    exporter = PythonExporter(get_config(TEMPLATE_PATH))
    exporter.register_filter(name='filter_trailing_cells',
                             jinja_filter=filter_trailing_cells)
    exporter.register_filter(name='get_formatted_cells',
                             jinja_filter=get_formatted_cells)
    exporter.register_filter(name='get_data_from_docstring',
                             jinja_filter=get_data_from_docstring)
    exporter.register_filter(name='sanitize_method_name',
                             jinja_filter=to_method_name)
    resources = {'ignore_keys': conf.ignore_keys}
    logging.debug(f'Template info {resources}')
    try:
        script_content, _ = exporter.from_filename(input_notebook_path,
                                                   resources=resources)
    except Exception as e:
        raise MlVToolException(e) from e
    return script_content
def export_to_script(input_notebook_path: str, output_path: str,
                     conf: MlVToolConf):
    """
        Export a notebook to a parameterize Python 3 script
        using Jinja templates
    """
    logging.info(
        f'Generate Python script {output_path} from Jupyter Notebook {input_notebook_path}'
    )
    logging.debug(f'Global Configuration: {conf}')
    logging.debug(f'Template path {TEMPLATE_PATH}')

    exporter = PythonExporter(get_config(TEMPLATE_PATH))
    exporter.register_filter(name='filter_trailing_cells',
                             jinja_filter=filter_trailing_cells)
    exporter.register_filter(name='get_formatted_cells',
                             jinja_filter=get_formatted_cells)
    exporter.register_filter(name='get_data_from_docstring',
                             jinja_filter=get_data_from_docstring)
    exporter.register_filter(name='sanitize_method_name',
                             jinja_filter=to_method_name)
    resources = {'ignore_keys': conf.ignore_keys}
    logging.debug(f'Template info {resources}')
    try:
        script_content, _ = exporter.from_filename(input_notebook_path,
                                                   resources=resources)
    except Exception as e:
        raise MlVToolException(e) from e

    if not script_content:
        logging.warning('Empty notebook provided. Nothing to do.')
        return
    write_python_script(script_content, output_path)
    logging.log(
        logging.WARNING + 1,
        f'Python script successfully generated in {abspath(output_path)}')