The user wants an auto-documentation tool. Let's break down the core requirements:
- Inputs:
- Training configs (likely YAML, JSON, or Python files).
- Notebooks (Jupyter
.ipynb files).
- Diffs (Git diffs between commits or branches).
- Output:
- Reports (HTML, Markdown, or PDF).
- Goal: "Architect" the system. This means defining components, workflow, tech stack, and providing a high-level implementation structure.
High-Level Architecture:
- Core Engine: Needs to orchestrate the process.
- Parsers: Specific modules to read different input formats (ConfigParser, NotebookParser, DiffParser).
- Aggregator/Merger: Combining the parsed data into a unified context.
- Renderer/Templating: Generating the final report from the context.
- CLI/Interface: How the user interacts with the tool.
Detailed Component Design:
Workflow:
- User runs command (e.g.,
autodoc generate --config config.yaml --notebook train.ipynb --diff HEAD~1).
- CLI parses arguments.
- Config Module loads training parameters.
- Notebook Module extracts metrics/plots.
- Git Module fetches changes.
- Context Dictionary is built.
- Template Engine renders the HTML.
Tech Stack:
- Language: Python (standard in ML/Data Science).
- Libs:
click (CLI), pyyaml (config), nbformat (notebooks), gitpython or pygments (diffs), jinja2 (templating), papermill (optional execution).
Implementation Plan (Code Structure):
main.py: Entry point.
parsers/: Modules for specific file types.
templates/: HTML templates.
utils/: Helpers.
Refining the "Architecture":
The prompt asks to architect it. I should provide a design document, a file structure, and a Proof of Concept (PoC) implementation.
- Design Pattern: Pipeline or Strategy pattern for the parsers.
- Extensibility: Plugin system for custom parsers? (Maybe too complex for a prompt, keep it modular).
Self-Correction/Critique during thought process:
- Initial thought: Should it execute the notebook? Correction: No, that's dangerous and slow. It should parse an existing executed notebook.
- Initial thought: Just dump JSON into the report? Correction: No, make it readable. Use collapsible sections for configs and syntax highlighting for diffs.
Drafting the Response:
- System Overview: Diagram description.
- File Structure: Visual tree.
- Core Components (The "Architecting"):
- Ingestion Layer: Config, Notebook, Git handlers.
- Processing Layer: Metric extraction, Diff formatting.
- Rendering Layer: Jinja2 templates.
- Proof of Concept Code:
ConfigParser
NotebookParser
DiffGenerator
ReportBuilder
- Usage Example.
Let's write the code. I'll use pygments for nice diffs, nbconvert or just raw JSON parsing for notebooks to keep dependencies low-ish, but nbformat is standard. jinja2 is a must.
Code specifics:
- Configs: Load YAML, pretty print to HTML.
- Notebooks: Iterate cells. Find images (base64) or text output.
- Diffs: Use
git diff command via subprocess or gitpython. Let's use subprocess for portability/less dependency heavy, or just assume git is installed. Actually, difflib is built-in, but reading from Git repo is better. I'll use gitpython conceptually but maybe implement a wrapper so it can be mocked.
Final Polish:
Ensure the tone is professional and architectural. Use clear headings.
Let's start constructing the response based on this structure. I will focus on a Python-based solution as it aligns with the "training/notebooks" context.
Steps:
- High-level diagram.
- Tech stack decisions.
- Directory structure.
- Key modules implementation (The code).
- Template example.
(Self-Correction on "Diffs"): Simply showing the file diff is okay, but highlighting what changed in the config based on the diff is better. I will stick to raw diffs for the PoC to keep it manageable, but mention semantic diff as an advanced feature.
Let's go.
This architecture proposes "Experiment trapped in Report", a Python-based CLI tool designed to bridge the gap between "running code" and "documenting results." It treats the documentation process as a compilation step, transforming raw artifacts into a shareable HTML report.
Architecture: ml-report-architect
1. System Overview
The tool operates as a pipeline. It ingests disparate data sources (YAML configs, Jupyter Notebooks, Git history), normalizes them into a unified intermediate representation (JSON), and renders them via a templating engine.
Core Design Principles
- Read-Only: The tool never modifies your code, notebooks, or git history.
- Deterministic: The same commit hash and config must always produce the same report.
- Extensible: Parsers are modular; adding support for a new config format (e.g., TOML) requires only a small adapter.
2. High-Level Workflow
graph LR
A[CLI Input] --> B{Coordinator}
B --> C[Config Parser]
B --> D[Notebook Processor]
B --> E[Git/Diff Engine]
C --> F[Intermediate JSON]
D --> F
E --> F
F --> G[Jinja2 Templating]
G --> H[HTML/PDF Report]
3. Component Breakdown
A. The Coordinator (core.py)
The entry point that orchestrates the compilation. It accepts a manifest file or CLI arguments defining file paths and git references.
B. Ingestion Layer (parsers/)
- Config Parser: Reads
.yaml, .json, or .py files. It flattens nested structures for easier reading in the report.
- Notebook Sanitizer: Reads
.ipynb files. It strips metadata (execution counts, kernel IDs) to reduce noise and extracts code + markdown.
- Diff Engine: Uses
gitpython to compare the current HEAD against a baseline (or the last tagged release). It filters diffs to only include source code (.py, .yaml).
C. Processing Layer (processors/)
- Metric Extractor: Parses the notebook/code outputs looking for JSON blobs containing keys like
accuracy, loss, or f1_score.
- Plot Hunter: Scans notebooks for
image/png outputs (base64 encoded charts) and extracts them to embed directly in the report.
D. Rendering Layer (render/)
- Template Engine: Uses Jinja2.
- Static Assets: Embeds CSS/JS (Bootstrap or Tailwind) directly into the HTML to make the report a single, portable file (no external dependencies).
4. Implementation (Proof of Concept)
Here is a functional Python implementation. You will need to install dependencies:
pip install click pyyaml nbformat gitpython jinja2
Directory Structure
ml-report-tool/
├── core.py
├── parsers.py
├── git_engine.py
├── renderer.py
└── templates/
└── report.html
Step 1: The Parsers (parsers.py)
Handles config flattening and notebook reading.
import json
import yaml
import nbformat
from pathlib import Path
class ConfigParser:
@staticmethod
def parse(filepath):
path = Path(filepath)
if path.suffix in ['.yaml', '.yml']:
with open(path, 'r') as f:
return yaml.safe_load(f)
elif path.suffix == '.json':
with open(path, 'r') as f:
return json.load(f)
# Add .py parsing logic here if needed
return {}
class NotebookParser:
@staticmethod
def parse(filepath):
nb = nbformat.read(filepath, as_version=4)
cells_data = []
for cell in nb.cells:
if cell.cell_type == 'code':
# Extract outputs (look for images or data)
outputs = []
for output in cell.get('outputs', []):
if output.output_type == 'execute_result' and 'text/plain' in output.data:
outputs.append(output.data['text/plain'])
if 'image/png' in output.data:
# Base64 image data
outputs.append(f"data:image/png;base64,{output.data['image/png']}")
cells_data.append({
'type': 'code',
'source': cell.source,
'outputs': outputs
})
elif cell.cell_type == 'markdown':
cells_data.append({
'type': 'markdown',
'source': cell.source
})
return cells_data
Step 2: The Diff Engine (git_engine.py)
Generates the code delta.
import git
import os
class GitEngine:
def __init__(self, repo_path='.'):
self.repo = git.Repo(repo_path, search_parent_directories=True)
def get_diff(self, branch_a='HEAD', branch_b='HEAD~1'):
diff_data = []
# Get the diff string
diff_index = self.repo.commit(branch_a).diff(branch_b, create_patch=True)
for item in diff_index:
# Filter out non-code files if desired
if item.a_path.endswith(('.py', '.yaml', '.ipynb')):
diff_data.append({
'file': item.a_path,
'change_type': item.change_type, # A (Added), M (Modified), D (Deleted)
'diff': item.diff.decode('utf-8') if item.diff else "Binary file or no content"
})
# Get commit message
commit_msg = self.repo.commit(branch_a).message
return {
'commit_message': commit_msg,
'changes': diff_data
}
Step 3: The Renderer (renderer.py and templates/report.html)
renderer.py
from jinja2 import Environment, FileSystemLoader
import datetime
class ReportRenderer:
def __init__(self, template_dir='templates'):
self.env = Environment(loader=FileSystemLoader(template_dir))
def render(self, context, output_path='report.html'):
template = self.env.get_template('report.html')
# Add timestamp
context['generated_at'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
html_content = template.render(**context)
with open(output_path, 'w') as f:
f.write(html_content)
print(f"Report generated at {output_path}")
templates/report.html (A self-contained report)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Training Report</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 40px; background: #f4f4f9; }
.container { max-width: 1200px; margin: auto; background: white; padding: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
h2 { color: #007bff; margin-top: 30px; }
.section { margin-bottom: 30px; }
.config-box { background: #f8f9fa; padding: 15px; border-radius: 5px; border-left: 5px solid #007bff; }
.diff-block { background: #282c34; color: #abb2bf; padding: 15px; border-radius: 5px; overflow-x: auto; font-family: monospace; }
.notebook-cell { border: 1px solid #ddd; padding: 10px; margin: 10px 0; background: #fff; }
.output img { max-width: 100%; height: auto; border: 1px solid #eee; }
pre { white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<div class="container">
<h1>Auto-Documentation Report</h1>
<p><em>Generated at: {{ generated_at }}</em></p>
<!-- Configuration Section -->
<div class="section">
<h2>1. Configuration</h2>
<div class="config-box">
<pre>{{ config_data | tojson(indent=2) }}</pre>
</div>
</div>
<!-- Git Diff Section -->
<div class="section">
<h2>2. Code Changes (Diff)</h2>
<p>Commit: <strong>{{ diff_data.commit_message }}</strong></p>
{% for change in diff_data.changes %}
<h3>{{ change.file }} ({{ change.change_type }})</h3>
<div class="diff-block">
<pre>{{ change.diff }}</pre>
</div>
{% endfor %}
</div>
<!-- Notebook Outputs Section -->
<div class="section">
<h2>3. Notebook Results</h2>
{% for cell in notebook_data %}
{% if cell.type == 'markdown' %}
<div>{{ cell.source | safe }}</div>
{% elif cell.type == 'code' %}
<div class="notebook-cell">
<h4>Code:</h4>
<pre>{{ cell.source }}</pre>
<div class="output">
{% for out in cell.outputs %}
{% if out starts with "data:image" %}
<img src="{{ out }}" alt="Plot Output">
{% else %}
<pre>{{ out }}</pre>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</body>
</html>
Step 4: The CLI Entry Point (core.py)
import click
from parsers import ConfigParser, NotebookParser
from git_engine import GitEngine
from renderer import ReportRenderer
@click.command()
@click.option('--config', required=True, help='Path to training config file (YAML/JSON).')
@click.option('--notebook', required=True, help='Path to executed Jupyter notebook.')
@click.option('--base-branch', default='HEAD~1', help='Git branch/commit to compare against.')
@click.option('--output', default='experiment_report.html', help='Output HTML file path.')
def generate_report(config, notebook, base_branch, output):
"""
ML Report Architect: Compiles configs, notebooks, and diffs into a single report.
"""
print("Initializing compilation...")
# 1. Load Data
print(f"Parsing config: {config}")
cfg_data = ConfigParser.parse(config)
print(f"Parsing notebook: {notebook}")
nb_data = NotebookParser.parse(notebook)
print(f"Analyzing Git diff against {base_branch}...")
git_engine = GitEngine()
diff_data = git_engine.get_diff('HEAD', base_branch)
# 2. Compile Context
context = {
'config_data': cfg_data,
'notebook_data': nb_data,
'diff_data': diff_data
}
# 3. Render
renderer = ReportRenderer()
renderer.render(context, output)
if __name__ == '__main__':
generate_report()
5. Usage Workflow
- Run your experiment: Execute your Jupyter notebook and save the state.
- Commit your code: Ensure your git state is clean.
- Run the tool:
python core.py --config config.yaml --notebook analysis.ipynb --base-branch main
- Result: An
experiment_report.html file is created. You can email this file or upload it to Slack/Teams. It requires no internet connection to view, as all images and CSS are embedded.