forked from patrickmineault/codebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assemble_book.py
239 lines (187 loc) · 5.63 KB
/
assemble_book.py
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import collections
import yaml
template = r"""
\documentclass[letterpaper,twoside,openright]{scrbook}
\usepackage{hyperref}
\usepackage{datetime}
\usepackage{graphicx}
\usepackage{natbib}
\usepackage{framed}
\usepackage[utf8]{inputenc}
\usepackage{svg}
% Header stuff
\usepackage{scrlayer-scrpage}
\usepackage[top=80pt, bottom=80pt, left=80pt, right=80pt]{geometry}
\clearscrheadfoot
\ihead{\headmark}
\ohead{\pagemark}
\rofoot{Patrick Mineault}
% Use a smaller verbatim font to prevent overfull hboxes
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@verbatim}
{\verbatim@font}
{\verbatim@font\small}
{}{}
\makeatother
% Listing code
\usepackage{courier}
\usepackage[formats]{listings}
\lstdefinestyle{mystyle}{
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
frame=tB,
aboveskip=16pt,
belowskip=16pt,
keepspaces=true,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstdefineformat{Python}{~=\( \sim \)}
% Blockquotes
\usepackage[tikz]{bclogo}
\usepackage[most]{tcolorbox}
\usetikzlibrary{calc,shapes}
\makeatletter
\NewTColorBox{quotebox}{+O{}+m}{%
enhanced,
sharp corners,
frame hidden,
% borderline west={\kvtcb@left@rule}{-2pt}{black!50!white},
borderline west={4pt}{0pt}{black!30!white},
colback = white,
left=15pt,
#1,
}
\makeatother
\lstset{style=mystyle}
\bibliographystyle{abbrvnat}
% colors for hyperlinks
\hypersetup{colorlinks=true, allcolors=blue}
\title{Good Research Code handbook}
\author{Patrick Mineault}
\begin{document}
\maketitle
\frontmatter
\setcounter{tocdepth}{\subsectiontocdepth}
\tableofcontents
\part{Introduction}
[-FRONTMATTER-]
\mainmatter
\part{Lessons}
[-CONTENT-]
\backmatter
\part{Extras}
[-BACKMATTER-]
\end{document}
"""
import subprocess
def clean_input(md):
lines = []
in_citation = False
for line in md.split("\n"):
if in_citation:
if "```" in line:
in_citation = False
else:
lines.append("> " + line)
else:
if "{epigraph}" in line:
in_citation = True
elif "{dropdown}" in line:
lines.append(line.replace("dropdown", "admonition"))
elif "{margin}" in line:
lines.append(line.replace("{margin}", "{admonition} Note"))
elif "{tabbed}" in line:
lines.append(line.replace("{tabbed}", "{admonition}"))
else:
lines.append(line.replace("🌠", "").replace("🌈", ""))
return "\n".join(lines)
def process_one(name):
with open(f"docs/{name}.md", "r") as f:
md = f.read()
md = clean_input(md)
with open(f"tmp/{name}.md", "w") as f:
f.write(md)
process = subprocess.Popen(
["curvenote", "export", "tex", f"tmp/{name}.md"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
print(stderr.decode("utf-8"))
with open(f"tmp/exports/{name}.tex", "r") as f:
tex = f.read()
return tex
def clean_output(book):
lines = []
in_code = False
for line in book.split("\n"):
if ".svg" in line and "includegraphics" in line:
lines.append(line.replace("includegraphics", "includesvg"))
elif "caption*" in line:
lines.append(line.replace("caption*", "caption"))
elif r"\begin{verbatim}" in line:
lines.append(
line.replace(
r"\begin{verbatim}", r"\begin{lstlisting}[language=Python]"
)
)
in_code = True
elif r"\end{verbatim}" in line:
lines.append(line.replace(r"\end{verbatim}", r"\end{lstlisting}"))
in_code = False
elif r"\begin{quote}" in line:
lines.append(r"\begin{quotebox}{quote}")
elif r"\end{quote}" in line:
lines.append(r"\end{quotebox}")
else:
if in_code:
lines.append(
line.replace("- -", "--")
.replace(" - ", "-")
.replace("true -neutral -cookiecutter", "true-neutral-cookiecutter")
.replace(" -forge", "-forge")
.replace("| --", "|--")
.replace("egg -info", "egg-info")
.replace("sphinx -quickstart", "sphinx-quickstart")
.replace("non -integer", "non-integer")
.replace("codebook -testbucket", "codebook-testbucket")
)
else:
lines.append(line.replace("testing.md", "testing"))
return "\n".join(lines)
def assemble_onepager():
with open("docs/_toc.yml", "r") as f:
toc = yaml.safe_load(f)
print(toc)
# Copy files
process = subprocess.Popen(
["cp", "-r", "docs/figures", "tmp"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
print(stderr.decode("utf-8"))
book_parts = collections.defaultdict(str)
book_parts["Intro"] += process_one("front-print")
for part in toc["parts"]:
for chapter in part["chapters"]:
book_parts[part["caption"]] += process_one(chapter["file"])
the_map = {
"Intro": "[-FRONTMATTER-]",
"Lessons": "[-CONTENT-]",
"Extras": "[-BACKMATTER-]",
}
complete = template
for k, v in the_map.items():
part = clean_output(book_parts[k])
complete = complete.replace(v, part)
with open("tmp/exports/book-complete.tex", "w") as f:
f.write(complete)
if __name__ == "__main__":
assemble_onepager()