Repository navigation
Expand file tree
/
Copy pathconvert_notebooks.py
More file actions
100 lines (73 loc) · 2.51 KB
/
Copy pathconvert_notebooks.py
File metadata and controls
100 lines (73 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env python3
from __future__ import annotations
import argparse
from pathlib import Path
import nbformat
from nbconvert import WebPDFExporter
def ipynb_to_pdf(ipynb_path: Path, pdf_path: Path):
try:
with open(ipynb_path, encoding="utf-8") as f:
nb = nbformat.read(f, as_version=4)
pdf_exporter = WebPDFExporter()
pdf_exporter.exclude_input_prompt = True
pdf_exporter.exclude_output_prompt = True
pdf_data, _ = pdf_exporter.from_notebook_node(nb)
with open(pdf_path, "wb") as f:
f.write(pdf_data)
print(f"✅ Converted: {ipynb_path.name} -> {pdf_path.name}")
except Exception as e:
print(f"❌ Failed to convert {ipynb_path.name} to pdf: {e}")
def sync_notebooks_to_pdf(directory_path: str, output_path: str, force: bool = False):
base_path = Path(directory_path)
if output_path:
out_base = Path(output_path)
else:
out_base = base_path / "resources"
out_base.mkdir(parents=True, exist_ok=True)
notebooks = list(base_path.glob("*.ipynb"))
if not notebooks:
print(f"⚠️ No notebooks found in: {directory_path}")
return
for ipynb_path in notebooks:
pdf_path = out_base / ipynb_path.with_suffix(".pdf").name
should_convert = False
if force:
should_convert = True
elif not pdf_path.exists():
should_convert = True
else:
ipynb_mtime = ipynb_path.stat().st_mtime
pdf_mtime = pdf_path.stat().st_mtime
if ipynb_mtime > pdf_mtime:
should_convert = True
if should_convert:
ipynb_to_pdf(ipynb_path, pdf_path)
else:
print(f"ℹ️ Skipped: {ipynb_path.name} (PDF is up to date)")
def main():
parser = argparse.ArgumentParser(
description="Sync jupyter notebooks to PDF with math support",
)
parser.add_argument(
"--notebooks_dir",
"-d",
required=True,
help="Path to directory with notebooks",
)
parser.add_argument(
"--output_dir",
"-o",
required=False,
default=None,
help="Output directory for PDF files",
)
parser.add_argument(
"--force",
"-f",
action="store_true",
help="Force re-export of all notebooks even if they haven't changed",
)
args = parser.parse_args()
sync_notebooks_to_pdf(args.notebooks_dir, args.output_dir, args.force)
if __name__ == "__main__":
main()