mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-12-06 11:47:58 -05:00
Name printer model ids after their vendor and model, and check them in CI (#18146)
* Give every printer model its own model id Several printer models shared a model id with another model, and the three Cubicon xCeler models had none, so printer connections, OrcaSonar and OrcaCloud could take a printer for the wrong model. Each model now has an id of its own, and models already in use with a connected printer keep theirs. * Fail profile checks when a printer model id is missing or shared Profile checks now fail when a printer model has no model id, uses one that another model in any bundle already has (ignoring case), or uses characters that printers and services cannot carry. The profile authoring guide gives the rule and how to choose a new id. * Name every printer model id after its vendor and model Printer model ids were a mix of hand-picked codes, some shared between models or as vague as "v1", so a printer could be taken for a different model. Every printer model outside Bambu Lab now has a readable id made from its vendor and model name, such as prusa-prusa-mk4s, while Bambu Lab models keep the codes their printers report. A printer added through a printer agent before this change has to be added again. * Fail profile checks on a printer model id its name does not give Profile checks now fail when a printer model outside Bambu Lab has no id, a hand-written one, or one another model shares, and generate-id writes the right id for new models. The profile authoring guide describes the rule. * Explain printer model id failures, including what a rename costs When a printer model's id is missing or doesn't match its vendor and model name, the profile check now gives the id to paste or the command that writes it. When the mismatch comes from renaming a model, it also warns that printers users added with the old id must be added again.
This commit is contained in:
1 parent
cb660ecfa5
commit
3143363b63
524 files changed
+1127
-581
No files matched your search
+236
-40
@@ -7,7 +7,7 @@ usage: python scripts/orca_profile_tool.py <command> [options]
|
||||
commands:
|
||||
check validate the whole tree -- what CI runs
|
||||
fix-variant resize the variant arrays check rejects
|
||||
generate-id write the filament_id / setting_id each profile's identity implies
|
||||
generate-id write the filament_id / setting_id / model_id each identity implies
|
||||
normalize rewrite profile files into their canonical shape
|
||||
trim delete profile files no <vendor>.json list references
|
||||
update-index regenerate the *_list sections of <vendor>.json
|
||||
@@ -36,8 +36,8 @@ the current index and can delete newly added, unindexed presets.
|
||||
Run from anywhere; "python scripts/orca_profile_tool.py --help" repeats this list
|
||||
and "... <command> --help" documents one command in full.
|
||||
|
||||
The two id rules are the heart of it. Both ids are pure functions of the thing
|
||||
they name, so nothing here is ever invented: the tool only writes the id the
|
||||
The three id rules are the heart of it. Each id is a pure function of the thing
|
||||
it names, so nothing here is ever invented: the tool only writes the id the
|
||||
rules below already imply, and a tree that already satisfies them is left
|
||||
untouched.
|
||||
|
||||
@@ -85,8 +85,24 @@ setting_id policy (see AGENTS.md "Critical Constraints"):
|
||||
base / template profiles do not.
|
||||
* Bambu (BBL) owns the authoritative "G*" setting_id space and is the only
|
||||
reserved vendor: its setting_ids are never rewritten, which keeps
|
||||
Bambu-synced presets backward compatible. That exemption is setting_id's
|
||||
alone — BBL's filament_ids are minted like every other vendor's.
|
||||
Bambu-synced presets backward compatible. BBL's filament_ids are minted
|
||||
like every other vendor's.
|
||||
|
||||
model_id policy:
|
||||
* model_id is a PRINTER MODEL id, the one devices, printer agents, OPCP
|
||||
discovery and Orca's cloud services match a printer by. Outside BBL it is
|
||||
readable and a pure function of the model's bundle and name:
|
||||
model_id = slug(<vendor folder>) + "-" + slug(<model name>)
|
||||
where slug lower-cases to ASCII, reads "+" as "plus", keeps a dot only
|
||||
between digits and joins the remaining words with "-". Prusa's "Prusa MK4S"
|
||||
is "prusa-prusa-mk4s". Renaming a model or moving it to another bundle
|
||||
changes the id BY DESIGN.
|
||||
* BBL keeps the codes its printers report about themselves (N1, BL-P001),
|
||||
which resources/printers/<model_id>.json is named after; the tool never
|
||||
writes them and check only requires one.
|
||||
* Ids are unique across the tree ignoring case, so two names in one bundle
|
||||
that differ only by punctuation are an error check reports; the remedy is
|
||||
a rename.
|
||||
|
||||
The effective-id resolution below is loader-faithful (PresetBundle.cpp
|
||||
load_vendor_configs_from_json): own filament_id key, else walk `inherits` within
|
||||
@@ -105,6 +121,7 @@ import posixpath
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
@@ -134,8 +151,9 @@ OFL = "OrcaFilamentLibrary"
|
||||
# not a vendor bundle, so an unscoped pass leaves it alone.
|
||||
USER_DIR = "user"
|
||||
|
||||
# Bambu (BBL) is the only vendor exempt from the setting_id rule: it keeps its
|
||||
# authoritative "G*" cloud ids. No vendor is exempt from the filament_id rule.
|
||||
# Bambu (BBL) is the only vendor exempt from the setting_id rule, keeping its
|
||||
# authoritative "G*" cloud ids, and from the model_id rule, keeping the model
|
||||
# codes its printers report. No vendor is exempt from the filament_id rule.
|
||||
RESERVED_VENDORS = {"BBL"}
|
||||
|
||||
# The profile types that carry a setting_id; the subdir name is also the type
|
||||
@@ -298,6 +316,7 @@ _JSON_STR = r'"(?:[^"\\]|\\.)*"'
|
||||
|
||||
GENERATE_CMD = "python scripts/orca_profile_tool.py generate-id"
|
||||
SETTING_ID_CMD = '"python scripts/orca_profile_tool.py generate-id --setting-id"'
|
||||
MODEL_ID_CMD = '"python scripts/orca_profile_tool.py generate-id --model-id"'
|
||||
BAMBU_MAP_HINT = 'regenerate the map with "python scripts/update_bambu_filament_ids.py" and commit the diff for maintainer review'
|
||||
NORMALIZE_HINT = 'try "python scripts/orca_profile_tool.py normalize" to fix common issues automatically'
|
||||
|
||||
@@ -391,6 +410,27 @@ def generate_filament_id(filament_vendor, filament_type, filament_name):
|
||||
return "OF" + _base62_tail(int.from_bytes(u.bytes, "big"), FILAMENT_ID_LENGTH)
|
||||
|
||||
|
||||
def _model_id_slug(text):
|
||||
"""Lower-case ASCII words joined by "-": "+" reads as "plus", and a dot is
|
||||
kept only between digits, so "2.4" stays distinct from "24"."""
|
||||
text = (unicodedata.normalize("NFKD", text).encode("ascii", "ignore")
|
||||
.decode("ascii").lower().replace("+", " plus "))
|
||||
text = re.sub(r"(?<=\d)\.(?=\d)", "\0", text)
|
||||
return re.sub(r"[^a-z0-9\0]+", "-", text).strip("-").replace("\0", ".")
|
||||
|
||||
|
||||
def generate_model_id(vendor, name):
|
||||
"""Readable model_id for a printer model: "<vendor>-<name>", slugged.
|
||||
|
||||
Prusa's "Prusa MK4S" mints "prusa-prusa-mk4s". The bundle prefix names the
|
||||
vendor in every id, and the whole id is a pure function of (bundle, model
|
||||
name), so renaming a model or moving it to another bundle changes its id.
|
||||
Returns "" when the name slugs to nothing.
|
||||
"""
|
||||
name_slug = _model_id_slug(name)
|
||||
return f"{_model_id_slug(vendor)}-{name_slug}" if name_slug else ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tree loading + loader-faithful effective-id resolution
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -935,6 +975,27 @@ def check_setting_id_uniqueness(profiles_dir):
|
||||
return errors
|
||||
|
||||
|
||||
def iter_machine_models(profiles_dir):
|
||||
"""Yield (vendor, relative path, data) for every machine_model file in the tree.
|
||||
|
||||
Walks the files on disk, indexed or not, so a cross-vendor check also sees a
|
||||
model whose index entry has not landed yet.
|
||||
"""
|
||||
for vendor in list_profile_dirs(profiles_dir):
|
||||
for path, _sub in iter_profile_files(os.path.join(profiles_dir, vendor)):
|
||||
if os.path.basename(path) in NON_PROFILE_FILES:
|
||||
continue
|
||||
try:
|
||||
data = load_json(path)
|
||||
except (ValueError, OSError):
|
||||
# Parse failures are reported by the checks that walk the same
|
||||
# files; reporting them here too would double-count.
|
||||
continue
|
||||
if isinstance(data, dict) and data.get("type") == "machine_model":
|
||||
yield (vendor, os.path.relpath(path, profiles_dir).replace(os.sep, "/"),
|
||||
data)
|
||||
|
||||
|
||||
def check_machine_model_name_uniqueness(profiles_dir):
|
||||
"""No two bundles may declare a machine_model with the same name.
|
||||
|
||||
@@ -955,22 +1016,10 @@ def check_machine_model_name_uniqueness(profiles_dir):
|
||||
"""
|
||||
errors = 0
|
||||
owners = defaultdict(list) # model name -> [relative path]
|
||||
for vendor in list_profile_dirs(profiles_dir):
|
||||
for path, _sub in iter_profile_files(os.path.join(profiles_dir, vendor)):
|
||||
if os.path.basename(path) in NON_PROFILE_FILES:
|
||||
continue
|
||||
try:
|
||||
data = load_json(path)
|
||||
except (ValueError, OSError):
|
||||
# Parse failures are reported by the checks that walk the same
|
||||
# files; reporting them here too would double-count.
|
||||
continue
|
||||
if not isinstance(data, dict) or data.get("type") != "machine_model":
|
||||
continue
|
||||
name = data.get("name")
|
||||
if name:
|
||||
owners[name].append(
|
||||
os.path.relpath(path, profiles_dir).replace(os.sep, "/"))
|
||||
for _vendor, rel, data in iter_machine_models(profiles_dir):
|
||||
name = data.get("name")
|
||||
if name:
|
||||
owners[name].append(rel)
|
||||
|
||||
for name, paths in sorted(owners.items()):
|
||||
if len(paths) < 2:
|
||||
@@ -984,6 +1033,76 @@ def check_machine_model_name_uniqueness(profiles_dir):
|
||||
return errors
|
||||
|
||||
|
||||
def check_machine_model_ids(profiles_dir):
|
||||
"""Every machine_model carries the model_id its bundle and name mint.
|
||||
|
||||
model_id is a printer model's identity outside the profiles:
|
||||
Preset::get_printer_type returns it, the send dialog and filament sync compare
|
||||
it with a connected printer's type, printer agents save it with each printer
|
||||
the user adds, OPCP printers report it in discovery, and OrcaSonar and
|
||||
OrcaCloud look printer models up by it. So every model needs one, and no two
|
||||
may share one.
|
||||
|
||||
Outside BBL the id is generate_model_id(vendor, name), so it is checked for
|
||||
equality with that mint. BBL keeps the codes its printers report about
|
||||
themselves (N1, BL-P001), which resources/printers/<model_id>.json is named
|
||||
after; those are only required to be present. Uniqueness, over the whole tree,
|
||||
ignores case: case-insensitive file systems fold per-id file names, and an id
|
||||
is typed by hand when a printer is set up.
|
||||
|
||||
Cross-vendor by nature, so it always runs over the whole tree, never narrowed
|
||||
by --vendor. Returns the error count.
|
||||
"""
|
||||
errors = 0
|
||||
owners = defaultdict(list) # lower-cased model_id -> [(model_id, relative path)]
|
||||
for vendor, rel, data in iter_machine_models(profiles_dir):
|
||||
name = data.get("name")
|
||||
model_id = data.get("model_id")
|
||||
where = f'{rel}: machine_model "{name or ""}"'
|
||||
if vendor in RESERVED_VENDORS:
|
||||
if not isinstance(model_id, str) or not model_id.strip():
|
||||
errors += 1
|
||||
print_error(f"{where} has no model_id; a {vendor} model carries the "
|
||||
f"code its printers report about themselves")
|
||||
continue
|
||||
elif isinstance(name, str) and name:
|
||||
expected = generate_model_id(vendor, name)
|
||||
if not expected:
|
||||
errors += 1
|
||||
print_error(f"{where} has a name that gives no model_id; name it "
|
||||
f"with ASCII letters or digits")
|
||||
continue
|
||||
if model_id is None or (isinstance(model_id, str) and not model_id.strip()):
|
||||
errors += 1
|
||||
print_error(f'{where} needs the model_id "{expected}", which its bundle '
|
||||
f"and name give; run {MODEL_ID_CMD} or paste it")
|
||||
continue
|
||||
if model_id != expected:
|
||||
errors += 1
|
||||
# A rename is the one legitimate way to get here, and its cost is
|
||||
# invisible in the diff, so the message names it.
|
||||
print_error(f"{where} has the model_id {json.dumps(model_id)} but its "
|
||||
f'bundle and name give "{expected}"; run {MODEL_ID_CMD} or '
|
||||
f"paste it. If you renamed the model, the new id is "
|
||||
f"expected: printers users added with the old id must be "
|
||||
f"added again")
|
||||
continue
|
||||
else:
|
||||
continue # a model with no name is reported by the name checks
|
||||
owners[model_id.lower()].append((model_id, rel))
|
||||
|
||||
for _key, entries in sorted(owners.items()):
|
||||
if len(entries) < 2:
|
||||
continue
|
||||
errors += 1
|
||||
spellings = " / ".join(sorted({model_id for model_id, _rel in entries}))
|
||||
files = ", ".join(sorted(rel for _model_id, rel in entries))
|
||||
print_error(f'model_id "{spellings}" is shared by {len(entries)} machine '
|
||||
f"models ({files}); a model_id identifies one printer model "
|
||||
f"across all bundles, ignoring case - rename one of the models")
|
||||
return errors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Per-vendor validation
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -2002,11 +2121,12 @@ def check_profiles(profiles_dir=PROFILES_DIR, vendors=None, strict=False):
|
||||
if remedies[category]:
|
||||
print_warning(f"{remedies[category]} {hint}")
|
||||
|
||||
# Cross-vendor checks: setting_id and machine_model name uniqueness and the
|
||||
# whole filament_id state, all validated over the entire tree regardless of
|
||||
# --vendor.
|
||||
# Cross-vendor checks: setting_id uniqueness, machine_model names and
|
||||
# model_ids, and the whole filament_id state, all validated over the entire
|
||||
# tree regardless of --vendor.
|
||||
errors_found += check_setting_id_uniqueness(profiles_dir)
|
||||
errors_found += check_machine_model_name_uniqueness(profiles_dir)
|
||||
errors_found += check_machine_model_ids(profiles_dir)
|
||||
errors_found += check_filament_ids(profiles_dir)
|
||||
|
||||
print("\n==================== SUMMARY ====================")
|
||||
@@ -2466,23 +2586,96 @@ def generate_setting_ids(profiles_dir=PROFILES_DIR, vendors=None, dry_run=False,
|
||||
return files_changed, errors
|
||||
|
||||
|
||||
def run_generate_id(profiles_dir, vendors, filament_id, setting_id, dry_run):
|
||||
def generate_model_ids(profiles_dir=PROFILES_DIR, vendors=None, dry_run=False,
|
||||
changed_paths=None):
|
||||
"""Make every machine_model carry the model_id its bundle and name mint.
|
||||
|
||||
BBL's models are left alone: they keep the codes their printers report.
|
||||
`changed_paths`, when a set is passed, collects the files that changed.
|
||||
Returns (files_changed, errors).
|
||||
"""
|
||||
_utf8_console()
|
||||
profiles_dir = str(profiles_dir)
|
||||
names = list_profile_dirs(profiles_dir)
|
||||
if vendors is not None:
|
||||
wanted = set(vendors)
|
||||
unknown = sorted(wanted - set(names))
|
||||
if unknown:
|
||||
for v in unknown:
|
||||
print_error(f'unknown vendor "{v}" in {profiles_dir}')
|
||||
return 0, len(unknown)
|
||||
names = [v for v in names if v in wanted]
|
||||
for v in sorted(wanted & RESERVED_VENDORS):
|
||||
print_info(f"{v} keeps the model_ids its printers report")
|
||||
|
||||
verb = "would " if dry_run else ""
|
||||
files_changed = errors = 0
|
||||
for vendor in names:
|
||||
if vendor in RESERVED_VENDORS:
|
||||
continue
|
||||
for path, _sub in iter_profile_files(os.path.join(profiles_dir, vendor)):
|
||||
if os.path.basename(path) in NON_PROFILE_FILES:
|
||||
continue
|
||||
try:
|
||||
data = load_json(path)
|
||||
except (ValueError, OSError) as e:
|
||||
print_error(f"unreadable profile {path}: {e}")
|
||||
errors += 1
|
||||
continue
|
||||
if not isinstance(data, dict) or data.get("type") != "machine_model":
|
||||
continue
|
||||
name = data.get("name")
|
||||
new_id = generate_model_id(vendor, name) if isinstance(name, str) else ""
|
||||
if not new_id:
|
||||
print_error(f"machine_model has no name that gives a model_id: {path}")
|
||||
errors += 1
|
||||
continue
|
||||
old_id = data.get("model_id")
|
||||
if old_id == new_id:
|
||||
continue
|
||||
if old_id is None:
|
||||
# After the last identifying key, so normalize's identity block stays
|
||||
# a prefix of the file.
|
||||
edit = lambda text, new=new_id: insert_key_line(
|
||||
text, "model_id", new, after=tuple(reversed(NORMALIZE_FIELD_ORDER)))
|
||||
else:
|
||||
edit = lambda text, new=new_id, old=old_id: replace_key_value(
|
||||
text, "model_id", new, old)
|
||||
try:
|
||||
_edit_profile(path, edit, dry_run)
|
||||
except (OSError, RuntimeError, ValueError) as e:
|
||||
print_error(str(e))
|
||||
errors += 1
|
||||
continue
|
||||
files_changed += 1
|
||||
if changed_paths is not None:
|
||||
changed_paths.add(os.path.normpath(path))
|
||||
rel = os.path.relpath(path, profiles_dir).replace(os.sep, "/")
|
||||
print_info(f'{verb}update {rel}: model_id {json.dumps(old_id)} -> "{new_id}"')
|
||||
|
||||
print_info(f"model_ids assigned : {files_changed}")
|
||||
return files_changed, errors
|
||||
|
||||
|
||||
def run_generate_id(profiles_dir, vendors, filament_id, setting_id, model_id, dry_run):
|
||||
"""The generate-id command: write the ids the tree's identities imply.
|
||||
|
||||
Returns the process exit code.
|
||||
"""
|
||||
# Both by default. filament_id runs first so its keys are in place before the
|
||||
# setting_id pass reads the files back.
|
||||
do_filament = filament_id or not setting_id
|
||||
do_setting = setting_id or not filament_id
|
||||
changed = set() # one file the two passes both touch is still one file
|
||||
# All three by default, or only the one asked for. filament_id runs first so
|
||||
# its keys are in place before the setting_id pass reads the files back.
|
||||
everything = not (filament_id or setting_id or model_id)
|
||||
changed = set() # one file two passes both touch is still one file
|
||||
errors = 0
|
||||
if do_filament:
|
||||
if filament_id or everything:
|
||||
_n, e = generate_filament_ids(profiles_dir, vendors, dry_run, changed)
|
||||
errors += e
|
||||
if do_setting:
|
||||
if setting_id or everything:
|
||||
_n, e = generate_setting_ids(profiles_dir, vendors, dry_run, changed)
|
||||
errors += e
|
||||
if model_id or everything:
|
||||
_n, e = generate_model_ids(profiles_dir, vendors, dry_run, changed)
|
||||
errors += e
|
||||
|
||||
summary = (f"dry run: {len(changed)} file(s) would change; nothing written"
|
||||
if dry_run else f"{len(changed)} file(s) changed")
|
||||
@@ -3602,8 +3795,8 @@ examples:
|
||||
orca_profile_tool.py check
|
||||
validate the whole tree, exactly as CI does
|
||||
orca_profile_tool.py check --vendor Creality
|
||||
the per-vendor checks for one bundle; setting_id and filament_id are
|
||||
cross-vendor properties, so those two always cover the whole tree
|
||||
the per-vendor checks for one bundle; setting_id, filament_id and model_id
|
||||
are cross-vendor properties, so those always cover the whole tree
|
||||
orca_profile_tool.py generate-id
|
||||
give every profile the id its identity mints, in every vendor bundle
|
||||
orca_profile_tool.py generate-id --dry-run
|
||||
@@ -3712,15 +3905,18 @@ def build_parser():
|
||||
"write the id each profile's identity implies",
|
||||
"Write the id every profile should carry: filament_id from each filament's\n"
|
||||
"(filament_vendor, filament_type, name) triple, setting_id from each preset's\n"
|
||||
"(vendor, type, name). Idempotent and byte-preserving.\n"
|
||||
"(vendor, type, name), model_id from each printer model's (vendor, name),\n"
|
||||
"BBL's models excepted. Idempotent and byte-preserving.\n"
|
||||
"\n"
|
||||
"The id is a function of the triple alone, so a narrowed run writes exactly\n"
|
||||
"what a full one would; check reports whatever it left outside.")
|
||||
which = generate_cmd.add_mutually_exclusive_group()
|
||||
which.add_argument("--filament-id", action="store_true", dest="filament_id",
|
||||
help="write filament_id only, skipping setting_id")
|
||||
help="write filament_id only")
|
||||
which.add_argument("--setting-id", action="store_true", dest="setting_id",
|
||||
help="write setting_id only, skipping filament_id")
|
||||
help="write setting_id only")
|
||||
which.add_argument("--model-id", action="store_true", dest="model_id",
|
||||
help="write model_id only")
|
||||
|
||||
normalize_cmd = add(
|
||||
"normalize", [vendor_opt, type_opt, dry_run_opt, profiles_opt],
|
||||
@@ -3839,7 +4035,7 @@ def main(argv=None):
|
||||
|
||||
if args.command == "generate-id":
|
||||
return run_generate_id(profiles_dir, vendors, args.filament_id, args.setting_id,
|
||||
args.dry_run)
|
||||
args.model_id, args.dry_run)
|
||||
|
||||
if args.command == "legacy-compat":
|
||||
return run_legacy_compat(args.base, profiles_dir, args.output, args.check)
|
||||
|
||||
Reference in new issue
Block a user