Every setup sheet starts accurate. Then the programmer swaps a 10 mm endmill for a 12, edits the program, and forgets the Word document. Three months later an operator loads T7 per the sheet, the program calls a different tool, and the best case is a scrapped part. The problem isn't carelessness. The problem is that the setup sheet is a second copy of information that already lives in the NC program, maintained by hand.
The fix is to stop maintaining it. Generate the sheet from the program, every time it's released: the tool list, the work offsets, the program number, and a fingerprint of the exact file it describes. This post builds that generator in about 100 lines of Python.
What belongs on a setup sheet (and where it comes from)
| Field | Source | Automatable? |
|---|---|---|
| Program number & name | O word and header comment in the NC file | Yes |
| Tool list: T number, description | T__ M6 lines plus the CAM's tool comments | Yes |
| Work offsets used | G54–G59 / G54.1 P__ in the program | Yes |
| Spindle speeds & feeds per tool | S and F words after each tool change | Yes |
| Estimated cycle time | Your CAM, or a G-code time estimate | Yes |
| Fixture, stock size, datum photo | The programmer | No: keep a small YAML file per job |
| Revision & program fingerprint | Hash of the NC file | Yes, and it's the most important line |
Your CAM already writes most of this
Mastercam, Fusion, and most posts emit tool comments like (T7 | 12MM FLAT ENDMILL | H7). Parsing the NC file instead of the CAM project means the generator works no matter which CAM made the program, and it describes what will actually run, including hand edits made at the machine.
Step 1: parse the program
You don't need a full G-code parser. A handful of regular expressions recover everything above, because posted code is extremely regular. (If you want the deeper version, generating G-code from Python covers the structure in detail.)
import hashlib, re
from pathlib import Path
TOOL_CHANGE = re.compile(r"\bT(\d+)\s*M0?6\b")
COMMENT = re.compile(r"\(([^)]*)\)")
OFFSET = re.compile(r"\bG5[4-9](?:\.1\s*P\d+)?\b")
PROGRAM = re.compile(r"^\s*[O:](\d{1,5})", re.M)
def fingerprint(text):
"""Hash the program, ignoring the (FP ...) line the release script inserts."""
body = "\n".join(l for l in text.splitlines() if not l.lstrip().startswith("(FP "))
return hashlib.sha256(body.encode()).hexdigest()[:8].upper()
def parse_nc(path):
text = Path(path).read_text(errors="replace")
tools, offsets, current = {}, [], None
for line in text.splitlines():
code = COMMENT.sub("", line) # don't match words inside comments
if m := TOOL_CHANGE.search(code):
current = int(m[1])
tools.setdefault(current, {"t": current, "desc": "", "s": set(), "f": set()})
if c := COMMENT.search(line): # comment on the tool-change line
tools[current]["desc"] = c[1].strip()
if current is not None:
if m := re.search(r"\bS(\d+)", code): tools[current]["s"].add(int(m[1]))
if m := re.search(r"\bF(\d+\.?\d*)", code): tools[current]["f"].add(float(m[1]))
for o in OFFSET.findall(code):
if o not in offsets:
offsets.append(o)
prog = PROGRAM.search(text)
return {
"program": prog[1] if prog else Path(path).stem,
"title": (COMMENT.search(text) or [None, ""])[1],
"tools": sorted(tools.values(), key=lambda t: t["t"]),
"offsets": offsets,
"sha": fingerprint(text),
"lines": text.count("\n") + 1,
}Two choices here save headaches later. Comments are stripped before matching codes, so (DRILL T5 HOLES) doesn't register as a tool change. And the hash is computed over the exact bytes the operator will load, which is what makes it useful on the shop floor (more on that below).
Step 2: the template is just HTML
Laying out a PDF in code, coordinate by coordinate, is miserable. Instead, write the sheet as an HTML page with print CSS, fill it with Jinja2, and let WeasyPrint turn it into a PDF. Anyone who can edit a web page can now change the layout, and you get real tables, page numbers, and repeating headers for free.
<!-- setup_sheet.html -->
<style>
@page { size: Letter; margin: 12mm;
@bottom-right { content: "Page " counter(page) " of " counter(pages); font-size: 9pt; } }
body { font-family: "DejaVu Sans", sans-serif; font-size: 10pt; }
h1 { font-size: 16pt; margin: 0; }
.fingerprint { font: bold 14pt monospace; border: 2px solid #000; padding: 4px 8px; }
table { width: 100%; border-collapse: collapse; margin-top: 8px; }
th, td { border: 1px solid #444; padding: 4px 6px; text-align: left; }
thead { display: table-header-group; } /* repeat header on every page */
tr { page-break-inside: avoid; }
</style>
<h1>O{{ nc.program }} — {{ job.part }}</h1>
<p>{{ nc.title }} · Rev {{ job.rev }} · Fixture: {{ job.fixture }} · Stock: {{ job.stock }}</p>
<p>Program fingerprint: <span class="fingerprint">{{ nc.sha }}</span>
— must match the first comment line on the control.</p>
<p><b>Work offsets:</b> {{ nc.offsets | join(", ") }}</p>
<table>
<thead><tr><th>T</th><th>Description</th><th>RPM</th><th>Feed</th><th>Checked</th></tr></thead>
{% for t in nc.tools %}
<tr><td>T{{ t.t }}</td><td>{{ t.desc }}</td>
<td>{{ t.s | sort | join(" / ") }}</td><td>{{ t.f | sort | join(" / ") }}</td><td>☐</td></tr>
{% endfor %}
</table>
{% if job.photo %}<img src="{{ job.photo }}" style="max-width:100%; margin-top:10px">{% endif %}
<p>{{ job.notes }}</p>Step 3: render it
import sys, yaml # pip install jinja2 weasyprint pyyaml
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
def build_sheet(nc_path, job_yaml, out_pdf):
nc = parse_nc(nc_path)
job = yaml.safe_load(Path(job_yaml).read_text()) # part, rev, fixture, stock, photo, notes
env = Environment(loader=FileSystemLoader("templates"), autoescape=True)
html = env.get_template("setup_sheet.html").render(nc=nc, job=job)
# base_url lets the template reference the fixture photo by relative path
HTML(string=html, base_url=str(Path(job_yaml).parent)).write_pdf(out_pdf)
return nc["sha"]
if __name__ == "__main__":
print("fingerprint:", build_sheet(*sys.argv[1:4]))WeasyPrint on Windows needs Pango
WeasyPrint is pure Python on top, but it renders with the Pango text library underneath. On Linux and macOS that's one package-manager command; on Windows, follow the WeasyPrint docs' install steps (it's a one-time setup). If that's a non-starter on locked-down shop PCs, fpdf2 is pure Python with no system dependencies. You give up the HTML template and lay out cells in code instead.
The fingerprint: the line that prevents the crash
The 8-character hash is the most valuable thing on the sheet. Have your release script insert it as a comment on the program's second line, (FP 3A9C41D7), then generate the sheet from the final file. Now the operator has a one-glance check: the code on the screen matches the code on the paper, or it doesn't. If someone edits the program after release, the next generated sheet gets a new fingerprint, and the old printed sheet visibly disagrees with the control.
That's why fingerprint() skips lines starting with (FP : inserting the stamp into the file must not change the hash it stamps.
Wire it into the release, not into someone's memory
- Generate on release. When a program moves from
/draftsto/released, a script (or a scheduled task watching the folder) builds the PDF beside it. Nobody "remembers to update the sheet" because nobody updates it. - Name files by fingerprint.
O1234_3A9C41D7.pdfmakes stale printouts obvious in the folder, too. - Put a QR code on it. The
segnoorqrcodelibrary can render a code linking to the released program folder or the job in your ERP; the template just needs an<img>. - Keep the job YAML in version control with the program. Fixture changes then have a history, too.
A setup sheet that's generated from the program can be wrong only if the program is wrong, and then you've got a different, much more visible problem.
This is the same pattern as replacing the shop's Excel sheets with ToolLink: find the information that's being copied by hand, pick one source of truth, and generate everything else from it. If your tool data lives in spreadsheets today, openpyxl can pull tool descriptions straight into the sheet, too.


