r/prusa • u/IronInEveryFire • 1d ago
Creality K1C Ignoring Speed Control - Follow Up Python Code
#!/usr/bin/env python3
"""k1c-tokenizer — reorder trailing F (feedrate) tokens in Klipper G-code.
For each non-comment, non-blank line: if the last token is a frequency /
feedrate setting (Klipper ``F`` parameter, e.g. ``F3000``), move that token
to immediately after the G-code command token. Relative order of other
parameters is preserved.
Creality K1C runs Klipper; "frequency" here means the standard feedrate ``F``
token (mm/min), not a printer-specific vibration/frequency M-code. Lines that
are only comments, blank, or lack a trailing ``F`` are left unchanged.
"""
from __future__ import annotations
import argparse
import re
import shutil
import sys
from pathlib import Path
# Klipper / Marlin-style feedrate parameter: F followed by a number
# (optional sign, integer or decimal). Case-insensitive.
F_TOKEN_RE = re.compile(r"^F[+-]?(?:\d+\.?\d*|\.\d+)$", re.IGNORECASE)
# Command token: G/M/T word, or a Klipper extended command (letters/underscores).
# First whitespace-separated token on a code line is treated as the command.
COMMENT_PREFIXES = (";",)
def is_f_token(token: str) -> bool:
return bool(F_TOKEN_RE.match(token))
def split_inline_comment(line: str) -> tuple[str, str]:
"""Split a line into code part and trailing `;` comment (if any).
Semicolons inside quoted strings are not expected in G-code; first `;`
starts the comment (Klipper convention).
"""
if ";" not in line:
return line, ""
code, comment = line.split(";", 1)
return code, ";" + comment
def reorder_line(line: str) -> str:
"""Reorder a single G-code line if its last token is an F feedrate.
Preserves original newline style (caller keeps line endings) and any
trailing inline comment. Leading/trailing whitespace on the code portion
is normalized to a single trailing space before an inline comment when
one is present; otherwise trailing whitespace on the code is dropped.
Blank and full-line comments are returned unchanged.
"""
# Preserve exact blank / full-line-comment lines (including whitespace-only).
stripped = line.strip()
if not stripped:
return line
if stripped.startswith(COMMENT_PREFIXES):
return line
code, comment = split_inline_comment(line.rstrip("\r\n"))
code_stripped = code.strip()
if not code_stripped:
return line # whitespace then comment only — leave alone
tokens = code_stripped.split()
if len(tokens) < 2:
return line
last = tokens[-1]
if not is_f_token(last):
return line
# Already command + F only — nothing to move.
if len(tokens) == 2:
return line
command, *rest = tokens
# Drop the trailing F; keep any earlier F tokens in their relative order.
middle = rest[:-1]
new_tokens = [command, last, *middle]
if new_tokens == tokens:
return line
new_code = " ".join(new_tokens)
ending = "\r\n" if line.endswith("\r\n") else ("\n" if line.endswith("\n") else "")
if comment.strip():
return f"{new_code} {comment.rstrip()}{ending}"
return f"{new_code}{ending}"
def process_text(text: str) -> tuple[str, int]:
"""Process full file text. Returns (new_text, number_of_lines_changed)."""
# Splitlines(keepends=True) handles \n, \r\n, and final line without newline.
lines = text.splitlines(keepends=True)
out: list[str] = []
changed = 0
for line in lines:
new_line = reorder_line(line)
if new_line != line:
changed += 1
out.append(new_line)
return "".join(out), changed
def resolve_input_path(explicit: str | None, tool_dir: Path) -> Path:
if explicit:
path = Path(explicit).expanduser()
if not path.is_file():
raise SystemExit(f"error: input file not found: {path}")
return path.resolve()
candidates = sorted(tool_dir.glob("*.gcode"))
# Also accept common casing variants on case-sensitive FS
if not candidates:
candidates = sorted(
p for p in tool_dir.iterdir() if p.is_file() and p.suffix.lower() == ".gcode"
)
candidates = sorted(set(candidates))
if not candidates:
raise SystemExit(
f"error: no .gcode file beside the tool ({tool_dir}). "
"Pass a path: k1c-tokenizer.py INPUT.gcode"
)
if len(candidates) > 1:
names = ", ".join(p.name for p in candidates)
raise SystemExit(
f"error: multiple .gcode files beside the tool ({names}). "
"Pass which one: k1c-tokenizer.py INPUT.gcode"
)
return candidates[0].resolve()
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="k1c-tokenizer",
description=(
"Move a trailing F (feedrate/frequency) token to immediately after "
"the G-code command on each line. Safe default: write *.reordered.gcode."
),
)
p.add_argument(
"input",
nargs="?",
default=None,
help="Path to a .gcode file (default: the only .gcode beside this script)",
)
p.add_argument(
"-o",
"--output",
default=None,
help="Output path (default: INPUT with .reordered.gcode suffix)",
)
p.add_argument(
"--in-place",
action="store_true",
help="Overwrite INPUT after writing a .bak backup",
)
p.add_argument(
"-n",
"--dry-run",
action="store_true",
help="Print how many lines would change; write nothing",
)
return p
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
tool_dir = Path(__file__).resolve().parent
src = resolve_input_path(args.input, tool_dir)
if args.in_place and args.output:
raise SystemExit("error: use either --in-place or -o/--output, not both")
text = src.read_text(encoding="utf-8", errors="replace")
new_text, changed = process_text(text)
if args.dry_run:
print(f"{src}: {changed} line(s) would change")
return 0
if changed == 0:
print(f"{src}: no changes needed")
if not args.in_place and args.output is None:
# Still produce an identical reordered copy for a predictable artifact,
# unless user asked for in-place (nothing to do) or custom -o.
pass
if args.in_place:
bak = src.with_suffix(src.suffix + ".bak")
shutil.copy2(src, bak)
src.write_text(new_text, encoding="utf-8")
print(f"{src}: reordered {changed} line(s); backup at {bak}")
return 0
if args.output:
out = Path(args.output).expanduser().resolve()
else:
# file.gcode → file.reordered.gcode
out = src.with_name(src.stem + ".reordered.gcode")
out.write_text(new_text, encoding="utf-8")
print(f"{src} → {out}: reordered {changed} line(s)")
return 0
if __name__ == "__main__":
sys.exit(main())