Преглед на файлове

Spoolman: subtype and colour from a product-style filament name (#3561)

- Spoolman has no subtype or colour-name field; Bambuddy only read
  names it writes itself ("PLA Matte"), so "Matte Scarlet Red" got
  the whole name as subtype and the colour was left blank
- split_spoolman_filament_name(): finish words (KNOWN_FINISHES) are
  the subtype, the rest is the colour, the material is removed
  wherever it stands; names Bambuddy writes read back unchanged
- A colour from the name counts as set, so the form shows it; a
  stored bambu_color_name still wins
- Saving a spool no longer renames its Spoolman filament to
  "<material> <subtype>" unless material or subtype changed; the
  update route reads the subtype with the same helper
- Tests: the reported names, round trip, punctuation, the save path
  keeping and rebuilding the name
maziggy преди 6 дни
родител
ревизия
7121c50d00

+ 1 - 0
CHANGELOG.md

@@ -32,6 +32,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **Spoolman mode reads the subtype and colour from a filament named after its product (#3561, reported by @ARGACE)** — Spoolman has no subtype or colour-name field, so Bambuddy reads both from the filament's name, and it only understood names it writes itself ("PLA Matte"). A filament named "Matte Scarlet Red", "Silk+ Baby Blue" or "Gold - Basic PLA" got its whole name as the subtype and no colour, so the spool form left the colour blank. The finish words (Basic, Matte, Silk, HF, ...) are now the subtype and the rest of the name is the colour, wherever the material stands in it. Saving a spool also renamed its Spoolman filament to "material subtype" on every save; the name is now only rebuilt when the material or subtype is changed.
 - **Spool labels print Chinese, Japanese and Korean (#3560, reported by @mohan456-wqs)** — Since labels embed Liberation Sans (#3553), every character was drawn in that font, which has no Chinese, Japanese or Korean, so names in those languages came out as empty boxes in the PDF and in the preview. Installing fonts in the container could not help, because labels only use the fonts Bambuddy embeds. A character Liberation Sans lacks is now drawn in Droid Sans Fallback (Chinese and Japanese) or Noto Sans KR (Korean), and only the characters a label uses are embedded. Long names are shortened by their real printed width. These fonts have no bold or italic, so CJK text on a bold or italic line prints in regular weight.
 - **A slot set to a support filament is a support slot (#3559)** — BambuStudio puts a support filament into an AMS slot as **PLA-S** (or **PA-S**), and a plate sliced with one asks for that type. Bambuddy wrote plain **PLA** instead, whether the slot was set with **Configure**, by assigning a spool or by linking a Spoolman spool, so a slot holding Support For PLA was offered to every PLA part and to nothing that needed support. Support W and Support For PLA/PETG came out as PLA and PETG. Bambu's support filaments now get Bambu's type, and a third-party or user preset whose name says "Support" gets PLA-S or PA-S over PLA or PA. Slots set up before this keep PLA until they are configured again. The spool form's built-in list, shown when no other preset source is available, also had wrong filament ids for most entries (Bambu PLA-CF was filed under Support W); they now match Bambu's.
 - **A group of weighed spools no longer shows a false weight mismatch** — With **Group** on, the collapsed row of a group compared the first spool's scale reading with the weight of the whole group, so a group of two or more weighed spools always showed a mismatch, and its **Sync** button re-synced only the first spool. The group row now shows no weight check; each spool in the expanded group keeps its own.

+ 67 - 7
backend/app/api/routes/_spoolman_helpers.py

@@ -14,6 +14,7 @@ from typing import Any
 from typing_extensions import TypedDict
 
 from backend.app.api.routes._url_safety import assert_safe_lan_service_url
+from backend.app.utils.filament_finish import KNOWN_FINISHES, finishes
 
 logger = logging.getLogger(__name__)
 
@@ -109,6 +110,66 @@ def assert_safe_spoolman_url(url: str) -> None:
 # Six characters, or eight when the filament carries an alpha byte. The write
 # side stores eight only for genuinely translucent spools (#2912); rejecting
 # them here turned every clear spool into neutral grey on read.
+# Spoolman has no subtype or colour-name field, only the filament's name, so
+# both are read out of it. Finish phrases longest first, so "Dual Color" is
+# taken before anything inside it.
+_FINISH_PHRASES: tuple[tuple[str, ...], ...] = tuple(
+    sorted((tuple(f.split()) for f in KNOWN_FINISHES), key=len, reverse=True)
+)
+# Punctuation that only separates parts of a name: "Gold - Basic PLA".
+_NAME_PUNCT = "-\u2013\u2014,/|()[]:;"
+
+
+def split_spoolman_filament_name(material: str | None, name: str | None) -> tuple[str | None, str | None]:
+    """(subtype, colour name) from a Spoolman filament's name (#3561).
+
+    Bambuddy writes a filament as ``"<material> <subtype>"`` ("PLA Matte"), and
+    that is all this used to read: the material came off the front and the
+    rest was the subtype. Spoolman users name a filament after the product --
+    "Matte Scarlet Red", "Silk+ Baby Blue", "Gold - Basic PLA" -- and then the
+    whole name became the subtype and the colour was left unnamed.
+
+    The material is removed wherever it stands. The finishes Bambuddy knows
+    (``KNOWN_FINISHES``: Basic, Matte, Silk, ...) are the subtype, as written,
+    and the rest is the colour. A name with no finish keeps the old reading
+    when it starts with the material, so a subtype Bambuddy wrote that is no
+    finish ("PLA Engineering") still comes back as the subtype -- unless the
+    material already carries the finish ("PLA Matte" / "PLA Matte Grey"), where
+    what follows can only be the colour.
+    """
+    mat = (material or "").strip()
+    text = (name or "").strip()
+    starts_with_material = bool(mat) and bool(re.match(rf"{re.escape(mat)}(?![\w-])", text, flags=re.IGNORECASE))
+    if starts_with_material:
+        rest = text[len(mat) :]
+    elif mat:
+        rest = re.sub(rf"(?<![\w-]){re.escape(mat)}(?![\w-])", " ", text, count=1, flags=re.IGNORECASE)
+    else:
+        rest = text
+
+    tokens = [t.strip(_NAME_PUNCT) for t in rest.split()]
+    tokens = [t for t in tokens if t and any(ch.isalnum() for ch in t)]
+    finish_words: list[str] = []
+    colour_words: list[str] = []
+    i = 0
+    while i < len(tokens):
+        for phrase in _FINISH_PHRASES:
+            window = tokens[i : i + len(phrase)]
+            if tuple(t.lower().rstrip("+") for t in window) == phrase:
+                finish_words.extend(window)
+                i += len(phrase)
+                break
+        else:
+            colour_words.append(tokens[i])
+            i += 1
+
+    if finish_words:
+        return " ".join(finish_words), " ".join(colour_words) or None
+    if starts_with_material and not finishes(mat):
+        return rest.strip() or None, None
+    return None, " ".join(colour_words) or None
+
+
 _COLOR_HEX_RE = re.compile(r"^[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$")
 _TAG_HEX_RE = re.compile(r"^[0-9A-F]+$")
 
@@ -400,13 +461,10 @@ def _map_spoolman_spool(spool: dict) -> MappedSpoolFields:
         elif 8 <= len(uid) <= 30:
             tag_uid = tag_uid or uid
 
-    # Subtype = filament name with material prefix stripped
+    # Subtype and colour from the filament's name (#3561).
     material: str = (filament.get("material") or "").strip()
     filament_name: str = (filament.get("name") or "").strip()
-    if material and filament_name.upper().startswith(material.upper()):
-        subtype: str | None = filament_name[len(material) :].strip() or None
-    else:
-        subtype = filament_name or None
+    subtype, name_color = split_spoolman_filament_name(material, filament_name)
 
     # Colour: validate as 6- or 8-char hex; fall back to neutral grey for invalid
     # values. An 8-char value already carries its alpha, so appending the opaque
@@ -487,14 +545,16 @@ def _map_spoolman_spool(spool: dict) -> MappedSpoolFields:
     #   2. filament.color_name (forward-compat — picks up the value if a
     #      future Spoolman release adds the field, or if an admin populated
     #      it via a custom extra-field they registered themselves)
-    #   3. subtype (synth fallback so the inventory list isn't a sea of
+    #   3. the colour named in the filament's name ("Matte Scarlet Red" ->
+    #      "Scarlet Red", #3561). The user wrote it, so it counts as set.
+    #   4. subtype (synth fallback so the inventory list isn't a sea of
     #      "Unknown color" entries on installs with neither field set)
     #
     # color_name_is_synthesized = True only when we fell back to subtype.
     # The edit form uses it to leave the input blank, so the user doesn't
     # round-trip the synth value back as if they had set it.
     extra_color_name = _extract_extra_str(extra, "bambu_color_name") or None
-    stored_color_name = extra_color_name or (filament.get("color_name") or None)
+    stored_color_name = extra_color_name or (filament.get("color_name") or None) or name_color
     color_name: str | None = stored_color_name or subtype or None
     color_name_is_synthesized: bool = stored_color_name is None and color_name is not None
 

+ 10 - 4
backend/app/api/routes/spoolman_inventory.py

@@ -34,6 +34,7 @@ from backend.app.api.routes._spoolman_helpers import (
     _safe_optional_float,
     assert_safe_spoolman_url,
     cost_per_kg_to_spoolman_price,
+    split_spoolman_filament_name,
     spoolman_cost_per_kg,
     spoolman_net_weight,
     spoolman_price_weight,
@@ -873,10 +874,9 @@ async def update_spool(
     cur_vendor: dict = cur_filament.get("vendor") or {}
     cur_mat: str = (cur_filament.get("material") or "").strip()
     cur_name: str = (cur_filament.get("name") or "").strip()
-    if cur_mat and cur_name.upper().startswith(cur_mat.upper()):
-        cur_subtype: str = cur_name[len(cur_mat) :].strip()
-    else:
-        cur_subtype = cur_name
+    # Read the same way the inventory shows it, so an untouched subtype is
+    # recognised as untouched below (#3561).
+    cur_subtype: str = split_spoolman_filament_name(cur_mat, cur_name)[0] or ""
 
     # Resolve final values: use request value if provided, else keep current
     material = data.material if data.material is not None else cur_mat
@@ -944,6 +944,12 @@ async def update_spool(
     # filament in place when it's a singleton.
     cur_filament_id = cur_filament.get("id")
     desired_name = f"{material} {subtype}".strip() if subtype else material
+    # The filament keeps the name it has unless its material or subtype was
+    # actually changed. The name is the user's own wording in Spoolman --
+    # "Matte Scarlet Red" carries the colour too -- and rebuilding it from the
+    # two fields renamed it on every save of anything at all (#3561).
+    if cur_name and material.strip() == cur_mat and (subtype or "").strip() == cur_subtype:
+        desired_name = cur_name
     # Compare the stored shapes, not raw strings and not bare RGB prefixes. Raw
     # strings make an opaque spool's six characters differ from an incoming eight
     # and PATCH the filament on every no-op edit; bare prefixes make an

+ 5 - 5
backend/tests/integration/test_ams_slot_material_2902.py

@@ -312,10 +312,10 @@ class TestSpoolmanInventoryAssign:
 
         assert sent["tray_type"] == "PLA"
         assert sent["tray_info_idx"] == "GFL99"
-        # Exactly, not just "contains PLA+": the filament's own name is in this
-        # string too, so a substring check would pass even if the material had
-        # been reduced before it was built.
-        assert sent["tray_sub_brands"] == "eSUN PLA+ Cool White"
+        # Exactly, not just "contains PLA+", so a reduced material would show.
+        # The filament's name "Cool White" is its colour (#3561), which is not
+        # part of the sub-brand.
+        assert sent["tray_sub_brands"] == "eSUN PLA+"
 
     @pytest.mark.asyncio
     @pytest.mark.integration
@@ -440,7 +440,7 @@ class TestSpoolmanLink:
 
         assert sent["tray_type"] == "PLA"
         assert sent["tray_info_idx"] == "GFL99"
-        assert sent["tray_sub_brands"] == "eSUN PLA+ Cool White"
+        assert sent["tray_sub_brands"] == "eSUN PLA+"  # "Cool White" is the colour (#3561)
         assert (sent["nozzle_temp_min"], sent["nozzle_temp_max"]) == (190, 230)
 
     @pytest.mark.asyncio

+ 75 - 0
backend/tests/integration/test_spoolman_filament_name_save_3561.py

@@ -0,0 +1,75 @@
+"""Saving a Spoolman spool leaves the filament's name alone (#3561).
+
+The update route rebuilt the filament's name as "<material> <subtype>" and
+PATCHed it whenever that differed from the stored one -- so saving any change
+to a spool whose filament is called "Matte Scarlet Red" renamed it in Spoolman.
+With the name now read as subtype "Matte" and colour "Scarlet Red", the same
+rule would have cut it down to "PLA Matte" and lost the colour from the name.
+The name is only rebuilt when material or subtype is actually changed.
+"""
+
+import pytest
+from httpx import AsyncClient
+
+from backend.tests.integration.test_spoolman_inventory_api import (  # noqa: F401  (fixtures)
+    SAMPLE_SPOOLMAN_SPOOL,
+    mock_spoolman_client,
+    spoolman_settings,
+)
+
+PRODUCT_NAMED = {
+    **SAMPLE_SPOOLMAN_SPOOL,
+    "filament": {**SAMPLE_SPOOLMAN_SPOOL["filament"], "name": "Matte Scarlet Red", "material": "PLA"},
+}
+
+
+@pytest.fixture
+def product_named(mock_spoolman_client):  # noqa: F811
+    mock_spoolman_client.get_spool.return_value = PRODUCT_NAMED
+    return mock_spoolman_client
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_saving_the_form_unchanged_does_not_rename_the_filament(
+    async_client: AsyncClient,
+    spoolman_settings,  # noqa: F811
+    product_named,
+):
+    """What the form sends back: the subtype and colour it was shown."""
+    response = await async_client.patch(
+        "/api/v1/spoolman/inventory/spools/42",
+        json={"material": "PLA", "subtype": "Matte", "color_name": "Scarlet Red", "note": "moved to shelf 2"},
+    )
+
+    assert response.status_code == 200
+    product_named.patch_filament.assert_not_called()
+    product_named.find_or_create_filament.assert_not_called()
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_a_colour_change_keeps_the_name_too(
+    async_client: AsyncClient,
+    spoolman_settings,  # noqa: F811
+    product_named,
+):
+    response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"rgba": "0000FFFF"})
+
+    assert response.status_code == 200
+    product_named.patch_filament.assert_called_once()
+    assert product_named.patch_filament.call_args.args[1]["name"] == "Matte Scarlet Red"
+
+
+@pytest.mark.asyncio
+@pytest.mark.integration
+async def test_changing_the_subtype_still_renames_it(
+    async_client: AsyncClient,
+    spoolman_settings,  # noqa: F811
+    product_named,
+):
+    response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json={"subtype": "Silk"})
+
+    assert response.status_code == 200
+    product_named.patch_filament.assert_called_once()
+    assert product_named.patch_filament.call_args.args[1]["name"] == "PLA Silk"

+ 91 - 0
backend/tests/unit/test_spoolman_filament_name_3561.py

@@ -0,0 +1,91 @@
+"""Subtype and colour from a Spoolman filament's name (#3561).
+
+Spoolman has neither field, only the filament's name. Bambuddy writes that as
+"<material> <subtype>", and that was all it could read back: a filament named
+after the product -- "Matte Scarlet Red" -- got the whole name as its subtype
+and no colour, so the spool form showed the colour blank.
+"""
+
+import pytest
+
+from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool, split_spoolman_filament_name
+
+
+@pytest.mark.parametrize(
+    ("material", "name", "subtype", "colour"),
+    [
+        # The three shapes from the report.
+        ("PLA", "Matte Scarlet Red", "Matte", "Scarlet Red"),
+        ("PLA", "Silk+ Baby Blue", "Silk+", "Baby Blue"),
+        ("PLA", "Gold - Basic PLA", "Basic", "Gold"),
+        # Punctuation attached to a word is a separator too.
+        ("PLA", "Scarlet Red (Matte)", "Matte", "Scarlet Red"),
+        ("PLA", "Matte, Scarlet Red", "Matte", "Scarlet Red"),
+        # The line in the material, the colour in the name.
+        ("PLA Matte", "PLA Matte Grey", None, "Grey"),
+        # A material and a finish at the front.
+        ("PLA", "PLA Basic Red", "Basic", "Red"),
+        ("PETG", "PETG HF Black", "HF", "Black"),
+        ("PLA", "PLA Dual Color Red Blue", "Dual Color", "Red Blue"),
+        # Only a colour.
+        ("PLA", "Scarlet Red", None, "Scarlet Red"),
+        ("", "Jade White", None, "Jade White"),
+        ("PLA", "PLA", None, None),
+        ("PLA", "", None, None),
+    ],
+)
+def test_the_name_splits_into_subtype_and_colour(material, name, subtype, colour):
+    assert split_spoolman_filament_name(material, name) == (subtype, colour)
+
+
+@pytest.mark.parametrize(
+    ("material", "name", "subtype"),
+    [
+        ("PLA", "PLA Matte", "Matte"),
+        ("PLA Matte", "PLA Matte Matte", "Matte"),
+        # A subtype that is no finish still comes back as the subtype: the name
+        # starts with the material, which is how Bambuddy writes it.
+        ("PLA", "PLA Engineering", "Engineering"),
+        ("PLA", "PLA Jade White", "Jade White"),
+    ],
+)
+def test_a_name_bambuddy_wrote_reads_back_as_it_was_written(material, name, subtype):
+    assert split_spoolman_filament_name(material, name) == (subtype, None)
+
+
+def test_the_material_is_only_taken_as_a_whole_word():
+    """PLA-CF is not PLA followed by "-CF"."""
+    assert split_spoolman_filament_name("PLA", "Black PLA-CF") == (None, "Black PLA-CF")
+
+
+def _spool(name, material="PLA", extra=None):
+    return {
+        "id": 5,
+        "filament": {"id": 2, "name": name, "material": material, "color_hex": "C8102E"},
+        "extra": extra or {},
+    }
+
+
+class TestTheMappedSpool:
+    def test_the_reported_case(self):
+        mapped = _map_spoolman_spool(_spool("Matte Scarlet Red"))
+
+        assert mapped["material"] == "PLA"
+        assert mapped["subtype"] == "Matte"
+        assert mapped["color_name"] == "Scarlet Red"
+        # Named by the user, so the edit form shows it rather than leaving it
+        # blank as it does for a colour made up from the subtype.
+        assert mapped["color_name_is_synthesized"] is False
+
+    def test_a_colour_bambuddy_stored_still_wins(self):
+        mapped = _map_spoolman_spool(_spool("Matte Scarlet Red", extra={"bambu_color_name": '"Crimson"'}))
+
+        assert mapped["color_name"] == "Crimson"
+        assert mapped["subtype"] == "Matte"
+
+    def test_a_name_without_a_colour_still_synthesises_one(self):
+        mapped = _map_spoolman_spool(_spool("PLA Matte"))
+
+        assert mapped["subtype"] == "Matte"
+        assert mapped["color_name"] == "Matte"
+        assert mapped["color_name_is_synthesized"] is True

+ 10 - 8
backend/tests/unit/test_spoolman_inventory_helpers.py

@@ -279,12 +279,14 @@ class TestMapSpoolmanSpool:
             **MINIMAL_SPOOL,
             "filament": {
                 **MINIMAL_SPOOL["filament"],
-                "name": "PLA Basic Red",
+                # No finish in the name, so it reads as Bambuddy's own
+                # "<material> <subtype>" and the colour is synthesised (#3561).
+                "name": "PLA Jade White",
                 # No color_name field.
             },
         }
         result = _map_spoolman_spool(spool)
-        assert result["color_name"] == "Basic Red"
+        assert result["color_name"] == "Jade White"
         assert result["color_name_is_synthesized"] is True
 
     def test_color_name_falls_back_to_subtype_when_field_missing(self):
@@ -298,15 +300,15 @@ class TestMapSpoolmanSpool:
             **MINIMAL_SPOOL,
             "filament": {
                 **MINIMAL_SPOOL["filament"],
-                "name": "PLA Basic Red",
+                "name": "PLA Jade White",
                 # No color_name field — the common case for default Spoolman installs.
             },
         }
         result = _map_spoolman_spool(spool)
-        # subtype is filament_name minus material prefix → "Basic Red"
-        assert result["subtype"] == "Basic Red"
+        # No finish in the name: subtype is filament_name minus material prefix.
+        assert result["subtype"] == "Jade White"
         # color_name falls back to subtype.
-        assert result["color_name"] == "Basic Red"
+        assert result["color_name"] == "Jade White"
 
     def test_color_name_read_from_spool_extra_first(self):
         """#1357: the canonical store for color_name is
@@ -354,11 +356,11 @@ class TestMapSpoolmanSpool:
             "extra": {"bambu_color_name": '""'},
             "filament": {
                 **MINIMAL_SPOOL["filament"],
-                "name": "PLA Basic Red",
+                "name": "PLA Jade White",
             },
         }
         result = _map_spoolman_spool(spool)
-        assert result["color_name"] == "Basic Red"
+        assert result["color_name"] == "Jade White"
         assert result["color_name_is_synthesized"] is True
 
     def test_color_name_none_when_both_fields_empty(self):