Skip to main content

Transform ordinary codebases into explainable execution artifacts.

Project description

martian

Transform ordinary codebases into explainable execution artifacts.

Martian captures how software behaves while it runs โ€” function calls, outputs, artifacts, logs, execution flow, runtime metadata, and relationships โ€” then compiles them into rich interactive mission reports called MartianBooks.

Write normal code.
Martian observes.
No notebooks required.

๐Ÿ‘จโ€๐Ÿš€ ๐Ÿ“ˆ ๐Ÿ‘๏ธ ๐Ÿ˜จ๐Ÿ”ฅ


๐Ÿค– Using an AI assistant? Attach SKILL.md to your conversation for accurate MartianBook help out of the box.

Explain It Like I'm A Little Martian

Imagine your code is a space mission.

Tiny astronauts are running around doing jobs ๐Ÿ‘จโ€๐Ÿš€๐Ÿ‘จโ€๐Ÿš€๐Ÿ‘จโ€๐Ÿš€๐Ÿ‘จโ€๐Ÿš€

One astronaut loads data.
One astronaut cleans things.
One astronaut makes a chart ๐Ÿ“ˆ
One astronaut accidentally catches on fire ๐Ÿ˜จ๐Ÿ”ฅ

Martian floats nearby and silently watches the chaos.

It remembers:

  • who did what
  • who called whom
  • what got created
  • what got printed
  • what exploded
  • how long everything took

Then Martian turns the whole mission into a MartianBook so humans can explore what happened afterward and pretend they completely understood it.

You write normal code. Martian just observes ๐Ÿ‘๏ธ

No notebook rituals required.


Why?

Developers often end up choosing between clean projects:

src/
models/
utils/
main.py

and:

analysis_FINAL_v7_REAL_FINAL.ipynb

because notebooks are easy to explain, visualize, and share.

Martian preserves normal software structure while giving you notebook-like explainability after execution. No cell-based workflows. No regression to notebooks just to show management a chart.


Installation

uv add martianbook

Martian runs inside your project's own environment so it can see all your dependencies โ€” torch, numpy, sklearn, huggingface, whatever you use. Install it alongside your other packages, not as a global tool.

# Add martianbook alongside your own deps
uv add martianbook numpy matplotlib torch

Or with pip:

pip install martianbook

Running

Martian understands Python files directly โ€” no subcommand needed:

uv run martian main.py              # run a single script
uv run martian "examples/*.py"      # run all scripts matching pattern
uv run martian "src/**/*.py"        # recursive wildcard

The go subcommand also works if you prefer explicit:

uv run martian go main.py

Optional: martian Alias

Set this up once and never type uv run martian again.

Linux / macOS โ€” add to ~/.bashrc or ~/.zshrc:

alias martian="uv run martian"
source ~/.bashrc   # reload

Windows PowerShell โ€” add to $PROFILE:

function martian { uv run martian @args }

After that, everywhere in your project:

martian main.py
martian "examples/*.py"
martian serve
martian export

Quick Start

1. Choose which functions to show in MartianBook.

You are in full control. Martian only captures the functions you explicitly decorate โ€” everything else runs normally and stays invisible. Decorate the functions that tell the story: the ones with meaningful outputs, the ones that produce charts, the ones you want to explain to others.

# main.py
import martianbook as martian

# โœ“ Decorate the functions you want in MartianBook
@martian.capture
def load_data(path: str):
    """Loads raw CSV data and validates schema."""
    print(f"Loading {path}...")
    return {"rows": 1200}

@martian.capture
def clean_data(dataset: dict):
    """Removes nulls and validates required columns."""
    print(f"Cleaning {dataset['rows']} rows...")
    return {**dataset, "rows": dataset["rows"] - 14}

# โœ— Skip functions you don't want shown โ€” they still run normally
@martian.skip
def debug_dump(data):
    print(f"DEBUG: {data}")

# Group related functions under a named section
@martian.section("Pipeline")
def run():
    """Full pipeline from ingestion to output."""
    data  = load_data("data/raw.csv")
    clean = clean_data(data)
    debug_dump(clean)   # runs but never appears in MartianBook

if __name__ == "__main__":
    run()

2. Run:

uv run martian main.py

3. Open MartianBook in your browser:

uv run martian serve

CLI Reference

uv run martian main.py                 # run script, capture execution
uv run martian "examples/*.py"         # run all matching scripts
uv run martian main.py --inspect       # run and print terminal summary
uv run martian inspect                 # print summary of last run
uv run martian serve                   # open MartianBook in browser
uv run martian export                  # export standalone HTML
uv run martian export -o report.html   # export to specific path

Works With Your Existing Stack

Martian runs inside your environment. It sees everything you have installed.

import martianbook as martian
import torch
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier

@martian.capture
def train_model(X, y):
    """Trains a random forest classifier on the cleaned dataset."""
    clf = RandomForestClassifier(n_estimators=100)
    clf.fit(X, y)
    print(f"Accuracy: {clf.score(X, y):.3f}")
    return clf

torch, sklearn, pandas, huggingface, beautifulsoup โ€” all visible. No lockout.


Artifact Detection

Martian automatically detects files produced during execution. Save plots, CSVs, or any file to .martian/artifacts/ and they appear in the report linked to the function that created them โ€” embedded inline in the exported HTML.

@martian.capture
def plot_results(data):
    """Plots distribution across numeric columns."""
    import matplotlib
    matplotlib.use("Agg")   # always required โ€” prevents GUI errors
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    ax.hist(data, bins=40)
    ax.set_title("Result Distribution")
    fig.savefig(".martian/artifacts/distribution.png")
    plt.close(fig)
uv run martian main.py
uv run martian export

# Open the exported file
open martianbook.html        # macOS
firefox martianbook.html    # Linux 

Supported: PNG, SVG, JPG, CSV, JSON, TXT, and any other format.


Decorators

@martian.capture

Instruments a function. Martian records its source code, docstring, arguments, stdout, return value summary, timing, exceptions, and any artifacts it produces. Only decorate the functions you want to appear in MartianBook.

@martian.capture
def train_model(data):
    """Trains the model on cleaned data."""
    ...

@martian.skip

Function executes normally and completely. Martian ignores it. Use for debug helpers, noisy internals, or anything you don't want surfaced in the report.

@martian.skip
def debug_dump():
    print("internal state...")

@martian.section

Groups all captured functions called inside this one under a named section in MartianBook. Useful for organizing complex pipelines into readable chapters.

@martian.section("Data Pipeline")
def run_pipeline():
    """Full pipeline from ingestion to output."""
    load_data()
    clean_data()
    train_model()

Generated Structure

.martian/
โ”œโ”€โ”€ report.json       โ† full execution IR
โ””โ”€โ”€ artifacts/        โ† files produced during the run

Intermediate Representation

Martian uses a language-independent runtime schema. All adapters produce the same report.json. All renderers consume only that file.

{
  "martian_version": "0.1.0",
  "mission": {
    "entry_point": "main.py",
    "duration_ms": 104.3,
    "status": "success"
  },
  "execution": [
    {
      "name": "load_data",
      "duration_ms": 50.3,
      "stdout": ["Loading data/raw.csv..."],
      "children": ["clean_data"]
    }
  ]
}

This separation allows HTML renderers, desktop apps, hosted viewers, VSCode integrations, and future language adapters to all consume the same format.


Demos

The demos/ directory in the repo contains working examples. They cannot be run directly from the repo โ€” they need their own environment. See demos/README.md for setup instructions.

Demo What it shows
demos/basic/pipeline.py Single file pipeline, all three decorators
demos/plotting/charts.py Matplotlib artifact capture, 3 plots
demos/multimodule/run.py Cross-file decorated functions, 3 modules

Current Status

โœ… Python runtime instrumentation
โœ… Execution tree generation
โœ… Function-level telemetry
โœ… stdout/stderr capture
โœ… Runtime duration tracking
โœ… Exception capture
โœ… Artifact detection (PNG, SVG, CSV, and more)
โœ… Inline image embedding in HTML exports
โœ… Return value summaries
โœ… Dependency relationships
โœ… JSON intermediate representation
โœ… Modular adapter architecture
โœ… Direct script invocation (martian main.py)
โœ… Wildcard execution (martian "examples/*.py")
โœ… CLI โ€” martian go, martian inspect, martian serve, martian export


Roadmap

Near-term

  • Syntax highlighting in code blocks
  • Call graph visualization
  • Execution timeline
  • Full styled MartianBook UI

Future

  • Rust adapter
  • C++ adapter
  • JavaScript adapter
  • Desktop application
  • VSCode integration
  • Hosted mission viewer
  • Multi-language execution support

Far future

martian universe/

Results may vary.


Author

Built by Andrew Garcia, Ph.D.

Martian started with a simple question:

Why should developers have to choose between clean software architecture and explainable notebooks?

Martian explores a different path:

Write ordinary software.

Observe execution.

Generate explainable artifacts afterward.


License

MIT

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

martianbook-0.1.0.tar.gz (73.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

martianbook-0.1.0-py3-none-any.whl (73.9 kB view details)

Uploaded Python 3

File details

Details for the file martianbook-0.1.0.tar.gz.

File metadata

  • Download URL: martianbook-0.1.0.tar.gz
  • Upload date:
  • Size: 73.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for martianbook-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e5c19a52ae153aef0271f02954675ce832476c06a1a58d6b5590cd95df9a50fd
MD5 a35b27ca4344e18c89db24e73a9247e0
BLAKE2b-256 66fd25231803f82d35d825a577b74d8184a25d8f84f1c4ae82517d07145c0444

See more details on using hashes here.

File details

Details for the file martianbook-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: martianbook-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 73.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for martianbook-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 84cfb662f4d36ee2720bb4616a8c78608ed42100ca8c98f270cf2e1e7495db0d
MD5 92c235f93818af537b676a65efe72544
BLAKE2b-256 117eb19d6d99d56b83b9031468ae9d5d0485fdb6aac3f6279ae99856e3e251dc

See more details on using hashes here.

Supported by

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