#!/usr/bin/env python3 """Fingerprint a slice sweep's G-code, and list the slices that differ between two sweeps. `OrcaSlicer_profile_validator -s -o ` slices a small scene through every shipped printer preset and saves one G-code file per slice. Two sweeps of the same sources give the same motion, but a few lines differ on every run or with the order of the slices: - "; generated by ... on ": the wall clock - the config block: every option, so one new option changes every file - "; model label id: ...", "... unique label id: N" and "; object ids of ...": ids from a process-wide counter, so they shift when an earlier slice is added or removed `fingerprint` drops those lines and hashes what is left. `compare` reads two fingerprint files and reports the slices whose G-code changed. Slice with ORCA_SOURCE_DATE_EPOCH set, so custom G-code that prints the time or calls random() repeats too. A slice whose output cannot repeat yet (fuzzy skin, random infill rotation) is listed as not compared. ORCA_SOURCE_DATE_EPOCH=1000000000 OrcaSlicer_profile_validator -p resources/profiles -s -o base python3 scripts/gcode_fingerprint.py fingerprint base -o base.tsv python3 scripts/gcode_fingerprint.py compare base.tsv head.tsv `compare` exits 0 when no slice changed, 1 when at least one did, and 2 on bad input, which includes two sweeps with no slice in common. A slice that exists in one sweep only is listed and does not count as changed. """ import argparse import hashlib import os import sys from dataclasses import dataclass, field CONFIG_BLOCK_START = b"; CONFIG_BLOCK_START" CONFIG_BLOCK_END = b"; CONFIG_BLOCK_END" TIMESTAMP_PREFIX = b"; generated by " MODEL_LABEL_PREFIX = b"; model label id: " OBJECT_LABEL_MARK = b"printing object, unique label id: " LAYER_OBJECT_IDS_PREFIX = b"; object ids of " # Options whose output does not repeat from one export to the next. FUZZY_SKIN_PREFIX = b"; fuzzy_skin = " FUZZY_SKIN_OFF = (b"none", b"disabled_fuzzy") ROTATE_TEMPLATE_PREFIXES = (b"; sparse_infill_rotate_template = ", b"; solid_infill_rotate_template = ") RANDOM_JOINTS = (b"~", b"^") UNSTABLE_DIGEST = "-" def normalise(data): """Return the G-code without the lines that differ between two runs of the same sources.""" kept = [] in_config_block = False for line in data.split(b"\n"): marker = line.rstrip() if in_config_block: in_config_block = marker != CONFIG_BLOCK_END continue if marker == CONFIG_BLOCK_START: in_config_block = True continue if marker == CONFIG_BLOCK_END: raise ValueError("config block closes without a CONFIG_BLOCK_START line") if line.startswith((TIMESTAMP_PREFIX, MODEL_LABEL_PREFIX, LAYER_OBJECT_IDS_PREFIX)) or OBJECT_LABEL_MARK in line: continue kept.append(line) if in_config_block: raise ValueError("config block opens without a CONFIG_BLOCK_END line") return b"\n".join(kept) def digest(data): """SHA-256 of the normalised G-code.""" return hashlib.sha256(normalise(data)).hexdigest() def unstable_reason(data): """Why this slice cannot be compared, or an empty string when it can.""" in_config_block = has_config_block = False for line in data.split(b"\n"): marker = line.rstrip() if marker == CONFIG_BLOCK_START: in_config_block = has_config_block = True elif marker == CONFIG_BLOCK_END: in_config_block = False elif in_config_block: _, _, value = marker.partition(b" = ") if line.startswith(FUZZY_SKIN_PREFIX) and value not in FUZZY_SKIN_OFF: return "fuzzy skin" if line.startswith(ROTATE_TEMPLATE_PREFIXES) and any(joint in value for joint in RANDOM_JOINTS): return "random infill rotation" # Without the config block there is no telling whether one of those options is on. return "" if has_config_block else "no config block" def fingerprint_dir(path): """(name, digest, reason) for every .gcode file in a folder, sorted by name.""" names = sorted(name for name in os.listdir(path) if name.endswith(".gcode")) if not names: raise ValueError(f"no .gcode files in {path}") rows = [] for file_name in names: name = file_name[: -len(".gcode")] if any(separator in name for separator in "\t\r\n"): raise ValueError(f"file name has a tab or a line break: {file_name!r}") with open(os.path.join(path, file_name), "rb") as f: data = f.read() try: reason = unstable_reason(data) rows.append((name, UNSTABLE_DIGEST if reason else digest(data), reason)) except ValueError as error: raise ValueError(f"{file_name}: {error}") from error return rows def write_fingerprints(rows, out): for name, sha, reason in rows: out.write(f"{name}\t{sha}\t{reason}\n") def read_fingerprints(path): """{name: (digest, reason)} from a file written by write_fingerprints.""" slices = {} with open(path, encoding="utf-8") as f: for number, line in enumerate(f, 1): fields = line.rstrip("\r\n").split("\t") if len(fields) != 3 or not fields[0] or not fields[1]: raise ValueError(f"{path}, line {number}: expected name, digest and reason separated by tabs") if (fields[1] == UNSTABLE_DIGEST) != bool(fields[2]): raise ValueError(f"{path}, line {number}: a slice has either a digest or a reason it was not hashed") if fields[0] in slices: raise ValueError(f"{path}, line {number}: slice {fields[0]!r} is listed twice") slices[fields[0]] = (fields[1], fields[2]) return slices @dataclass class Report: changed: list = field(default_factory=list) only_base: list = field(default_factory=list) only_head: list = field(default_factory=list) not_compared: list = field(default_factory=list) # (name, reason) same_count: int = 0 def compare(base, head): report = Report() for name in sorted(base.keys() | head.keys()): if name not in head: report.only_base.append(name) elif name not in base: report.only_head.append(name) else: reason = base[name][1] or head[name][1] if reason: report.not_compared.append((name, reason)) elif base[name][0] != head[name][0]: report.changed.append(name) else: report.same_count += 1 return report def _grouped(names, limit): """Lines listing slice names under their vendor, the part before the first "__".""" groups = {} for name in names: vendor, _, rest = name.partition("__") groups.setdefault(vendor, []).append(rest or vendor) lines = [] for vendor in sorted(groups): slices = groups[vendor] lines.append(f" {vendor} ({len(slices)})") lines.extend(f" {name}" for name in slices[:limit]) if len(slices) > limit: lines.append(f" ... and {len(slices) - limit} more") return lines def format_report(report, limit): compared = report.same_count + len(report.changed) if report.changed: lines = [f"G-code changed for {len(report.changed)} of {compared} compared slices"] lines += _grouped(report.changed, limit) else: lines = [f"G-code is the same for all {compared} compared slices"] if report.only_base: lines.append(f"Only in base ({len(report.only_base)})") lines += _grouped(report.only_base, limit) if report.only_head: lines.append(f"Only in head ({len(report.only_head)})") lines += _grouped(report.only_head, limit) if report.not_compared: lines.append(f"Not compared ({len(report.not_compared)})") lines += [f" {name}: {reason}" for name, reason in report.not_compared] return "\n".join(lines) + "\n" def _positive_int(text): try: value = int(text) except ValueError: value = 0 if value < 1: raise argparse.ArgumentTypeError("must be a whole number, at least 1") return value def main(argv=None): parser = argparse.ArgumentParser(description="Fingerprint a slice sweep's G-code and compare two sweeps.") commands = parser.add_subparsers(dest="command", required=True) fingerprint = commands.add_parser("fingerprint", help="hash every .gcode file in a folder") fingerprint.add_argument("gcode_dir", help="folder written by OrcaSlicer_profile_validator -s -o") fingerprint.add_argument("-o", "--output", help="fingerprint file to write (default: standard output)") comparison = commands.add_parser("compare", help="list the slices that differ between two fingerprint files") comparison.add_argument("base", help="fingerprint file of the sweep to compare against") comparison.add_argument("head", help="fingerprint file of the sweep under test") comparison.add_argument("--limit", type=_positive_int, default=20, help="slice names shown per vendor (default: 20)") args = parser.parse_args(argv) try: if args.command == "fingerprint": rows = fingerprint_dir(args.gcode_dir) if args.output: with open(args.output, "w", encoding="utf-8", newline="\n") as out: write_fingerprints(rows, out) else: # The same bytes as the file: redirected output on Windows would otherwise get CRLF # line ends and the console code page. sys.stdout.reconfigure(encoding="utf-8", newline="\n") write_fingerprints(rows, sys.stdout) return 0 report = compare(read_fingerprints(args.base), read_fingerprints(args.head)) if report.same_count + len(report.changed) == 0: raise ValueError(f"{args.base} and {args.head} have no slice in common to compare") sys.stdout.write(format_report(report, args.limit)) return 1 if report.changed else 0 except (OSError, ValueError) as error: print(f"error: {error}", file=sys.stderr) return 2 if __name__ == "__main__": sys.exit(main())