Skip to main content

An automation tool to refactor Jupyter Notebooks to Python modules, with code dependency analysis.

Project description

nbrefactor Logo


Platform pypi License Read the Docs

An automation tool to refactor Jupyter Notebooks to Python packages and modules.


Overview (The "What")

nbrefactor is designed to refactor Jupyter Notebooks into structured Python packages and modules. Using Markdown Headers and/or custom commands in a notebook's Markdown/text cells, nbrefactor creates a hierarchical module structure that reflects the notebook's content autonomously.

Motivation (The "Why")

With the growing dependence on cloud-based IPython platforms (Google Colab, primarily), developing projects directly in-browser has become more prominent. Having suffered through the pain of refactoring entire projects from Jupyter Notebooks into Python packages/modules to facilitate PyPI publication (and proper source control), this tool was developed to automate the refactoring process.

Approach (The "How")

This project does not just create a hierarchy based on the level of Markdown headers (how many # there are); this is just a single step in the refactoring process.

Since we are generating modules that potentially depend on context from previous cells in the notebook, dependency-analysis is required. Furthermore, we also need track the generated modules and all globally-accessible identifiers throughout the notebook to generate relative import statements as needed.

For instance, if a class is refactored to a generated module ./package/sub_package/module.py, this definition and module path need to be tracked so we can relatively import it as needed if it appears in successive cells or modules. Scope-Awareness and Identifier-Shadowing posed a challenge as well, and are also handled in the dependency analysis phase of the refactoring.

Module Hierarchy Generation

Convert markdown headers in notebooks into a corresponding folder and file structure.

refactoring_examples

Code Dependency Analyzer (CDA)

The core of nbrefactor's functionality lies in the Code Dependency Analyzer (CDA). The CDA is responsible for parsing code cells, tracking declared definitions, and analyzing dependencies across the generated modules. This module tackles challenges that were raised during the inception of the refactoring-automation process (primarily handling relative imports dynamically as we generate the modules, identifier shadowing, and non-redundant dependency injection).

  1. IPython Magic Command Removal: clean the source code by omitting IPython magic commands (to ensure that the code can be parsed by Python's ast).
  2. AST Parsing: parse the sanitized code into an Abstract Syntax Tree
  3. Import Statement Stripping: extract and strip import statements from the parsed code, and add them to a global (across all cells) tracker.
  4. Global Definition Tracking: track all encountered definitions (declared functions and classes) globally. This inherently handles identifier shadowing.
  5. Dependency Analysis: analyze identifier usages in a given code block.
  6. Dynamic Relative Import Resolution: resolve local import statements dynamically depending on the current and target modules' positions in the tree.
  7. Dependency Generation and Resolution: generate the respective import statements (given the definitions' analysis in step 5 & 6) to be injected during the file-writing phase.

Installation

PyPI (recommended)

The Python package is hosted on the Python Package Index (PyPI).

The latest published version of nbrefactor can be installed using

pip install nbrefactor

Manual Installation

Simply clone the repo and extract the files in the nbrefactor folder, then run:

pip install -r requirements.txt
pip install -e .

Or use one of the scripts below:

GIT

  • cd into your project directory
  • Use sparse-checkout to pull the library files only into your project directory
    git init nbrefactor
    cd nbrefactor
    git remote add -f origin https://github.com/ThunderStruct/nbrefactor.git
    git config core.sparseCheckout true
    echo "nbrefactor/*" >> .git/info/sparse-checkout
    git pull --depth=1 origin master
    pip install -r requirements.txt
    pip install -e .
    

SVN

  • cd into your project directory
  • checkout the library files
    svn checkout https://github.com/ThunderStruct/nbrefactor/trunk/nbrefactor
    pip install -r requirements.txt
    pip install -e .
    

Usage

Refer to the documentation for the comprehensive commands' reference. Some basic usages are provided below.

Command Line Interface

nbrefactor provides a CLI to easily refactor notebooks into a structured project hierarchy.

Basic CLI Usage

To use the CLI, run the following command:

jupyter nbrefactor <notebook_path> <output_path> [OPTIONS]
  • <notebook_path>: Path to the Jupyter notebook file you want to refactor.
  • <output_path>: Directory where the refactored Python modules will be saved.

CLI Arguments

Argument Type Description Default
notebook_path str Path to the Jupyter Notebook file to be refactored. (Required)
output_path str Path to the output directory where refactored modules will be saved. (Required)
-rp, --root-package str Name of the root package. Defaults to the current directory ".". "."
-gp, --generate-plot flag Plots a dendrogram of the refactored project structure. False
-pf, --plot-format str Format of the generated plot (e.g., "pdf", "png"). "pdf"

Demo

There are several example notebooks provided to showcase nbrefactor's capabilities.

  • Primary Demo Notebook: this notebook contains several examples of the core nbrefactor features, including all Markdown commands.
  • CS231n Notebook: the official CS231n Colab notebook.
  • HiveNAS Notebook: a larger project with a more complex folder structure.
  • Markdown-only Notebook: a Markdown-only notebook to illustrate the directory-refactoring abilities of nbrefactor.

Interactive Demo

An interactive Notebook-based demo can be found here, which can be used to run the example projects discussed above.

License

nbrefactor is licensed under the MIT License. See the LICENSE file for more details.

Contributing

PRs are welcome (and encouraged)! If you'd like to contribute to nbrefactor, please read the CONTRIBUTING guidelines. The TODO list delineates some potential future implementations and improvements.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nbrefactor-0.1.0.tar.gz (25.2 kB view hashes)

Uploaded Source

Built Distribution

nbrefactor-0.1.0-py3-none-any.whl (27.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page