kylebrodeur commited on
Commit
1130366
·
verified ·
1 Parent(s): c3fc85f

Upload folder using huggingface_hub

Browse files
.env ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Chief Engineer — local config. Copy to .env — it is LOADED AUTOMATICALLY at
2
+ # import (core/__init__.py); real shell env vars always win over the file.
3
+ # Fully local; no cloud keys.
4
+
5
+ CHIEF_ENGINEER_MODEL=gemma4:e4b
6
+ # If e4b is too slow on your CPU for a responsive demo, switch to:
7
+ # CHIEF_ENGINEER_MODEL=gemma4:e2b
.gitignore CHANGED
@@ -1,13 +1,13 @@
1
- # Runtime ledger (seed corpus lives in seed_lessons.jsonl, which IS tracked)
2
- data/lessons.jsonl
3
- # Generated by `python -m ingest.run` from your configs
4
- data/references.jsonl
5
  # Learned policy — accumulates at runtime from the simulated loop
6
  data/policy.json
7
  # Transient UI artifacts (parametric-generated mesh, on-the-fly GIFs)
8
  data/_generated.glb
9
  data/_vprint.gif
10
- data/_modal_candidate_lessons.jsonl # Modal Lane-B review file (pre-honesty-gate)
11
  dist/
12
 
13
  # Sample meshes ARE committed — the HF Space doesn't run make_assets, and
 
1
+ # Runtime ledger — now tracked (ingestion artifacts are committed)
2
+ # data/lessons.jsonl — TRACKED
3
+ # data/references.jsonl — TRACKED
4
+ # data/_modal_candidate_lessons.jsonl — TRACKED (Modal Lane-B review file)
5
  # Learned policy — accumulates at runtime from the simulated loop
6
  data/policy.json
7
  # Transient UI artifacts (parametric-generated mesh, on-the-fly GIFs)
8
  data/_generated.glb
9
  data/_vprint.gif
10
+ # data/_modal_candidate_lessons.jsonl — TRACKED (Modal Lane-B review file)
11
  dist/
12
 
13
  # Sample meshes ARE committed — the HF Space doesn't run make_assets, and
Makefile CHANGED
@@ -23,6 +23,9 @@ test: ## headless core tests (no Ollama required)
23
  preflight: ## GO/NO-GO gate on the real stack (see RUNBOOK)
24
  uv run python -m scripts.preflight
25
 
 
 
 
26
  demo: ## scripted integration run / video-beat dry run
27
  uv run python -m scripts.scripted_demo
28
 
 
23
  preflight: ## GO/NO-GO gate on the real stack (see RUNBOOK)
24
  uv run python -m scripts.preflight
25
 
26
+ deploy-check: ## deploy/record readiness gate (offline: build + files + creds + Space)
27
+ uv run python -m scripts.deploy_preflight
28
+
29
  demo: ## scripted integration run / video-beat dry run
30
  uv run python -m scripts.scripted_demo
31
 
README.md CHANGED
@@ -78,12 +78,14 @@ the key code changes (`@spaces.GPU`, monkey-patched `demo.launch`, module-level
78
  Falls back to a deterministic advisor if Ollama is unreachable, so the demo never crashes; the
79
  UI always shows which model ran. Set `CHIEF_ENGINEER_MODEL=gemma4:e2b` if CPU latency is high.
80
 
81
- **Resetting demo state.** The Print loop and the 🧪 *Simulate one print* button accumulate runtime
82
- state — earned/sim lessons in `data/lessons.jsonl` and the learned cells in `data/policy.json` (both
83
- gitignored). For a clean slate between demos:
 
84
 
85
  ```bash
86
- rm -f data/lessons.jsonl data/policy.json # seed corpus reloads automatically on next launch
 
87
  ```
88
 
89
  ## Workspaces — the real print workflow
 
78
  Falls back to a deterministic advisor if Ollama is unreachable, so the demo never crashes; the
79
  UI always shows which model ran. Set `CHIEF_ENGINEER_MODEL=gemma4:e2b` if CPU latency is high.
80
 
81
+ **Resetting demo state.** `data/lessons.jsonl` is now the **durable knowledge base** (12 seed +
82
+ 13 ingested lessons — *tracked*, not disposable); the Print loop appends earned/sim lessons to it
83
+ at runtime, and `data/policy.json` is the derived learned policy. For a clean curve between demos,
84
+ **don't delete the ledger** — restore it to the committed baseline and clear only the derived policy:
85
 
86
  ```bash
87
+ git checkout -- data/lessons.jsonl # discard this session's runtime lessons, keep seed + ingested
88
+ rm -f data/policy.json # drop the learned policy (re-derives from the loop)
89
  ```
90
 
91
  ## Workspaces — the real print workflow
data/_modal_candidate_lessons.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {"job_id": "modal-saviour-detach-b6bc015e", "material": "PLA", "geometry_type": "adhesion", "env_temp": 22.0, "env_humidity": 45.0, "outcome": "failed_sag", "lesson": "Print detachment detected when layer-to-layer NRMSE score > 1.0 AND 5-layer deviance > 1.0. Large structural changes across consecutive layers indicate the part has separated from the bed. Check bed adhesion: clean surface, raise bed temp, use brim or raft.", "source": "ingested", "timestamp": "2026-06-12T18:29:36.460621+00:00"}
2
+ {"job_id": "modal-saviour-clog-81f35c76", "material": "PLA", "geometry_type": "stringing", "env_temp": 22.0, "env_humidity": 45.0, "outcome": "failed_stringing", "lesson": "Filament runout or nozzle clog detected when NRMSE score < 0.2 AND deviance < 0.2. Near-zero structural change means no material is being deposited. Check filament spool, extruder tension, and nozzle for clogs.", "source": "ingested", "timestamp": "2026-06-12T18:29:36.460621+00:00"}
3
+ {"job_id": "modal-saviour-break-1cbfb724", "material": "PLA", "geometry_type": "overhang", "env_temp": 22.0, "env_humidity": 45.0, "outcome": "failed_sag", "lesson": "Partial breakage detected when frame-to-frame score delta > 0.2 AND deviance delta > 0.2. Sudden structural changes mid-print indicate layer delamination or part fracture. Reduce cooling fan, increase nozzle temp, check for drafts.", "source": "ingested", "timestamp": "2026-06-12T18:29:36.460621+00:00"}
data/references.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
ingest/distill.py CHANGED
@@ -122,6 +122,95 @@ def parse_marlin_config(path: Path) -> list[ReferenceFact]:
122
  return facts
123
 
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  def write_references(facts: list[ReferenceFact]) -> int:
126
  DATA.mkdir(parents=True, exist_ok=True)
127
  with REFERENCES_PATH.open("w", encoding="utf-8") as f:
@@ -143,11 +232,85 @@ def load_references() -> list[ReferenceFact]:
143
  return out
144
 
145
 
146
- def reference_block(material: str, facts: list[ReferenceFact] | None = None) -> list[str]:
147
- """Compact material-reference lines for the prompt (this material + global limits)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  facts = facts if facts is not None else load_references()
149
- rel = [f for f in facts if f.material in (material, "*")]
150
- return [f"{f.param}={f.value:g} ({f.source})" for f in rel]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
 
153
  def ingest_candidate_lessons(path: Path, ledger: LedgerManager) -> int:
 
122
  return facts
123
 
124
 
125
+ def parse_prusa_config(path: Path) -> list[ReferenceFact]:
126
+ """Parse a PrusaSlicer flat config — the `; key = value` block inside a `.3mf`
127
+ project (Metadata/*.config) or a standalone exported `.config`/`.ini`. Carries
128
+ REAL per-filament settings incl. fan (which the slicer/firmware configs above
129
+ don't). One filament_type per file; source = the profile id (curated)."""
130
+ try:
131
+ if path.suffix.lower() == ".3mf":
132
+ import zipfile
133
+ with zipfile.ZipFile(path) as z:
134
+ name = next((n for n in z.namelist() if n.lower().endswith(".config")), None)
135
+ if not name:
136
+ return []
137
+ text = z.read(name).decode("utf-8", "ignore")
138
+ else:
139
+ text = path.read_text(encoding="utf-8", errors="ignore")
140
+ except Exception:
141
+ return []
142
+
143
+ def get(key: str) -> str | None:
144
+ m = re.search(rf"(?mi)^[;\s]*{re.escape(key)}\s*=\s*(.+)$", text)
145
+ return m.group(1).strip().strip('"') if m else None
146
+
147
+ def num(raw: str | None) -> float | None:
148
+ if not raw:
149
+ return None
150
+ m = re.search(r"-?\d+(?:\.\d+)?", raw.split(",")[0])
151
+ return float(m.group()) if m else None
152
+
153
+ mat = (get("filament_type") or "").upper()
154
+ if mat not in MATERIALS:
155
+ return []
156
+ src = (get("filament_settings_id") or path.stem) + (" (3mf)" if path.suffix.lower() == ".3mf" else "")
157
+ facts: list[ReferenceFact] = []
158
+ for key, param in (("temperature", "nozzle_temp"), ("first_layer_temperature", "nozzle_temp"),
159
+ ("bed_temperature", "bed_temp"), ("retract_length", "retraction_mm"),
160
+ ("max_fan_speed", "fan_pct")):
161
+ v = num(get(key))
162
+ if v is not None:
163
+ facts.append(ReferenceFact(material=mat, param=param, value=v, source=src))
164
+ return facts
165
+
166
+
167
+ def parse_octoprint_history(path: Path) -> list[dict]:
168
+ """Extract Lane-B lesson candidates from an OctoPrint print-job-history CSV.
169
+ The `result` column is COMPLETION status, not print quality (a 'success' row can
170
+ read 'very stringy'), and fan/retraction/geometry/humidity aren't recorded — so
171
+ this yields *lessons from the Note field*, not calibration rows. Honesty gate:
172
+ only emit a lesson when the note names a real defect/outcome. Neutral env (the
173
+ history doesn't log room conditions)."""
174
+ import csv as _csv
175
+
176
+ KEYWORDS = { # note phrase → (outcome, geometry, what it teaches)
177
+ "string": ("failed_stringing", "stringing"),
178
+ "sag": ("failed_sag", "overhang"),
179
+ "droop": ("failed_sag", "overhang"),
180
+ "warp": ("failed_sag", "adhesion"),
181
+ "curl": ("failed_sag", "adhesion"),
182
+ "lift": ("failed_sag", "adhesion"),
183
+ "rough": ("success", "adhesion"), # finish note, not a hard failure
184
+ }
185
+ out: list[dict] = []
186
+ try:
187
+ rows = list(_csv.DictReader(path.open(encoding="utf-8")))
188
+ except Exception:
189
+ return out
190
+ for r in rows:
191
+ note = (r.get("Note") or "").strip()
192
+ if note in ("", "-"):
193
+ continue
194
+ mat = (r.get("Material") or "").upper().replace("_PLUS", "").replace("PLA_PLUS", "PLA")
195
+ if mat not in MATERIALS:
196
+ continue
197
+ m = re.search(r"_(\d{3})C_", r.get("File Name", ""))
198
+ noz = m.group(1) if m else "?"
199
+ low = note.lower()
200
+ hit = next(((o, g) for k, (o, g) in KEYWORDS.items() if k in low), None)
201
+ if not hit:
202
+ continue
203
+ outcome, geo = hit
204
+ out.append({
205
+ "job_id": f"octo-{r.get('Start Datetime [dd.mm.yyyy hh:mm]','')[:10].replace('.','')}",
206
+ "material": mat, "geometry_type": geo, "env_temp": 22.0, "env_humidity": 50.0,
207
+ "outcome": outcome,
208
+ "lesson": f"My own print ({mat} at ~{noz}°C nozzle): \"{note}\". ",
209
+ "source": "ingested", "_note": note, "_file": r.get("File Name", ""),
210
+ })
211
+ return out
212
+
213
+
214
  def write_references(facts: list[ReferenceFact]) -> int:
215
  DATA.mkdir(parents=True, exist_ok=True)
216
  with REFERENCES_PATH.open("w", encoding="utf-8") as f:
 
232
  return out
233
 
234
 
235
+ # Params injected as material baselines — restricted to ones we have HIGH-CONFIDENCE
236
+ # (curated config) values for. Deliberately excludes fan_pct/first_layer_fan_pct
237
+ # (only present from bulk 3DTime G-code headers where M106 was unparsed → defaulted
238
+ # to ~0, which is wrong and misleading) and the noisy modal-only advance params.
239
+ # Everything the ingestion collects still lives in data/references.jsonl as a dataset;
240
+ # this is just what's trustworthy enough to put in front of the model.
241
+ _PROMPT_PARAMS = ("nozzle_temp", "bed_temp", "retraction_mm", "fan_pct",
242
+ "max_temp", "bed_max_temp")
243
+ # Params we trust ONLY from curated configs, never from bulk modal/3DTime parses
244
+ # (fan was defaulted to ~0 by the G-code header extractor). So fan reaches the prompt
245
+ # only when a real slicer profile supplies it.
246
+ _CURATED_ONLY = {"fan_pct", "first_layer_fan_pct"}
247
+ # Sane physical ranges — drop parse-garbage (e.g. a G-code header that yields
248
+ # bed_temp=12 or nozzle_temp=120 from a misread M-code) before it reaches the model.
249
+ _SANE_RANGE = {
250
+ "nozzle_temp": (170, 320), "bed_temp": (40, 130), "max_temp": (200, 350),
251
+ "bed_max_temp": (60, 150), "retraction_mm": (0.2, 8.0), "fan_pct": (0, 100),
252
+ "first_layer_fan_pct": (0, 100), "pressure_advance": (0.0, 1.5),
253
+ "linear_advance_k": (0.0, 2.0), "shore_hardness": (0, 100),
254
+ }
255
+ _REF_ORDER = ("nozzle_temp", "bed_temp", "retraction_mm", "fan_pct", "max_temp", "bed_max_temp")
256
+
257
+
258
+ def material_facts(material: str, facts: list[ReferenceFact] | None = None,
259
+ params: tuple[str, ...] | None = None) -> dict[str, dict]:
260
+ """On-demand reference lookup for ONE material: curated + range-filtered +
261
+ aggregated. Returns {param: {value(median), lo, hi, n, sources}}. The bulk
262
+ model-metadata params are excluded; out-of-range parse noise is dropped. This
263
+ is the single source the prompt block and any targeted fact lookup draw from —
264
+ facts are fetched per request, not bulk-injected."""
265
  facts = facts if facts is not None else load_references()
266
+ want = set(params) if params else set(_PROMPT_PARAMS)
267
+ # split curated (slicer/firmware/profile configs — precise) from bulk
268
+ # (modal/3DTime/gcode-derived — high volume, lower precision). Prefer curated.
269
+ cur: dict[str, list[tuple[float, str]]] = {}
270
+ bulk: dict[str, list[tuple[float, str]]] = {}
271
+ for f in facts:
272
+ if f.material not in (material, "*") or f.param not in want:
273
+ continue
274
+ lo, hi = _SANE_RANGE.get(f.param, (float("-inf"), float("inf")))
275
+ if not (lo <= f.value <= hi):
276
+ continue
277
+ head = f.source.split(":")[0]
278
+ bucket = bulk if head.startswith(("modal", "ablam")) else cur
279
+ bucket.setdefault(f.param, []).append((f.value, head))
280
+ out: dict[str, dict] = {}
281
+ for p in want:
282
+ # authoritative first; bulk only if no curated AND the param is bulk-trustworthy
283
+ pairs = cur.get(p) or (None if p in _CURATED_ONLY else bulk.get(p))
284
+ if not pairs:
285
+ continue
286
+ vals = sorted(v for v, _ in pairs)
287
+ out[p] = {"value": vals[len(vals) // 2], "lo": vals[0], "hi": vals[-1],
288
+ "n": len(vals), "sources": sorted({s for _, s in pairs})[:3]}
289
+ return out
290
+
291
+
292
+ def lookup_fact(material: str, param: str, facts: list[ReferenceFact] | None = None) -> dict | None:
293
+ """On-demand single-fact lookup (material+global), aggregated. None if unknown."""
294
+ return material_facts(material, facts, params=(param,)).get(param)
295
+
296
+
297
+ def reference_block(material: str, facts: list[ReferenceFact] | None = None,
298
+ max_lines: int = 8) -> list[str]:
299
+ """Lean prompt lines for THIS material — one aggregated line per useful param
300
+ (median + observed range + source count), capped. Computed on demand, so the
301
+ 1,300-row reference corpus never floods the prompt (was 500+ lines/material)."""
302
+ md = material_facts(material, facts)
303
+ lines: list[str] = []
304
+ for p in _REF_ORDER:
305
+ d = md.get(p)
306
+ if not d:
307
+ continue
308
+ rng = f" (range {d['lo']:g}–{d['hi']:g}, n={d['n']})" if d["n"] > 1 else ""
309
+ src = f" [{', '.join(d['sources'])}]" if d["sources"] else ""
310
+ lines.append(f"{p}≈{d['value']:g}{rng}{src}")
311
+ if len(lines) >= max_lines:
312
+ break
313
+ return lines
314
 
315
 
316
  def ingest_candidate_lessons(path: Path, ledger: LedgerManager) -> int:
ingest/modal_app.py CHANGED
@@ -1,14 +1,7 @@
1
- """Modal app — heavy-dataset ingestion at scale (the Modal-bonus track).
2
 
3
- SCAFFOLD: the structure + the output CONTRACT are done; the per-dataset *mapping*
4
- (raw row → Chief Engineer record) is where Kyle's MCP-hackathon parser plugs in —
5
- see the MAPPERS registry below. Isolated from the demo path: `modal` is
6
- import-guarded, not in the Space requirements, and nothing in app.py imports this.
7
-
8
- Why Modal: the source datasets (slicer g-code corpora, 3D-ADAM defect sets, etc.)
9
- are too big to pull/parse on a laptop or in the Space. Modal does the heavy
10
- download+parse; the OUTPUT is the same three lanes the local pipeline already
11
- consumes, so the artifacts drop straight into the app.
12
 
13
  THE CONTRACT — three artifact shapes (one JSON object per line):
14
  A) reference fact -> data/references.jsonl
@@ -19,17 +12,19 @@ THE CONTRACT — three artifact shapes (one JSON object per line):
19
  C) calibration obs -> sim/calibration/observations.modal.jsonl
20
  {"material","geometry_type","env_temp","env_humidity","nozzle_temp",
21
  "bed_temp","retraction_mm","fan_pct","first_layer_fan_pct","outcome","quality"?}
22
- (enums: see core/models.py MATERIALS / GEOMETRY_TYPES / OUTCOMES.)
23
 
24
  Run (after `uv pip install modal datasets` + `modal token set`):
25
- modal run ingest/modal_app.py # all registered datasets
26
- modal run ingest/modal_app.py --dataset 3d-adam --limit 2000
27
- Lane B is written to a REVIEW file, never straight to the ledger (honesty gate).
28
  """
29
 
30
  from __future__ import annotations
31
 
32
  import json
 
 
 
33
  from pathlib import Path
34
 
35
  # Import-guarded so the rest of the app/tests never depend on modal being present.
@@ -38,77 +33,1704 @@ try:
38
  except Exception: # pragma: no cover
39
  modal = None # type: ignore
40
 
41
- # ── per-dataset mappers: raw HF/GH row -> list of (lane, record dict) ──────────
42
- # TODO(kyle): drop your MCP-hackathon parsing here. Each mapper takes one dataset
43
- # row and returns zero or more ("A"|"B"|"C", record) tuples in the shapes above.
44
- # Honesty rule: only emit Lane-B lessons that are true + directional; emit Lane-C
45
- # only when the row carries the actual settings used.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  def _map_3d_adam(row: dict) -> list[tuple[str, dict]]:
48
- """3D-ADAM-style defect dataset → mostly Lane C (settings + defect outcome)."""
49
- # TODO(kyle): map your columns. Example shape (pseudocode — adjust field names):
50
- # return [("C", {"material": row["material"], "geometry_type": "overhang",
51
- # "env_temp": row.get("ambient_c", 22), "env_humidity": row.get("rh", 45),
52
- # "nozzle_temp": row["nozzle"], "bed_temp": row["bed"], "retraction_mm": row["retract"],
53
- # "fan_pct": row["fan"], "first_layer_fan_pct": 0,
54
- # "outcome": _defect_to_outcome(row["label"]), "quality": row.get("quality")})]
55
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
 
58
  def _map_gcode(row: dict) -> list[tuple[str, dict]]:
59
- """Slicer g-code corpus → Lane A material baselines (temps/retraction)."""
60
- # TODO(kyle): extract M104/M140/retraction etc. into reference facts:
61
- # return [("A", {"material": m, "param": "nozzle_temp", "value": v, "source": "ablam/gcode"})]
62
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
 
64
 
65
- # dataset key → (HF dataset id or loader, mapper). Add yours here.
66
- MAPPERS = {
67
- "3d-adam": ("<hf-org/3d-adam-id>", _map_3d_adam), # TODO(kyle): real id
 
68
  "gcode": ("ablam/gcode", _map_gcode),
 
69
  }
70
 
71
  _VALID_LANES = {"A", "B", "C"}
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  if modal is not None:
75
  app = modal.App("chief-engineer-ingest")
76
- image = modal.Image.debian_slim().pip_install(
77
- "datasets", "pyarrow", "huggingface_hub", "pydantic>=2.7")
78
-
79
- @app.function(image=image, timeout=3600)
80
- def distill(dataset: str, limit: int = 1000, split: str = "train") -> dict:
81
- """Heavy step on Modal: load a dataset, map rows → lane records, return them.
82
- Returns {"A":[...], "B":[...], "C":[...], "stats":{...}} for the local
83
- entrypoint to write into the repo's artifact files."""
84
- from datasets import load_dataset
85
 
86
- if dataset not in MAPPERS:
87
- return {"error": f"unknown dataset '{dataset}'; known: {list(MAPPERS)}"}
88
- hf_id, mapper = MAPPERS[dataset]
89
- ds = load_dataset(hf_id, split=f"{split}[:{limit}]")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  out: dict[str, list] = {"A": [], "B": [], "C": []}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  for row in ds:
92
  for lane, rec in mapper(dict(row)):
93
  if lane in _VALID_LANES:
94
  out[lane].append(rec)
95
- out["stats"] = {"dataset": dataset, "hf_id": hf_id, "rows": len(ds),
96
- "A": len(out["A"]), "B": len(out["B"]), "C": len(out["C"])}
 
 
97
  return out
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  @app.local_entrypoint()
100
- def main(dataset: str = "", limit: int = 1000):
101
- """Run locally: fan out to Modal, then write artifacts into the repo in the
102
- three lane shapes. Lane B goes to a REVIEW file (not the ledger)."""
 
 
 
 
 
 
 
 
 
 
 
103
  root = Path(__file__).resolve().parent.parent
104
- targets = [dataset] if dataset else list(MAPPERS)
105
  agg: dict[str, list] = {"A": [], "B": [], "C": []}
106
- for d in targets:
107
- res = distill.remote(d, limit)
108
- print(" ", res.get("stats", res))
109
- for lane in ("A", "B", "C"):
110
- agg[lane].extend(res.get(lane, []))
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  def _write(path: Path, rows: list, append: bool):
113
  if not rows:
114
  return
@@ -118,22 +1740,39 @@ if modal is not None:
118
  f.write(json.dumps(r) + "\n")
119
  print(f" wrote {len(rows)} → {path.relative_to(root)}")
120
 
121
- _write(root / "data" / "references.jsonl", agg["A"], append=True) # Lane A (safe)
122
- _write(root / "data" / "_modal_candidate_lessons.jsonl", agg["B"], append=False) # Lane B (REVIEW)
123
- _write(root / "sim" / "calibration" / "observations.modal.jsonl", agg["C"], append=False) # Lane C
124
- print("\nNext:")
125
- print(" • REVIEW data/_modal_candidate_lessons.jsonl (honesty gate), then fold into the")
126
- print(" ledger via ingest_candidate_lessons / the ingestion work order.")
127
- print(" • Calibrate: uv run python -m sim.calibrate --data sim/calibration/observations.modal.jsonl")
128
- print(" • make test → make run")
129
-
130
- # FRONTIER (named in the writeup, NOT in-window): fine-tune a small Gemma on the
131
- # accumulated ledger. Kyle's MCP-hackathon training pipeline would plug in here.
 
 
 
 
 
 
132
  # @app.function(gpu="A10G", image=image, timeout=3600)
133
  # def finetune_on_ledger(...): ...
134
 
135
 
136
  if __name__ == "__main__":
137
- print("Modal app scaffold. Install modal + datasets, `modal token set`, then:")
138
- print(" modal run ingest/modal_app.py [--dataset 3d-adam --limit 2000]")
139
- print("Plug your MCP-hackathon parsers into the MAPPERS registry (see docstring).")
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modal app — heavy ingestion at scale (the Modal-bonus track).
2
 
3
+ Ingests 3D-printing knowledge from documentation URLs, GitHub repos, slicer
4
+ profiles, and HF datasets into the three lanes the Chief Engineer consumes.
 
 
 
 
 
 
 
5
 
6
  THE CONTRACT — three artifact shapes (one JSON object per line):
7
  A) reference fact -> data/references.jsonl
 
12
  C) calibration obs -> sim/calibration/observations.modal.jsonl
13
  {"material","geometry_type","env_temp","env_humidity","nozzle_temp",
14
  "bed_temp","retraction_mm","fan_pct","first_layer_fan_pct","outcome","quality"?}
 
15
 
16
  Run (after `uv pip install modal datasets` + `modal token set`):
17
+ modal run ingest/modal_app.py # all sources
18
+ modal run ingest/modal_app.py --source klipper-config # single source
19
+ modal run ingest/modal_app.py --category firmware # category of sources
20
  """
21
 
22
  from __future__ import annotations
23
 
24
  import json
25
+ import re
26
+ import hashlib
27
+ from datetime import datetime, timezone
28
  from pathlib import Path
29
 
30
  # Import-guarded so the rest of the app/tests never depend on modal being present.
 
33
  except Exception: # pragma: no cover
34
  modal = None # type: ignore
35
 
36
+ # ── Enums (must match core/models.py) ──────────────────────────────────────────
37
+ MATERIALS = ["PLA", "PETG", "ABS", "TPU"]
38
+ GEOMETRY_TYPES = ["overhang", "bridge", "stringing", "adhesion", "vase"]
39
+ OUTCOMES = ["success", "failed_sag", "failed_stringing"]
40
+
41
+ # ── Source Registry ───────────────────────────────────────────────────────────
42
+ # Each source: key -> (url, category, source_type, description)
43
+ # source_type determines how we fetch & parse it:
44
+ # "github_repo" — clone, scan for config files (*.cfg, *.h, *.ini)
45
+ # "web_doc" — fetch HTML, extract text, parse for params & lessons
46
+ # "prusa_profiles" — download INI files, parse with Prusa parser
47
+ # "product_spec" — extract material parameters from product pages
48
+ # "research_repo" — clone, look for datasets/configs
49
+
50
+ SOURCES: dict[str, tuple[str, str, str, str]] = {
51
+ # ── Firmware, Libraries & Host Controllers ──
52
+ "moonraker": (
53
+ "https://github.com/Arksine/moonraker",
54
+ "firmware", "github_repo",
55
+ "Moonraker web API server for Klipper"
56
+ ),
57
+ "mainsail": (
58
+ "https://github.com/meteyou/mainsail",
59
+ "firmware", "github_repo",
60
+ "Mainsail web dashboard for Klipper"
61
+ ),
62
+ "tmcstepper": (
63
+ "https://github.com/teemuatlut/TMCStepper",
64
+ "firmware", "github_repo",
65
+ "TMC stepper driver library"
66
+ ),
67
+ "klipper-thermistors": (
68
+ "https://www.klipper3d.org/Config_Reference.html#common-thermistors",
69
+ "firmware", "web_doc",
70
+ "Klipper thermistor sensor designations"
71
+ ),
72
+ "tmc26x": (
73
+ "https://github.com/trinamic/TMC26XStepper",
74
+ "firmware", "github_repo",
75
+ "TMC26X high-current driver library"
76
+ ),
77
+ "arduino-l6470": (
78
+ "https://github.com/ameyer/Arduino-L6470",
79
+ "firmware", "github_repo",
80
+ "L6470 stepper driver library"
81
+ ),
82
+ "u8glib": (
83
+ "https://github.com/olikraus/U8glib_Arduino",
84
+ "firmware", "github_repo",
85
+ "Display rendering library"
86
+ ),
87
+ "platformio": (
88
+ "http://docs.platformio.org/en/latest/projectconf.html",
89
+ "firmware", "web_doc",
90
+ "PlatformIO project configuration"
91
+ ),
92
+
93
+ # ── Calibration Frameworks & Parametric Rules ──
94
+ "reprap-calibration": (
95
+ "http://reprap.org/wiki/Calibration",
96
+ "calibration", "web_doc",
97
+ "RepRap calibration framework"
98
+ ),
99
+ "pid-tuning": (
100
+ "http://reprap.org/wiki/PID_Tuning",
101
+ "calibration", "web_doc",
102
+ "PID tuning for heater performance"
103
+ ),
104
+ "linear-advance": (
105
+ "http://marlinfw.org/docs/features/lin_advance.html",
106
+ "calibration", "web_doc",
107
+ "Marlin Linear Advance configuration"
108
+ ),
109
+ "laser-spindle": (
110
+ "http://marlinfw.org/docs/configuration/laser_spindle.html",
111
+ "calibration", "web_doc",
112
+ "PWM-to-RPM spindle configuration"
113
+ ),
114
+ "probes": (
115
+ "http://marlinfw.org/docs/configuration/probes.html",
116
+ "calibration", "web_doc",
117
+ "Z-probe configuration"
118
+ ),
119
+ "gcode-actions": (
120
+ "https://reprap.org/wiki/G-code#Action_commands",
121
+ "calibration", "web_doc",
122
+ "G-code protocol specification"
123
+ ),
124
+ "jerk-motion": (
125
+ "https://github.com/synthetos/TinyG/wiki/Jerk-Controlled-Motion-Explained",
126
+ "calibration", "web_doc",
127
+ "Jerk-controlled motion kinematics"
128
+ ),
129
+ "junction-deviation": (
130
+ "https://reprap.org/forum/read.php?1,739819",
131
+ "calibration", "web_doc",
132
+ "Junction Deviation equations"
133
+ ),
134
+
135
+ # ── Research Datasets & ML Resources ──
136
+ "bcn3d-moveo": (
137
+ "https://www.bcn3d.com/bcn3d-moveo-the-future-of-learning-robotic-arm/",
138
+ "research", "web_doc",
139
+ "BCN3D Moveo robotic arm (3D-ADAM base)"
140
+ ),
141
+ "3dtime-dataloader": (
142
+ "https://github.com/3DTimeDataset/3DTime_pytorch_dataloader",
143
+ "research", "research_repo",
144
+ "3DTime time-series slicing data loader"
145
+ ),
146
+ "klipper-analysis": (
147
+ "https://github.com/worksasintended/klipper_linear_movement_analysis",
148
+ "research", "research_repo",
149
+ "Klipper linear movement analysis"
150
+ ),
151
+
152
+ # ── Hardware Profiles & Slicer Configuration ──
153
+ "prusa-anycubic": (
154
+ "https://files.prusa3d.com/wp-content/uploads/repository/PrusaSlicer-settings-master/live/Anycubic/",
155
+ "profiles", "prusa_profiles",
156
+ "PrusaSlicer Anycubic machine profiles"
157
+ ),
158
+ "hartrusion-config": (
159
+ "https://hartrusion.com/en/prusaslicer-config-for-anycubic-4max-pro-2-0/",
160
+ "profiles", "web_doc",
161
+ "Anycubic 4Max Pro 2.0 PrusaSlicer config"
162
+ ),
163
+ "sainsmart-tpu": (
164
+ "https://www.sainsmart.com/collections/tpu-filament/products/all-colors-tpu-flexible-filament-1-75mm-0-8kg-1-76lb",
165
+ "profiles", "product_spec",
166
+ "Sainsmart TPU filament specifications"
167
+ ),
168
+ "ratos-install": (
169
+ "https://os.ratrig.com/docs/installation",
170
+ "profiles", "web_doc",
171
+ "RatOS installation framework"
172
+ ),
173
+ "ratos-upgrade": (
174
+ "https://os.ratrig.com/docs/upgrading_rc3",
175
+ "profiles", "web_doc",
176
+ "RatOS upgrade migration"
177
+ ),
178
+
179
+ # ── Structured Profile & Config Repos (Tier S) ──
180
+ "bambu-filament-profiles": (
181
+ "https://github.com/bambulab/BambuStudio",
182
+ "structured", "bambu_json_profiles",
183
+ "BambuStudio tree-structured filament JSON profiles (200+ materials)"
184
+ ),
185
+ "kanrog-klipper-configs": (
186
+ "https://github.com/Kanrog/klipper-config-generator",
187
+ "structured", "klipper_config_repo",
188
+ "Klipper config generator: 150+ motherboard pin maps, PID, max temps"
189
+ ),
190
+ "3dprint-saviour-thresholds": (
191
+ "https://github.com/Manicben/3DPrintSaviour",
192
+ "structured", "failure_detection_repo",
193
+ "3DPrintSaviour: NRMSE failure detection thresholds + classification logic"
194
+ ),
195
+ "jklewa-filament-profiles": (
196
+ "https://github.com/jklewa/filament-profiles-data",
197
+ "structured", "filament_profiles_repo",
198
+ "Community-verified filament profiles: nozzle/bed temps, vendor, price"
199
+ ),
200
+ "fdm-error-detection": (
201
+ "https://github.com/NilsHagenBeyer/3D-printing_recorder",
202
+ "structured", "fdm_error_gcode",
203
+ "FDM error detection: G-code + YAML with known failure outcomes (Lane C goldmine)"
204
+ ),
205
+ }
206
+
207
+ # ── HF Dataset Mappers (for structured datasets) ──────────────────────────────
208
+ # These are separate from the documentation sources above.
209
+ # Each mapper takes one dataset row and returns zero or more ("A"|"B"|"C", record) tuples.
210
 
211
  def _map_3d_adam(row: dict) -> list[tuple[str, dict]]:
212
+ """3D-ADAM defect dataset → Lane C calibration observations.
213
+
214
+ The 3D-ADAM dataset (pmchard/3D-ADAM) contains images and defect masks
215
+ for 3D printing defects. We extract defect type → outcome mapping and
216
+ any available print settings to produce calibration observations.
217
+
218
+ Dataset structure (from anomalib loader):
219
+ - image: PIL Image of the printed part
220
+ - mask: defect mask
221
+ - label: defect class (warping, under_extrusion, stringing, cracking)
222
+ - category: part category
223
+ """
224
+ records = []
225
+ defect = str(row.get("label", row.get("category", ""))).lower()
226
+
227
+ # Map 3D-ADAM defect classes to Chief Engineer outcomes
228
+ defect_to_outcome = {
229
+ "warping": "failed_sag",
230
+ "under_extrusion": "failed_sag",
231
+ "stringing": "failed_stringing",
232
+ "cracking": "failed_sag",
233
+ }
234
+ outcome = defect_to_outcome.get(defect)
235
+ if not outcome:
236
+ return records
237
+
238
+ # Map defect to geometry type
239
+ defect_to_geometry = {
240
+ "warping": "adhesion",
241
+ "under_extrusion": "overhang",
242
+ "stringing": "stringing",
243
+ "cracking": "adhesion",
244
+ }
245
+ geometry_type = defect_to_geometry.get(defect, "overhang")
246
+
247
+ # 3D-ADAM doesn't include print settings in the dataset itself,
248
+ # but we can emit Lane B lessons from the defect taxonomy.
249
+ # Lane C requires actual settings — only emit if settings columns exist.
250
+ has_settings = all(k in row for k in ("nozzle_temp", "bed_temp", "retraction_mm", "fan_pct"))
251
+ if has_settings:
252
+ records.append(("C", {
253
+ "material": row.get("material", "PLA"),
254
+ "geometry_type": geometry_type,
255
+ "env_temp": float(row.get("env_temp", 22)),
256
+ "env_humidity": float(row.get("env_humidity", 45)),
257
+ "nozzle_temp": float(row["nozzle_temp"]),
258
+ "bed_temp": float(row["bed_temp"]),
259
+ "retraction_mm": float(row["retraction_mm"]),
260
+ "fan_pct": float(row["fan_pct"]),
261
+ "first_layer_fan_pct": float(row.get("first_layer_fan_pct", 0)),
262
+ "outcome": outcome,
263
+ "quality": float(row.get("quality", 0.5)),
264
+ }))
265
+
266
+ # Always emit Lane B lesson from defect taxonomy
267
+ defect_lessons = {
268
+ "warping": "Corners lift when lower layers cool and contract — raise bed temp, enclose, slow first layer.",
269
+ "under_extrusion": "Gaps and weak walls from too-low temp or too-fast flow — raise temp or slow down, check for clogs.",
270
+ "stringing": "Fine whiskers across gaps from wet filament or hot travel — dry filament, lower temp, tune retraction.",
271
+ "cracking": "Layers split under stress from over-cooling — reduce fan, raise temp, enclose for ABS.",
272
+ }
273
+ lesson_text = defect_lessons.get(defect, "")
274
+ if lesson_text:
275
+ job_id = f"modal-3dadam-{hashlib.md5(str(row).encode()).hexdigest()[:8]}"
276
+ records.append(("B", {
277
+ "job_id": job_id,
278
+ "material": row.get("material", "PLA"),
279
+ "geometry_type": geometry_type,
280
+ "env_temp": float(row.get("env_temp", 22)),
281
+ "env_humidity": float(row.get("env_humidity", 45)),
282
+ "outcome": outcome,
283
+ "lesson": lesson_text,
284
+ "source": "ingested",
285
+ "timestamp": datetime.now(timezone.utc).isoformat(),
286
+ }))
287
+
288
+ return records
289
 
290
 
291
  def _map_gcode(row: dict) -> list[tuple[str, dict]]:
292
+ """Slicer g-code corpus → Lane A material baselines.
293
+
294
+ The ablam/gcode dataset contains G-code files from Printables.
295
+ We parse M104 (set extruder temp), M140 (set bed temp), and
296
+ retraction settings to extract reference facts.
297
+ """
298
+ records = []
299
+ gcode_text = str(row.get("gcode", row.get("content", row.get("text", ""))))
300
+ if not gcode_text:
301
+ return records
302
+
303
+ # Extract temperatures from G-code
304
+ nozzle_match = re.search(r"M104\s+S(\d+)", gcode_text)
305
+ bed_match = re.search(r"M140\s+S(\d+)", gcode_text)
306
+ retract_match = re.search(r"G1\s+E-?(\d+\.?\d*).*retract", gcode_text, re.I)
307
+
308
+ # Try to determine material from filename or comments
309
+ filename = str(row.get("filename", row.get("file_name", ""))).upper()
310
+ material = "PLA" # default
311
+ for m in MATERIALS:
312
+ if m in filename:
313
+ material = m
314
+ break
315
+
316
+ source = f"ablam/gcode:{row.get('filename', row.get('id', 'unknown'))}"
317
+
318
+ if nozzle_match:
319
+ records.append(("A", {
320
+ "material": material,
321
+ "param": "nozzle_temp",
322
+ "value": float(nozzle_match.group(1)),
323
+ "source": source,
324
+ }))
325
+ if bed_match:
326
+ records.append(("A", {
327
+ "material": material,
328
+ "param": "bed_temp",
329
+ "value": float(bed_match.group(1)),
330
+ "source": source,
331
+ }))
332
+ if retract_match:
333
+ records.append(("A", {
334
+ "material": material,
335
+ "param": "retraction_mm",
336
+ "value": float(retract_match.group(1)),
337
+ "source": source,
338
+ }))
339
+
340
+ return records
341
+
342
+
343
+ def _map_3dtime(row: dict) -> list[tuple[str, dict]]:
344
+ """3DTime metadata CSV → Lane A reference facts (material, infill, geometry)."""
345
+ records = []
346
+ material_map = {"pla": "PLA", "pet": "PETG", "abs": "ABS", "tpu": "TPU"}
347
+ material = material_map.get(str(row.get("Material", "")).lower(), "PLA")
348
+ source = f"3DTime:{row.get('3D mesh name', row.get('G-code file name', 'unknown'))}"
349
+
350
+ for dim, param in [("Bounding box X (mm)", "bbox_x_mm"),
351
+ ("Bounding box Y (mm)", "bbox_y_mm"),
352
+ ("Bounding box Z (mm)", "bbox_z_mm")]:
353
+ val = row.get(dim)
354
+ if val:
355
+ try:
356
+ records.append(("A", {"material": material, "param": param,
357
+ "value": float(val), "source": source}))
358
+ except ValueError:
359
+ pass
360
+
361
+ for key, param in [("Infill density (%)", "infill_density_pct"),
362
+ ("Infill rotation (°)", "infill_rotation")]:
363
+ val = row.get(key)
364
+ if val:
365
+ try:
366
+ records.append(("A", {"material": material, "param": param,
367
+ "value": float(val), "source": source}))
368
+ except ValueError:
369
+ pass
370
+
371
+ infill_type = row.get("Infill type", "")
372
+ if infill_type:
373
+ records.append(("A", {"material": material, "param": "infill_type",
374
+ "value": 0, "source": f"{source}:{infill_type}"}))
375
+
376
+ print_time = row.get("Print time (s)")
377
+ if print_time:
378
+ try:
379
+ records.append(("A", {"material": material, "param": "print_time_s",
380
+ "value": float(print_time), "source": source}))
381
+ except ValueError:
382
+ pass
383
 
384
+ return records
385
 
386
+
387
+ # dataset key → (HF dataset id, mapper)
388
+ HF_MAPPERS = {
389
+ "3d-adam": ("pmchard/3D-ADAM", _map_3d_adam),
390
  "gcode": ("ablam/gcode", _map_gcode),
391
+ "3dtime": ("3DTimeDataset/3DTime", _map_3dtime),
392
  }
393
 
394
  _VALID_LANES = {"A", "B", "C"}
395
 
396
+ # ── Deterministic parsers for documentation content ───────────────────────────
397
+
398
+ def _material_of(text: str) -> str | None:
399
+ """Detect material name in text."""
400
+ up = text.upper()
401
+ for m in MATERIALS:
402
+ if m in up:
403
+ return m
404
+ return None
405
+
406
+
407
+ def _extract_temperature_values(text: str, source_label: str) -> list[tuple[str, dict]]:
408
+ """Extract temperature reference facts from documentation text.
409
+
410
+ Looks for patterns like:
411
+ - "nozzle temperature: 200-220°C"
412
+ - "bed temperature 60°C"
413
+ - "max_temp: 300"
414
+ - "recommended temperature 210°C for PLA"
415
+ """
416
+ records = []
417
+ # Pattern: material name near a temperature value
418
+ # e.g. "PLA at 200°C", "PETG: 230-240°C"
419
+ temp_patterns = [
420
+ # nozzle_temp patterns
421
+ (r'(?:nozzle|hotend|extruder)\s*(?:temp(?:erature)?)?\s*[:=]?\s*(\d{3})(?:\s*[-–]\s*\d{3})?\s*°?[CF]?', "nozzle_temp"),
422
+ (r'(?:print(?:ing)?\s*)?temp(?:erature)?\s*[:=]?\s*(\d{3})(?:\s*[-–]\s*\d{3})?\s*°?[CF]?', "nozzle_temp"),
423
+ # bed_temp patterns
424
+ (r'(?:bed|heatbed)\s*(?:temp(?:erature)?)?\s*[:=]?\s*(\d{2,3})\s*°?[CF]?', "bed_temp"),
425
+ # retraction patterns
426
+ (r'retract(?:ion)?\s*(?:length|distance)?\s*[:=]?\s*(\d+\.?\d*)\s*mm', "retraction_mm"),
427
+ # max_temp patterns
428
+ (r'max(?:imum)?\s*_?temp(?:erature)?\s*[:=]?\s*(\d{3})\s*°?[CF]?', "max_temp"),
429
+ # fan patterns
430
+ (r'(?:part\s*)?(?:cooling\s*)?fan\s*(?:speed|pct|percent)?\s*[:=]?\s*(\d{1,3})\s*%?', "fan_pct"),
431
+ ]
432
+
433
+ for pattern, param in temp_patterns:
434
+ for match in re.finditer(pattern, text, re.IGNORECASE):
435
+ value = float(match.group(1))
436
+ # Find nearby material mention (within 200 chars before)
437
+ context_start = max(0, match.start() - 200)
438
+ context = text[context_start:match.end()]
439
+ material = _material_of(context) or "*"
440
+ records.append(("A", {
441
+ "material": material,
442
+ "param": param,
443
+ "value": value,
444
+ "source": source_label,
445
+ }))
446
+
447
+ return records
448
+
449
+
450
+ def _extract_lessons_from_doc(text: str, source_label: str) -> list[tuple[str, dict]]:
451
+ """Extract candidate lessons from documentation text.
452
+
453
+ Looks for patterns indicating cause→effect relationships:
454
+ - "if ... then ..." (conditional advice)
455
+ - "to prevent/avoid ... do ..." (preventative advice)
456
+ - "when ... occurs, ..." (troubleshooting)
457
+ - "increase/decrease ... to ..." (parametric advice)
458
+ """
459
+ records = []
460
+ lesson_patterns = [
461
+ # Conditional: "If [condition], [action]"
462
+ (r'(?i)if\s+(.{20,200}?)(?:,\s*|then\s*)(.{20,200}?)(?:\.|$)', "conditional"),
463
+ # Preventative: "To prevent/avoid [problem], [action]"
464
+ (r'(?i)to\s+(?:prevent|avoid|reduce|fix)\s+(.{20,150}?)(?:,\s*|you\s*(?:should|can|need\s*to)?\s*)(.{20,150}?)(?:\.|$)', "preventative"),
465
+ # Troubleshooting: "When/If [symptom], [cause/solution]"
466
+ (r'(?i)(?:when|if)\s+(.{20,150}?)(?:occurs|happens|appears)(?:,\s*|it\s*(?:is|means|indicates)\s*)(.{20,150}?)(?:\.|$)', "troubleshooting"),
467
+ # Parametric: "increase/decrease [param] to [effect]"
468
+ (r'(?i)(increase|decrease|raise|lower)\s+(?:the\s*)?(\w+(?:\s*\w+)?)\s*(?:to|for|when)\s+(.{20,150}?)(?:\.|$)', "parametric"),
469
+ ]
470
+
471
+ for pattern, lesson_type in lesson_patterns:
472
+ for match in re.finditer(pattern, text):
473
+ groups = match.groups()
474
+ if lesson_type == "conditional":
475
+ condition, action = groups[0], groups[1]
476
+ lesson_text = f"{condition.strip()} — {action.strip()}."
477
+ elif lesson_type == "preventative":
478
+ problem, action = groups[0], groups[1]
479
+ lesson_text = f"To prevent {problem.strip()}, {action.strip()}."
480
+ elif lesson_type == "troubleshooting":
481
+ symptom, cause = groups[0], groups[1]
482
+ lesson_text = f"When {symptom.strip()} occurs, {cause.strip()}."
483
+ elif lesson_type == "parametric":
484
+ direction, param, effect = groups[0], groups[1], groups[2]
485
+ lesson_text = f"{direction.capitalize()} {param.strip()} to {effect.strip()}."
486
+ else:
487
+ continue
488
+
489
+ # Skip if too short or too long
490
+ if len(lesson_text) < 30 or len(lesson_text) > 300:
491
+ continue
492
+
493
+ # Try to detect material and geometry from context
494
+ context_start = max(0, match.start() - 300)
495
+ context = text[context_start:match.end()]
496
+ material = _material_of(context) or "PLA"
497
+ geometry = "overhang" # default
498
+ for gt in GEOMETRY_TYPES:
499
+ if gt in context.lower():
500
+ geometry = gt
501
+ break
502
+
503
+ # Detect outcome from lesson text
504
+ outcome = "success"
505
+ if any(w in lesson_text.lower() for w in ("fail", "warp", "sag", "string", "crack", "lift", "poor", "bad", "issue", "problem")):
506
+ if "string" in lesson_text.lower():
507
+ outcome = "failed_stringing"
508
+ else:
509
+ outcome = "failed_sag"
510
+
511
+ job_id = f"modal-doc-{hashlib.md5(lesson_text.encode()).hexdigest()[:8]}"
512
+ records.append(("B", {
513
+ "job_id": job_id,
514
+ "material": material,
515
+ "geometry_type": geometry,
516
+ "env_temp": 22.0,
517
+ "env_humidity": 45.0,
518
+ "outcome": outcome,
519
+ "lesson": lesson_text,
520
+ "source": "ingested",
521
+ "timestamp": datetime.now(timezone.utc).isoformat(),
522
+ }))
523
+
524
+ return records
525
+
526
+
527
+ def _extract_pid_values(text: str, source_label: str) -> list[tuple[str, dict]]:
528
+ """Extract PID constants from documentation (specialized parser)."""
529
+ records = []
530
+ # Klipper-style: pid_Kp=22.2 pid_Ki=1.08 pid_Kd=114
531
+ pid_match = re.search(
532
+ r'pid_Kp\s*=\s*([\d.]+).*?pid_Ki\s*=\s*([\d.]+).*?pid_Kd\s*=\s*([\d.]+)',
533
+ text, re.S | re.I
534
+ )
535
+ if pid_match:
536
+ for i, (val, param) in enumerate(zip(pid_match.groups(), ("pid_Kp", "pid_Ki", "pid_Kd"))):
537
+ records.append(("A", {
538
+ "material": "*",
539
+ "param": param,
540
+ "value": float(val),
541
+ "source": source_label,
542
+ }))
543
+ return records
544
+
545
+
546
+ def _extract_linear_advance(text: str, source_label: str) -> list[tuple[str, dict]]:
547
+ """Extract Linear Advance K-factors from documentation."""
548
+ records = []
549
+ # Marlin-style: M900 K0.05 for PLA, K0.08 for PETG
550
+ for match in re.finditer(
551
+ r'(?:M900\s*)?K\s*(\d+(?:\.\d+)?)\s*(?:for\s+)?(\w+)',
552
+ text, re.I
553
+ ):
554
+ try:
555
+ k_value = float(match.group(1))
556
+ except ValueError:
557
+ continue
558
+ # Realistic K-factors are 0.0-2.0 (most filaments 0.0-0.2, flexible up to 2.0)
559
+ if k_value < 0 or k_value > 2.0:
560
+ continue
561
+ material = _material_of(match.group(2)) or match.group(2).upper()
562
+ if material not in MATERIALS:
563
+ material = "*"
564
+ records.append(("A", {
565
+ "material": material,
566
+ "param": "linear_advance_k",
567
+ "value": k_value,
568
+ "source": source_label,
569
+ }))
570
+ return records
571
+
572
+
573
+ def _extract_thermistor_types(text: str, source_label: str) -> list[tuple[str, dict]]:
574
+ """Extract thermistor type → max_temp mappings from Klipper docs."""
575
+ records = []
576
+ # Pattern: "EPCOS 100K B57560G104F" with max_temp nearby
577
+ for match in re.finditer(
578
+ r'(?:thermistor|sensor)_type\s*[:=]\s*[\'"]?(\w+(?:\s+\w+)*)[\'"]?.*?max_temp\s*[:=]\s*(\d+)',
579
+ text, re.S | re.I
580
+ ):
581
+ records.append(("A", {
582
+ "material": "*",
583
+ "param": "max_temp",
584
+ "value": float(match.group(2)),
585
+ "source": f"{source_label}:{match.group(1).strip()}",
586
+ }))
587
+ return records
588
+
589
+
590
+ # ── Source-type dispatchers ───────────────────────────────────────────────────
591
+
592
+ def _parse_web_doc(text: str, url: str, source_key: str) -> list[tuple[str, dict]]:
593
+ """Parse a web documentation page into lane records."""
594
+ records = []
595
+ source_label = f"modal:{source_key}"
596
+
597
+ # Clean HTML tags if present
598
+ clean = re.sub(r'<[^>]+>', ' ', text)
599
+ clean = re.sub(r'\s+', ' ', clean).strip()
600
+
601
+ if len(clean) < 100:
602
+ return records
603
+
604
+ # Run all deterministic parsers
605
+ records.extend(_extract_temperature_values(clean, source_label))
606
+ records.extend(_extract_lessons_from_doc(clean, source_label))
607
+ records.extend(_extract_pid_values(clean, source_label))
608
+ records.extend(_extract_linear_advance(clean, source_label))
609
+ records.extend(_extract_thermistor_types(clean, source_label))
610
+
611
+ return records
612
+
613
+
614
+ def _parse_github_repo(repo_path: str, url: str, source_key: str) -> list[tuple[str, dict]]:
615
+ """Parse a cloned GitHub repo for config files and documentation."""
616
+ records = []
617
+ repo_dir = Path(repo_path)
618
+ if not repo_dir.exists():
619
+ return records
620
+
621
+ source_label = f"modal:{source_key}"
622
+
623
+ # Look for config files
624
+ config_patterns = [
625
+ ("**/*.cfg", _parse_klipper_style_cfg),
626
+ ("**/Configuration.h", _parse_marlin_style_h),
627
+ ("**/*.ini", _parse_prusa_style_ini),
628
+ ("**/README.md", _parse_readme),
629
+ ]
630
+
631
+ for glob_pattern, parser_fn in config_patterns:
632
+ for filepath in repo_dir.glob(glob_pattern):
633
+ try:
634
+ text = filepath.read_text(encoding="utf-8", errors="ignore")
635
+ records.extend(parser_fn(text, f"{source_label}:{filepath.name}"))
636
+ except Exception:
637
+ continue
638
+
639
+ return records
640
+
641
+
642
+ def _parse_prusa_profiles(text: str, url: str, source_key: str) -> list[tuple[str, dict]]:
643
+ """Parse PrusaSlicer INI profiles."""
644
+ return _parse_prusa_style_ini(text, f"modal:{source_key}")
645
+
646
+
647
+ def _parse_product_spec(text: str, url: str, source_key: str) -> list[tuple[str, dict]]:
648
+ """Parse product specification page for material parameters."""
649
+ records = []
650
+ source_label = f"modal:{source_key}"
651
+ clean = re.sub(r'<[^>]+>', ' ', text)
652
+ clean = re.sub(r'\s+', ' ', clean).strip()
653
+
654
+ # Extract temperature ranges
655
+ for match in re.finditer(
656
+ r'(?:print(?:ing)?|nozzle|extruder)\s*temp(?:erature)?\s*(?:range)?\s*[:=]?\s*(\d{3})\s*[-–]\s*(\d{3})\s*°?[CF]?',
657
+ clean, re.I
658
+ ):
659
+ material = _material_of(clean) or "TPU"
660
+ records.append(("A", {
661
+ "material": material,
662
+ "param": "nozzle_temp",
663
+ "value": float(match.group(1)),
664
+ "source": source_label,
665
+ }))
666
+
667
+ for match in re.finditer(
668
+ r'(?:bed|heatbed)\s*temp(?:erature)?\s*(?:range)?\s*[:=]?\s*(\d{2,3})\s*[-–]\s*(\d{2,3})\s*°?[CF]?',
669
+ clean, re.I
670
+ ):
671
+ material = _material_of(clean) or "TPU"
672
+ records.append(("A", {
673
+ "material": material,
674
+ "param": "bed_temp",
675
+ "value": float(match.group(1)),
676
+ "source": source_label,
677
+ }))
678
+
679
+ # Shore hardness
680
+ shore_match = re.search(r'(?:shore\s*hardness|hardness)\s*[:=]?\s*(\d{2}A)', clean, re.I)
681
+ if shore_match:
682
+ records.append(("A", {
683
+ "material": _material_of(clean) or "TPU",
684
+ "param": "shore_hardness",
685
+ "value": float(shore_match.group(1).replace("A", "")),
686
+ "source": source_label,
687
+ }))
688
+
689
+ return records
690
+
691
+
692
+ # ── Config file parsers (reuse logic from distill.py) ─────────────────────────
693
+
694
+ def _parse_klipper_style_cfg(text: str, source_label: str) -> list[tuple[str, dict]]:
695
+ """Parse Klipper-style cfg for max temps and settings."""
696
+ records = []
697
+ for section, param in (("extruder", "max_temp"), ("heater_bed", "bed_max_temp")):
698
+ m = re.search(rf"\[{section}\][^\[]*?max_temp\s*[:=]\s*(\d+(?:\.\d+)?)", text, re.S | re.I)
699
+ if m:
700
+ records.append(("A", {
701
+ "material": "*",
702
+ "param": param,
703
+ "value": float(m.group(1)),
704
+ "source": source_label,
705
+ }))
706
+ # PID values
707
+ records.extend(_extract_pid_values(text, source_label))
708
+ # Pressure advance
709
+ pa_match = re.search(r'pressure_advance\s*[:=]\s*([\d.]+)', text, re.I)
710
+ if pa_match:
711
+ records.append(("A", {
712
+ "material": "*",
713
+ "param": "pressure_advance",
714
+ "value": float(pa_match.group(1)),
715
+ "source": source_label,
716
+ }))
717
+ return records
718
+
719
+
720
+ def _parse_marlin_style_h(text: str, source_label: str) -> list[tuple[str, dict]]:
721
+ """Parse Marlin Configuration.h for max temps."""
722
+ records = []
723
+ for define, param in (("HEATER_0_MAXTEMP", "max_temp"), ("BED_MAXTEMP", "bed_max_temp")):
724
+ m = re.search(rf"#define\s+{define}\s+(\d+)", text)
725
+ if m:
726
+ records.append(("A", {
727
+ "material": "*",
728
+ "param": param,
729
+ "value": float(m.group(1)),
730
+ "source": source_label,
731
+ }))
732
+ # DEFAULT_Kp/Ki/Kd
733
+ for pid_param in ("DEFAULT_Kp", "DEFAULT_Ki", "DEFAULT_Kd"):
734
+ m = re.search(rf"#define\s+{pid_param}\s+([\d.]+)", text)
735
+ if m:
736
+ records.append(("A", {
737
+ "material": "*",
738
+ "param": pid_param.lower(),
739
+ "value": float(m.group(1)),
740
+ "source": source_label,
741
+ }))
742
+ # Linear advance K factor
743
+ la_match = re.search(r'#define\s+LIN_ADVANCE_K\s+([\d.]+)', text)
744
+ if la_match:
745
+ records.append(("A", {
746
+ "material": "*",
747
+ "param": "linear_advance_k",
748
+ "value": float(la_match.group(1)),
749
+ "source": source_label,
750
+ }))
751
+ return records
752
+
753
+
754
+ def _parse_prusa_style_ini(text: str, source_label: str) -> list[tuple[str, dict]]:
755
+ """Parse PrusaSlicer-style INI for filament settings."""
756
+ records = []
757
+ # Find filament sections and extract key values
758
+ current_material = None
759
+ for line in text.splitlines():
760
+ line = line.strip()
761
+ # Section header: [filament:Generic PLA]
762
+ section_match = re.match(r'\[(?:filament:)?(.+)\]', line, re.I)
763
+ if section_match:
764
+ current_material = _material_of(section_match.group(1))
765
+ continue
766
+
767
+ if not current_material:
768
+ continue
769
+
770
+ # Key = value pairs
771
+ kv_match = re.match(r'(\w+)\s*=\s*(.+)$', line)
772
+ if not kv_match:
773
+ continue
774
+
775
+ key, raw_val = kv_match.group(1), kv_match.group(2).strip()
776
+ num_match = re.search(r'-?\d+(?:\.\d+)?', raw_val.split(",")[0])
777
+ if not num_match:
778
+ continue
779
+ value = float(num_match.group())
780
+
781
+ param_map = {
782
+ "temperature": "nozzle_temp",
783
+ "first_layer_temperature": "nozzle_temp",
784
+ "bed_temperature": "bed_temp",
785
+ "first_layer_bed_temperature": "bed_temp",
786
+ "retract_length": "retraction_mm",
787
+ "retract_speed": "retraction_speed",
788
+ "fan_speed": "fan_pct",
789
+ "min_fan_speed": "fan_pct",
790
+ "max_fan_speed": "fan_pct",
791
+ }
792
+ param = param_map.get(key)
793
+ if param:
794
+ records.append(("A", {
795
+ "material": current_material,
796
+ "param": param,
797
+ "value": value,
798
+ "source": source_label,
799
+ }))
800
+
801
+ return records
802
+
803
+
804
+ def _parse_readme(text: str, source_label: str) -> list[tuple[str, dict]]:
805
+ """Parse README for reference facts and lessons."""
806
+ records = []
807
+ records.extend(_extract_temperature_values(text, source_label))
808
+ records.extend(_extract_lessons_from_doc(text, source_label))
809
+ return records
810
+
811
+
812
+ # ── Structured profile parsers (Tier S sources) ──────────────────────────────
813
+
814
+ def _parse_bambu_json_profiles(repo_path: str, url: str, source_key: str) -> list[tuple[str, dict]]:
815
+ """Parse BambuStudio tree-structured filament JSON profiles → Lane A.
816
+
817
+ Three-layer inheritance: fdm_filament_pla → Material@base → Material@BBL_A1.
818
+ Extracts: nozzle_temp, bed_temp, fan_speed, retraction, volumetric_speed,
819
+ flow_ratio, density, cost per material.
820
+ """
821
+ import json as _json
822
+ records = []
823
+ repo_dir = Path(repo_path)
824
+ filament_dir = repo_dir / "resources" / "profiles" / "BBL" / "filament"
825
+ if not filament_dir.exists():
826
+ return records
827
+
828
+ source_label = f"modal:{source_key}"
829
+
830
+ # First, load the root defaults (fdm_filament_pla.json, etc.)
831
+ root_defaults = {}
832
+ for root_file in filament_dir.glob("fdm_filament_*.json"):
833
+ try:
834
+ data = _json.loads(root_file.read_text(encoding="utf-8"))
835
+ mat_key = root_file.stem.replace("fdm_filament_", "")
836
+ root_defaults[mat_key] = data
837
+ except Exception:
838
+ continue
839
+
840
+ # Then process each material-specific file
841
+ for json_file in sorted(filament_dir.glob("*.json")):
842
+ name = json_file.stem
843
+ # Skip root defaults and non-material files
844
+ if name.startswith("fdm_filament_") or "@" not in name:
845
+ continue
846
+
847
+ try:
848
+ data = _json.loads(json_file.read_text(encoding="utf-8"))
849
+ except Exception:
850
+ continue
851
+
852
+ # Resolve inheritance chain
853
+ inherits = data.get("inherits", "")
854
+ parent_data = {}
855
+ if inherits in root_defaults:
856
+ parent_data = root_defaults[inherits]
857
+
858
+ # Merge: child overrides parent
859
+ merged = {**parent_data, **data}
860
+
861
+ # Extract material name from filename: "Bambu PLA Basic @BBL A1" → "PLA"
862
+ material = "*"
863
+ for m in MATERIALS:
864
+ if m in name.upper():
865
+ material = m
866
+ break
867
+ # Handle special materials
868
+ special_map = {
869
+ "PA": "ABS", "PC": "ABS", "ASA": "ABS", "PETG": "PETG",
870
+ "TPU": "TPU", "PLA": "PLA", "ABS": "ABS",
871
+ }
872
+ for key, mat in special_map.items():
873
+ if key in name.upper() and material == "*":
874
+ material = mat
875
+ break
876
+
877
+ src = f"{source_label}:{name}"
878
+
879
+ # Extract settings (BambuStudio uses array format ["value"])
880
+ def _first_num(val):
881
+ if isinstance(val, list) and val:
882
+ val = val[0]
883
+ if isinstance(val, str):
884
+ try:
885
+ return float(val.rstrip("%"))
886
+ except ValueError:
887
+ return None
888
+ if isinstance(val, (int, float)):
889
+ return float(val)
890
+ return None
891
+
892
+ param_map = {
893
+ "nozzle_temperature": "nozzle_temp",
894
+ "nozzle_temperature_initial_layer": "nozzle_temp",
895
+ "hot_plate_temp": "bed_temp",
896
+ "hot_plate_temp_initial_layer": "bed_temp",
897
+ "textured_plate_temp": "bed_temp",
898
+ "textured_plate_temp_initial_layer": "bed_temp",
899
+ "fan_max_speed": "fan_pct",
900
+ "fan_min_speed": "fan_pct",
901
+ "filament_max_volumetric_speed": "max_volumetric_speed",
902
+ "filament_flow_ratio": "flow_ratio",
903
+ "filament_density": "density",
904
+ "filament_cost": "cost",
905
+ "filament_retraction_length": "retraction_mm",
906
+ "filament_retraction_speed": "retraction_speed",
907
+ "slow_down_layer_time": "slow_down_layer_time",
908
+ }
909
+
910
+ for json_key, param in param_map.items():
911
+ val = _first_num(merged.get(json_key))
912
+ if val is not None:
913
+ records.append(("A", {
914
+ "material": material,
915
+ "param": param,
916
+ "value": val,
917
+ "source": src,
918
+ }))
919
+
920
+ return records
921
+
922
+
923
+ def _parse_klipper_config_repo(repo_path: str, url: str, source_key: str) -> list[tuple[str, dict]]:
924
+ """Parse Kanrog Klipper config generator → Lane A.
925
+
926
+ 150+ .cfg files with motherboard pin maps, PID values, max temps,
927
+ thermistor types, stepper driver settings.
928
+ """
929
+ records = []
930
+ repo_dir = Path(repo_path)
931
+ config_dir = repo_dir / "config-examples"
932
+ if not config_dir.exists():
933
+ return records
934
+
935
+ source_label = f"modal:{source_key}"
936
+
937
+ for cfg_file in config_dir.glob("*.cfg"):
938
+ try:
939
+ text = cfg_file.read_text(encoding="utf-8", errors="ignore")
940
+ except Exception:
941
+ continue
942
+
943
+ src = f"{source_label}:{cfg_file.name}"
944
+
945
+ # Reuse existing Klipper parser for max temps + PID
946
+ records.extend(_parse_klipper_style_cfg(text, src))
947
+
948
+ # Additional: extract stepper run_current
949
+ for match in re.finditer(r'run_current\s*[:=]\s*([\d.]+)', text):
950
+ records.append(("A", {
951
+ "material": "*",
952
+ "param": "run_current",
953
+ "value": float(match.group(1)),
954
+ "source": src,
955
+ }))
956
+
957
+ # Extract thermistor type
958
+ for match in re.finditer(r'sensor_type\s*[:=]\s*(\S+)', text):
959
+ records.append(("A", {
960
+ "material": "*",
961
+ "param": "sensor_type",
962
+ "value": 0,
963
+ "source": f"{src}:{match.group(1)}",
964
+ }))
965
+
966
+ # Extract microsteps
967
+ for match in re.finditer(r'microsteps\s*[:=]\s*(\d+)', text):
968
+ records.append(("A", {
969
+ "material": "*",
970
+ "param": "microsteps",
971
+ "value": float(match.group(1)),
972
+ "source": src,
973
+ }))
974
+
975
+ return records
976
+
977
+
978
+ def _parse_failure_detection_repo(repo_path: str, url: str, source_key: str) -> list[tuple[str, dict]]:
979
+ """Parse 3DPrintSaviour failure detection thresholds → Lane B lessons.
980
+
981
+ Extracts the NRMSE threshold constants and classification logic:
982
+ - Detachment: score > 1.0 AND deviance > 1.0
983
+ - Partial breakage: scr_diff > 0.2 AND dev_diff > 0.2
984
+ - Filament runout/clog: score < 0.2 AND deviance < 0.2
985
+ - Spaghetti: ML confidence ≥ 0.3
986
+ """
987
+ records = []
988
+ repo_dir = Path(repo_path)
989
+ source_label = f"modal:{source_key}"
990
+ now = datetime.now(timezone.utc).isoformat()
991
+
992
+ # Read printcontrol.py for threshold constants
993
+ pc_path = repo_dir / "printcontrol.py"
994
+ if pc_path.exists():
995
+ text = pc_path.read_text(encoding="utf-8", errors="ignore")
996
+
997
+ # Extract threshold constants
998
+ thresholds = {}
999
+ for match in re.finditer(r'(SCR_THRES|DEV_THRES|BR_SCR_THRES|BR_DEV_THRES|FIL_SCR_THRES|FIL_DEV_THRES)\s*=\s*([\d.]+)', text):
1000
+ thresholds[match.group(1)] = float(match.group(2))
1001
+
1002
+ # Detachment lesson
1003
+ if "SCR_THRES" in thresholds:
1004
+ records.append(("B", {
1005
+ "job_id": f"modal-saviour-detach-{hashlib.md5(b'detach').hexdigest()[:8]}",
1006
+ "material": "PLA",
1007
+ "geometry_type": "adhesion",
1008
+ "env_temp": 22.0,
1009
+ "env_humidity": 45.0,
1010
+ "outcome": "failed_sag",
1011
+ "lesson": (
1012
+ f"Print detachment detected when layer-to-layer NRMSE score > {thresholds['SCR_THRES']} "
1013
+ f"AND 5-layer deviance > {thresholds.get('DEV_THRES', 1.0)}. "
1014
+ "Large structural changes across consecutive layers indicate the part has separated from the bed. "
1015
+ "Check bed adhesion: clean surface, raise bed temp, use brim or raft."
1016
+ ),
1017
+ "source": "ingested",
1018
+ "timestamp": now,
1019
+ }))
1020
+
1021
+ # Clog/runout lesson
1022
+ if "FIL_SCR_THRES" in thresholds:
1023
+ records.append(("B", {
1024
+ "job_id": f"modal-saviour-clog-{hashlib.md5(b'clog').hexdigest()[:8]}",
1025
+ "material": "PLA",
1026
+ "geometry_type": "stringing",
1027
+ "env_temp": 22.0,
1028
+ "env_humidity": 45.0,
1029
+ "outcome": "failed_stringing",
1030
+ "lesson": (
1031
+ f"Filament runout or nozzle clog detected when NRMSE score < {thresholds['FIL_SCR_THRES']} "
1032
+ f"AND deviance < {thresholds.get('FIL_DEV_THRES', 0.2)}. "
1033
+ "Near-zero structural change means no material is being deposited. "
1034
+ "Check filament spool, extruder tension, and nozzle for clogs."
1035
+ ),
1036
+ "source": "ingested",
1037
+ "timestamp": now,
1038
+ }))
1039
+
1040
+ # Partial breakage lesson
1041
+ if "BR_SCR_THRES" in thresholds:
1042
+ records.append(("B", {
1043
+ "job_id": f"modal-saviour-break-{hashlib.md5(b'break').hexdigest()[:8]}",
1044
+ "material": "PLA",
1045
+ "geometry_type": "overhang",
1046
+ "env_temp": 22.0,
1047
+ "env_humidity": 45.0,
1048
+ "outcome": "failed_sag",
1049
+ "lesson": (
1050
+ f"Partial breakage detected when frame-to-frame score delta > {thresholds['BR_SCR_THRES']} "
1051
+ f"AND deviance delta > {thresholds.get('BR_DEV_THRES', 0.2)}. "
1052
+ "Sudden structural changes mid-print indicate layer delamination or part fracture. "
1053
+ "Reduce cooling fan, increase nozzle temp, check for drafts."
1054
+ ),
1055
+ "source": "ingested",
1056
+ "timestamp": now,
1057
+ }))
1058
+
1059
+ return records
1060
+
1061
+
1062
+ def _parse_filament_profiles_repo(repo_path: str, url: str, source_key: str) -> list[tuple[str, dict]]:
1063
+ """Parse jklewa filament-profiles-data → Lane A.
1064
+
1065
+ sample-filaments.json: community-verified nozzle/bed temp ranges,
1066
+ material type, vendor, price, color per filament SKU.
1067
+ """
1068
+ import json as _json
1069
+ records = []
1070
+ repo_dir = Path(repo_path)
1071
+ json_path = repo_dir / "sample-filaments.json"
1072
+ if not json_path.exists():
1073
+ return records
1074
+
1075
+ source_label = f"modal:{source_key}"
1076
+
1077
+ try:
1078
+ data = _json.loads(json_path.read_text(encoding="utf-8"))
1079
+ except Exception:
1080
+ return records
1081
+
1082
+ filaments = data.get("filaments", [])
1083
+ for fil in filaments:
1084
+ material_name = str(fil.get("material", "")).upper()
1085
+ material = "*"
1086
+ for m in MATERIALS:
1087
+ if m in material_name:
1088
+ material = m
1089
+ break
1090
+
1091
+ brand = fil.get("brand_name", "unknown")
1092
+ color = fil.get("color", "")
1093
+ src = f"{source_label}:{brand}/{material_name}/{color}" if color else f"{source_label}:{brand}/{material_name}"
1094
+
1095
+ # Properties: temp_min, temp_max, bed_temp_min, bed_temp_max
1096
+ props = fil.get("properties") or fil.get("default_properties") or {}
1097
+
1098
+ for key, param in [("temp_min", "nozzle_temp_min"), ("temp_max", "nozzle_temp_max"),
1099
+ ("bed_temp_min", "bed_temp_min"), ("bed_temp_max", "bed_temp_max")]:
1100
+ val = props.get(key)
1101
+ if val is not None:
1102
+ try:
1103
+ records.append(("A", {"material": material, "param": param,
1104
+ "value": float(val), "source": src}))
1105
+ except (ValueError, TypeError):
1106
+ pass
1107
+
1108
+ # Optional: k_value, flow_ratio, fan_speed_min
1109
+ for key, param in [("k_value", "linear_advance_k"), ("flow_ratio", "flow_ratio"),
1110
+ ("fan_speed_min", "fan_pct")]:
1111
+ val = props.get(key)
1112
+ if val is not None:
1113
+ try:
1114
+ records.append(("A", {"material": material, "param": param,
1115
+ "value": float(val), "source": src}))
1116
+ except (ValueError, TypeError):
1117
+ pass
1118
+
1119
+ # Price data
1120
+ price_data = fil.get("price_data")
1121
+ if price_data and price_data.get("price"):
1122
+ try:
1123
+ records.append(("A", {"material": material, "param": "price_usd",
1124
+ "value": float(price_data["price"]), "source": src}))
1125
+ except (ValueError, TypeError):
1126
+ pass
1127
+
1128
+ return records
1129
+
1130
+
1131
+ def _parse_fdm_error_gcode(repo_path: str, url: str, source_key: str) -> list[tuple[str, dict]]:
1132
+ """Parse FDM error detection G-code + YAML → Lane C calibration observations.
1133
+
1134
+ NilsHagenBeyer/3D-printing_recorder: G-code files with known failure outcomes.
1135
+ YAML metadata logs: class (GOOD/STRINGING/underextrusion), filament, nozzle,
1136
+ retraction, layer_height, extrusion_multiplier.
1137
+ G-code filenames encode: temperature, material, printer.
1138
+
1139
+ FIXED (per RESEARCH-NEEDS.md):
1140
+ - Parse M106 across the WHOLE file, not just header
1141
+ - Parse retraction from G1 E- moves + PrusaSlicer footer comments
1142
+ - Infer geometry from G-code moves (bridge/overhang), not bbox heuristic
1143
+ - Skip rows where fan_pct can't be determined (no M106 found → null, not 0)
1144
+ """
1145
+ import yaml as _yaml
1146
+ records = []
1147
+ repo_dir = Path(repo_path)
1148
+ gcode_dir = repo_dir / "gcode"
1149
+ if not gcode_dir.exists():
1150
+ return records
1151
+
1152
+ source_label = f"modal:{source_key}"
1153
+
1154
+ # Failure class → outcome
1155
+ failure_map = {
1156
+ "good": "success",
1157
+ "stringing": "failed_stringing",
1158
+ "underextrusion": "failed_sag",
1159
+ "underex": "failed_sag",
1160
+ }
1161
+
1162
+ def _infer_geometry_from_gcode(text: str) -> str:
1163
+ """Infer geometry type from G-code move patterns.
1164
+
1165
+ Bridge: long X/Y moves at the same Z with extrusion → spanning gaps.
1166
+ Overhang: outward-stepping perimeters (X/Y expanding each layer).
1167
+ Stringing: many travel moves (G0) between disconnected regions.
1168
+ Default: overhang.
1169
+ """
1170
+ # Count travel moves vs extrusion moves
1171
+ travels = len(re.findall(r'\nG0\s', text))
1172
+ extrudes = len(re.findall(r'\nG1\s.*?E', text))
1173
+ if extrudes > 0 and travels > extrudes * 0.3:
1174
+ return "stringing" # high travel ratio = disconnected regions
1175
+
1176
+ # Look for bridge patterns: long X/Y moves at same Z
1177
+ bridge_moves = 0
1178
+ prev_z = None
1179
+ for match in re.finditer(r'G1\s.*?X([\d.]+)\s+Y([\d.]+)\s+Z([\d.]+).*?E([\d.]+)', text):
1180
+ z = float(match.group(3))
1181
+ e = float(match.group(4))
1182
+ if prev_z is not None and abs(z - prev_z) < 0.01 and e > 0.5:
1183
+ dx = abs(float(match.group(1)) - prev_x) if 'prev_x' in dir() else 0
1184
+ dy = abs(float(match.group(2)) - prev_y) if 'prev_y' in dir() else 0
1185
+ if dx > 30 or dy > 30:
1186
+ bridge_moves += 1
1187
+ prev_z = z
1188
+ prev_x = float(match.group(1))
1189
+ prev_y = float(match.group(2))
1190
+ if bridge_moves > 3:
1191
+ return "bridge"
1192
+
1193
+ return "overhang"
1194
+
1195
+ def _parse_retraction(text: str, yaml_entry: dict) -> float | None:
1196
+ """Parse retraction from G-code moves + slicer footer + YAML."""
1197
+ # 1. YAML metadata (most reliable)
1198
+ yaml_ret = yaml_entry.get("retraction")
1199
+ if yaml_ret is not None:
1200
+ return float(yaml_ret)
1201
+
1202
+ # 2. PrusaSlicer/Orca footer comment block (last 2KB of file)
1203
+ footer = text[-2000:] if len(text) > 2000 else text
1204
+ footer_match = re.search(r';\s*retract_length\s*=\s*([\d.]+)', footer, re.I)
1205
+ if footer_match:
1206
+ return float(footer_match.group(1))
1207
+
1208
+ # 3. G1 E- retraction moves (negative extrusion = retract)
1209
+ retract_moves = re.findall(r'G1\s.*?E-([\d.]+)', text)
1210
+ if retract_moves:
1211
+ return float(retract_moves[0])
1212
+
1213
+ return None
1214
+
1215
+ def _parse_fan(text: str) -> float | None:
1216
+ """Parse fan speed from M106 across the WHOLE file + slicer footer."""
1217
+ # 1. M106 commands anywhere in the file
1218
+ fan_matches = re.findall(r'M106\s+S(\d+)', text)
1219
+ if fan_matches:
1220
+ # Use the most common non-zero fan speed
1221
+ fans = [int(f) for f in fan_matches if int(f) > 0]
1222
+ if fans:
1223
+ # Convert 0-255 PWM to 0-100%
1224
+ fan_val = max(set(fans), key=fans.count)
1225
+ return round(fan_val / 255.0 * 100, 1)
1226
+
1227
+ # 2. PrusaSlicer/Orca footer comment block
1228
+ footer = text[-3000:] if len(text) > 3000 else text
1229
+ for key in ['fan_speed', 'fan_percentage', 'cooling_fan_speed', 'bridge_fan_speed']:
1230
+ m = re.search(rf';\s*{key}\s*=\s*([\d.]+)', footer, re.I)
1231
+ if m:
1232
+ return float(m.group(1))
1233
+
1234
+ # 3. M107 (fan off) — explicit off is valid data
1235
+ if re.search(r'M107', text):
1236
+ return 0.0
1237
+
1238
+ return None # Can't determine — skip this row
1239
+
1240
+ # Process each macro run directory
1241
+ for macro_dir in sorted(gcode_dir.iterdir()):
1242
+ if not macro_dir.is_dir():
1243
+ continue
1244
+
1245
+ # Determine failure type from directory name
1246
+ dir_name = macro_dir.name.lower()
1247
+ failure_type = "good"
1248
+ if "stringing" in dir_name:
1249
+ failure_type = "stringing"
1250
+ elif "underex" in dir_name:
1251
+ failure_type = "underextrusion"
1252
+ elif "good" in dir_name:
1253
+ failure_type = "good"
1254
+
1255
+ outcome = failure_map.get(failure_type, "success")
1256
+
1257
+ # Load YAML metadata if present
1258
+ yaml_data = {}
1259
+ for yaml_file in macro_dir.glob("*.yaml"):
1260
+ try:
1261
+ yaml_data = _yaml.safe_load(yaml_file.read_text(encoding="utf-8"))
1262
+ except Exception:
1263
+ pass
1264
+
1265
+ # Build lookup from YAML: gcode filename → metadata
1266
+ yaml_lookup = {}
1267
+ if isinstance(yaml_data, list):
1268
+ for entry in yaml_data:
1269
+ gcode_name = entry.get("gcode", "")
1270
+ if gcode_name:
1271
+ yaml_lookup[gcode_name] = entry
1272
+
1273
+ # Process each G-code file
1274
+ for gcode_file in sorted(macro_dir.glob("*.gcode")):
1275
+ try:
1276
+ full_text = gcode_file.read_text(encoding="utf-8", errors="ignore")
1277
+ except Exception:
1278
+ continue
1279
+
1280
+ # Parse settings from the FULL file — use FINAL temps (M109/M190), not preheat
1281
+ nozzle_matches = re.findall(r'M109\s+S(\d+)', full_text) # wait-for-nozzle = final temp
1282
+ if not nozzle_matches:
1283
+ nozzle_matches = re.findall(r'M104\s+S(\d+)', full_text)
1284
+ if nozzle_matches:
1285
+ nozzle_temp = float(nozzle_matches[-1]) # last M104 = final
1286
+ else:
1287
+ continue
1288
+ else:
1289
+ nozzle_temp = float(nozzle_matches[-1])
1290
+
1291
+ bed_matches = re.findall(r'M190\s+S(\d+)', full_text) # wait-for-bed = final temp
1292
+ if not bed_matches:
1293
+ bed_matches = re.findall(r'M140\s+S(\d+)', full_text)
1294
+ bed_temp = float(bed_matches[-1]) if bed_matches else 60.0
1295
+
1296
+ # Parse fan — skip row if can't determine (RESEARCH-NEEDS.md fix #1)
1297
+ fan_pct = _parse_fan(full_text)
1298
+ if fan_pct is None:
1299
+ continue # Skip — can't trust fan=0 default
1300
+
1301
+ # Parse filename for material
1302
+ fname = gcode_file.name.upper()
1303
+ material = "PLA"
1304
+ for m in MATERIALS:
1305
+ if m in fname:
1306
+ material = m
1307
+ break
1308
+
1309
+ # Get YAML metadata
1310
+ yaml_entry = yaml_lookup.get(gcode_file.name, {})
1311
+
1312
+ # Parse retraction (RESEARCH-NEEDS.md fix #2)
1313
+ retraction = _parse_retraction(full_text, yaml_entry)
1314
+ if retraction is None:
1315
+ retraction = 5.0 # fallback default
1316
+
1317
+ # Infer geometry from G-code moves (RESEARCH-NEEDS.md fix #3)
1318
+ geometry_type = _infer_geometry_from_gcode(full_text)
1319
+ # Override with failure type if it's more specific
1320
+ if failure_type == "stringing":
1321
+ geometry_type = "stringing"
1322
+
1323
+ # Quality estimate from extrusion multiplier
1324
+ ex_mul = float(yaml_entry.get("extrusion_multiplier", yaml_entry.get("ex_mul", 1.0)))
1325
+ quality = max(0.1, min(1.0, ex_mul)) if failure_type == "good" else max(0.1, min(0.7, 1.0 - abs(1.0 - ex_mul)))
1326
+
1327
+ records.append(("C", {
1328
+ "material": material,
1329
+ "geometry_type": geometry_type,
1330
+ "env_temp": 22.0,
1331
+ "env_humidity": 45.0,
1332
+ "nozzle_temp": nozzle_temp,
1333
+ "bed_temp": bed_temp,
1334
+ "retraction_mm": retraction,
1335
+ "fan_pct": fan_pct,
1336
+ "first_layer_fan_pct": 0,
1337
+ "outcome": outcome,
1338
+ "quality": round(quality, 2),
1339
+ }))
1340
+
1341
+ return records
1342
+
1343
+
1344
+ # ── Source-type → parser dispatch ─────────────────────────────────────────────
1345
+
1346
+ PARSER_DISPATCH = {
1347
+ "web_doc": _parse_web_doc,
1348
+ "github_repo": _parse_github_repo,
1349
+ "prusa_profiles": _parse_prusa_profiles,
1350
+ "product_spec": _parse_product_spec,
1351
+ "research_repo": _parse_github_repo,
1352
+ "bambu_json_profiles": _parse_bambu_json_profiles,
1353
+ "klipper_config_repo": _parse_klipper_config_repo,
1354
+ "failure_detection_repo": _parse_failure_detection_repo,
1355
+ "filament_profiles_repo": _parse_filament_profiles_repo,
1356
+ "fdm_error_gcode": _parse_fdm_error_gcode,
1357
+ }
1358
+
1359
+
1360
+ # ═══════════════════════════════════════════════════════════════════════════════
1361
+ # Modal App
1362
+ # ═══════════════════════════════════════════════════════════════════════════════
1363
 
1364
  if modal is not None:
1365
  app = modal.App("chief-engineer-ingest")
 
 
 
 
 
 
 
 
 
1366
 
1367
+ # Persistent volume for caching fetched content (Spanish tutor pattern)
1368
+ vol = modal.Volume.from_name("chief-engineer-ingest-data", create_if_missing=True)
1369
+
1370
+ # Image with dependencies
1371
+ image = (
1372
+ modal.Image.debian_slim()
1373
+ .pip_install(
1374
+ "datasets", "pyarrow", "huggingface_hub",
1375
+ "pydantic>=2.7", "requests", "beautifulsoup4",
1376
+ "pyyaml",
1377
+ )
1378
+ .apt_install("git", "wget")
1379
+ # Share enums into the image (Spanish tutor pattern)
1380
+ # Must be last — add_local_* after build steps
1381
+ .env({"PYTHONPATH": "/root"})
1382
+ .add_local_file("core/models.py", "/root/core/models.py")
1383
+ )
1384
+
1385
+ # ── HF Dataset Distillation ───────────────────────────────────────────
1386
+
1387
+ @app.function(
1388
+ image=image,
1389
+ timeout=3600,
1390
+ cpu=4,
1391
+ memory=4096,
1392
+ secrets=[modal.Secret.from_name("chief-engineer-secrets")],
1393
+ )
1394
+ def distill_hf_dataset(dataset: str, limit: int = 1000, split: str = "train") -> dict:
1395
+ """Load an HF dataset, map rows → lane records.
1396
+
1397
+ Special case: 3dtime loads from metadata CSV (not standard rows).
1398
+ """
1399
+ import csv
1400
+ import io
1401
+ import requests
1402
+
1403
+ if dataset not in HF_MAPPERS:
1404
+ return {"error": f"unknown dataset '{dataset}'; known: {list(HF_MAPPERS)}"}
1405
+ hf_id, mapper = HF_MAPPERS[dataset]
1406
+
1407
  out: dict[str, list] = {"A": [], "B": [], "C": []}
1408
+
1409
+ # 3DTime special case: download metadata CSV + G-code headers
1410
+ if dataset == "3dtime":
1411
+ csv_url = f"https://huggingface.co/datasets/{hf_id}/resolve/main/metadata/metadata_sub21.csv"
1412
+ resp = requests.get(csv_url, timeout=30)
1413
+ resp.raise_for_status()
1414
+ reader = csv.DictReader(io.StringIO(resp.text))
1415
+ rows = list(reader)[:limit]
1416
+
1417
+ for row in rows:
1418
+ # Lane A: metadata reference facts
1419
+ for lane, rec in mapper(row):
1420
+ if lane in _VALID_LANES:
1421
+ out[lane].append(rec)
1422
+
1423
+ # Lane C: download G-code header + footer, extract settings
1424
+ gcode_name = row.get("G-code file name", "")
1425
+ if gcode_name:
1426
+ try:
1427
+ gcode_url = f"https://huggingface.co/datasets/{hf_id}/resolve/main/sliced/21/{gcode_name}"
1428
+ # Download header (first 10KB) for nozzle/bed temps
1429
+ gcode_resp = requests.get(gcode_url, stream=True, timeout=15)
1430
+ header = ""
1431
+ for chunk in gcode_resp.iter_content(chunk_size=1024):
1432
+ header += chunk.decode("utf-8", errors="ignore")
1433
+ if len(header) > 10000:
1434
+ break
1435
+ # Also try to get footer (last 3KB) for fan/retraction settings
1436
+ footer = ""
1437
+ try:
1438
+ content_length = gcode_resp.headers.get("Content-Length")
1439
+ if content_length:
1440
+ size = int(content_length)
1441
+ if size > 3000:
1442
+ footer_resp = requests.get(gcode_url, headers={"Range": f"bytes={size-3000}-{size}"}, timeout=10)
1443
+ footer = footer_resp.text
1444
+ except Exception:
1445
+ pass
1446
+ full_text = header + footer
1447
+
1448
+ # Parse nozzle/bed — use FINAL temps (M109/M190)
1449
+ nozzle_matches = re.findall(r'M109\s+S(\d+)', full_text)
1450
+ if not nozzle_matches:
1451
+ nozzle_matches = re.findall(r'M104\s+S(\d+)', full_text)
1452
+ bed_matches = re.findall(r'M190\s+S(\d+)', full_text)
1453
+ if not bed_matches:
1454
+ bed_matches = re.findall(r'M140\s+S(\d+)', full_text)
1455
+ if not nozzle_matches or not bed_matches:
1456
+ continue
1457
+ nozzle_temp = float(nozzle_matches[-1])
1458
+ bed_temp = float(bed_matches[-1])
1459
+
1460
+ # Parse fan from M106 across full text + slicer footer
1461
+ fan_matches = re.findall(r'M106\s+S(\d+)', full_text)
1462
+ fan_pct = None
1463
+ if fan_matches:
1464
+ fans = [int(f) for f in fan_matches if int(f) > 0]
1465
+ if fans:
1466
+ fan_pct = round(max(set(fans), key=fans.count) / 255.0 * 100, 1)
1467
+ if fan_pct is None:
1468
+ # Check slicer footer comments
1469
+ for key in ['fan_speed', 'fan_percentage', 'cooling_fan_speed', 'bridge_fan_speed']:
1470
+ m = re.search(rf';\s*{key}\s*=\s*([\d.]+)', full_text, re.I)
1471
+ if m:
1472
+ fan_pct = float(m.group(1))
1473
+ break
1474
+ if fan_pct is None and re.search(r'M107', full_text):
1475
+ fan_pct = 0.0 # explicit fan off
1476
+ if fan_pct is None:
1477
+ continue # Skip — can't determine fan (RESEARCH-NEEDS.md fix)
1478
+
1479
+ material_map = {"pla": "PLA", "pet": "PETG", "abs": "ABS", "tpu": "TPU"}
1480
+ material = material_map.get(str(row.get("Material", "")).lower(), "PLA")
1481
+
1482
+ # Parse retraction from footer or G-code
1483
+ retraction = 5.0
1484
+ footer_ret = re.search(r';\s*retract_length\s*=\s*([\d.]+)', full_text, re.I)
1485
+ if footer_ret:
1486
+ retraction = float(footer_ret.group(1))
1487
+ else:
1488
+ retract_moves = re.findall(r'G1\s.*?E-([\d.]+)', full_text)
1489
+ if retract_moves:
1490
+ retraction = float(retract_moves[0])
1491
+
1492
+ # Geometry from bounding box (3DTime has no G-code move context in header)
1493
+ try:
1494
+ bx, by, bz = float(row["Bounding box X (mm)"]), float(row["Bounding box Y (mm)"]), float(row["Bounding box Z (mm)"])
1495
+ except (KeyError, ValueError):
1496
+ bx, by, bz = 50, 50, 20
1497
+ ratio = bx / max(by, 0.1)
1498
+ if bz < 5:
1499
+ geometry = "vase"
1500
+ elif ratio > 5:
1501
+ geometry = "bridge"
1502
+ elif bz > bx * 0.8:
1503
+ geometry = "adhesion"
1504
+ else:
1505
+ geometry = "overhang"
1506
+
1507
+ out["C"].append({
1508
+ "material": material,
1509
+ "geometry_type": geometry,
1510
+ "env_temp": 22.0,
1511
+ "env_humidity": 45.0,
1512
+ "nozzle_temp": float(nozzle_matches[-1]),
1513
+ "bed_temp": float(bed_matches[-1]),
1514
+ "retraction_mm": retraction,
1515
+ "fan_pct": fan_pct,
1516
+ "first_layer_fan_pct": 0,
1517
+ "outcome": "success",
1518
+ "quality": 0.85,
1519
+ })
1520
+ except Exception:
1521
+ pass
1522
+ out["stats"] = {
1523
+ "dataset": dataset, "hf_id": hf_id, "rows": len(rows),
1524
+ "A": len(out["A"]), "B": len(out["B"]), "C": len(out["C"]),
1525
+ }
1526
+ return out
1527
+
1528
+ # Standard HF dataset
1529
+ from datasets import load_dataset
1530
+ ds = load_dataset(hf_id, split=f"{split}[:{limit}]")
1531
  for row in ds:
1532
  for lane, rec in mapper(dict(row)):
1533
  if lane in _VALID_LANES:
1534
  out[lane].append(rec)
1535
+ out["stats"] = {
1536
+ "dataset": dataset, "hf_id": hf_id, "rows": len(ds),
1537
+ "A": len(out["A"]), "B": len(out["B"]), "C": len(out["C"]),
1538
+ }
1539
  return out
1540
 
1541
+ # ── Documentation Source Fetching ─────────────────────────────────────
1542
+
1543
+ @app.function(
1544
+ image=image,
1545
+ volumes={"/data": vol},
1546
+ timeout=600,
1547
+ secrets=[modal.Secret.from_name("chief-engineer-secrets")],
1548
+ )
1549
+ def fetch_and_parse_source(source_key: str) -> dict:
1550
+ """Fetch a documentation source, parse it, return lane records.
1551
+
1552
+ Uses Modal Volume for caching: if already fetched, skips download.
1553
+ Idempotent/resumable (Spanish tutor pattern).
1554
+ """
1555
+ import requests
1556
+ import subprocess
1557
+ import tempfile
1558
+
1559
+ if source_key not in SOURCES:
1560
+ return {"error": f"unknown source '{source_key}'", "source_key": source_key}
1561
+
1562
+ url, category, source_type, description = SOURCES[source_key]
1563
+ cache_dir = Path("/data/cache")
1564
+ cache_dir.mkdir(parents=True, exist_ok=True)
1565
+
1566
+ # Cache key from URL hash
1567
+ cache_key = hashlib.md5(url.encode()).hexdigest()[:12]
1568
+ content_path = cache_dir / f"{source_key}_{cache_key}.txt"
1569
+ records_path = cache_dir / f"{source_key}_{cache_key}_records.json"
1570
+
1571
+ # Check cache — idempotent/resumable
1572
+ if records_path.exists():
1573
+ try:
1574
+ cached = json.loads(records_path.read_text())
1575
+ print(f" ✓ {source_key}: loaded from cache ({cached.get('stats', {}).get('total', 0)} records)")
1576
+ return cached
1577
+ except Exception:
1578
+ pass
1579
+
1580
+ # Fetch content
1581
+ content = ""
1582
+ if source_type == "github_repo" or source_type == "research_repo" or source_type in ("bambu_json_profiles", "klipper_config_repo", "failure_detection_repo", "filament_profiles_repo", "fdm_error_gcode"):
1583
+ # Download repo as zip (more reliable than git clone on Modal)
1584
+ repo_name = url.rstrip("/").split("/")[-1]
1585
+ repo_dir = cache_dir / f"repo_{source_key}_{cache_key}"
1586
+ if not repo_dir.exists():
1587
+ print(f" downloading {url} → {repo_dir}")
1588
+ zip_url = f"https://github.com/{url.split('github.com/')[-1]}/archive/refs/heads/main.zip"
1589
+ try:
1590
+ resp = requests.get(zip_url, timeout=120, headers={"User-Agent": "chief-engineer/1.0"})
1591
+ resp.raise_for_status()
1592
+ import zipfile as _zipfile
1593
+ import io as _io
1594
+ with _zipfile.ZipFile(_io.BytesIO(resp.content)) as zf:
1595
+ # Extract all files, stripping the top-level directory
1596
+ for member in zf.namelist():
1597
+ # Strip the leading repo-name-branch directory
1598
+ parts = member.split("/", 1)
1599
+ if len(parts) > 1:
1600
+ target = repo_dir / parts[1]
1601
+ if member.endswith("/"):
1602
+ target.mkdir(parents=True, exist_ok=True)
1603
+ else:
1604
+ target.parent.mkdir(parents=True, exist_ok=True)
1605
+ with zf.open(member) as src, open(target, "wb") as dst:
1606
+ dst.write(src.read())
1607
+ print(f" ✓ extracted to {repo_dir}")
1608
+ except Exception as e:
1609
+ print(f" ⚠ download failed: {e}")
1610
+ return {"error": f"download failed: {e}", "source_key": source_key}
1611
+
1612
+ # Parse the cloned repo
1613
+ records = _parse_github_repo(str(repo_dir), url, source_key)
1614
+ content = f"[cloned repo at {repo_dir}]"
1615
+
1616
+ elif source_type == "prusa_profiles":
1617
+ # Download INI files from PrusaSlicer repository
1618
+ print(f" fetching Prusa profiles from {url}")
1619
+ try:
1620
+ resp = requests.get(url, timeout=30, headers={"User-Agent": "chief-engineer/1.0"})
1621
+ resp.raise_for_status()
1622
+ content = resp.text
1623
+ # Parse INI content
1624
+ records = _parse_prusa_profiles(content, url, source_key)
1625
+ except Exception as e:
1626
+ print(f" ⚠ fetch failed: {e}")
1627
+ return {"error": f"fetch failed: {e}", "source_key": source_key}
1628
+
1629
+ else:
1630
+ # web_doc, product_spec — fetch HTML
1631
+ print(f" fetching {url}")
1632
+ try:
1633
+ resp = requests.get(url, timeout=30, headers={"User-Agent": "chief-engineer/1.0"})
1634
+ resp.raise_for_status()
1635
+ content = resp.text
1636
+ except Exception as e:
1637
+ print(f" ⚠ fetch failed: {e}")
1638
+ return {"error": f"fetch failed: {e}", "source_key": source_key}
1639
+
1640
+ # Parse based on source type
1641
+ parser = PARSER_DISPATCH.get(source_type, _parse_web_doc)
1642
+ records = parser(content, url, source_key)
1643
+
1644
+ # Save content cache
1645
+ content_path.write_text(content[:50000], encoding="utf-8") # truncate for cache
1646
+
1647
+ # Build result
1648
+ out: dict[str, list] = {"A": [], "B": [], "C": []}
1649
+ for lane, rec in records:
1650
+ if lane in _VALID_LANES:
1651
+ out[lane].append(rec)
1652
+
1653
+ stats = {
1654
+ "source_key": source_key,
1655
+ "category": category,
1656
+ "url": url,
1657
+ "A": len(out["A"]),
1658
+ "B": len(out["B"]),
1659
+ "C": len(out["C"]),
1660
+ "total": len(records),
1661
+ }
1662
+ out["stats"] = stats
1663
+
1664
+ # Cache records
1665
+ records_path.write_text(json.dumps(out))
1666
+
1667
+ # Commit volume (Spanish tutor pattern)
1668
+ vol.commit()
1669
+
1670
+ print(f" ✓ {source_key}: {stats['total']} records (A:{stats['A']} B:{stats['B']} C:{stats['C']})")
1671
+ return out
1672
+
1673
+ # ── Main Entrypoint ───────────────────────────────────────────────────
1674
+
1675
  @app.local_entrypoint()
1676
+ def main(
1677
+ source: str = "",
1678
+ category: str = "",
1679
+ dataset: str = "",
1680
+ limit: int = 1000,
1681
+ ):
1682
+ """Run locally: fan out to Modal, then write artifacts.
1683
+
1684
+ Usage:
1685
+ modal run ingest/modal_app.py # all sources
1686
+ modal run ingest/modal_app.py --source klipper-config # single source
1687
+ modal run ingest/modal_app.py --category calibration # category
1688
+ modal run ingest/modal_app.py --dataset 3d-adam # HF dataset
1689
+ """
1690
  root = Path(__file__).resolve().parent.parent
 
1691
  agg: dict[str, list] = {"A": [], "B": [], "C": []}
 
 
 
 
 
1692
 
1693
+ # ── Process documentation sources ──
1694
+ if not dataset:
1695
+ targets = []
1696
+ if source:
1697
+ if source not in SOURCES:
1698
+ print(f"Unknown source: {source}")
1699
+ print(f"Known sources: {list(SOURCES.keys())}")
1700
+ return
1701
+ targets = [source]
1702
+ elif category:
1703
+ targets = [k for k, v in SOURCES.items() if v[1] == category]
1704
+ if not targets:
1705
+ print(f"No sources in category '{category}'")
1706
+ print(f"Categories: {set(v[1] for v in SOURCES.values())}")
1707
+ return
1708
+ else:
1709
+ targets = list(SOURCES.keys())
1710
+
1711
+ print(f"Processing {len(targets)} documentation sources...\n")
1712
+ for src_key in targets:
1713
+ res = fetch_and_parse_source.remote(src_key)
1714
+ stats = res.get("stats", res)
1715
+ if "error" in stats:
1716
+ print(f" ✗ {src_key}: {stats['error']}")
1717
+ else:
1718
+ print(f" ✓ {src_key}: A={stats.get('A',0)} B={stats.get('B',0)} C={stats.get('C',0)}")
1719
+ for lane in ("A", "B", "C"):
1720
+ agg[lane].extend(res.get(lane, []))
1721
+
1722
+ # ── Process HF datasets ──
1723
+ if dataset:
1724
+ targets = [dataset] if dataset else list(HF_MAPPERS)
1725
+ print(f"Processing {len(targets)} HF datasets...\n")
1726
+ for d in targets:
1727
+ res = distill_hf_dataset.remote(d, limit)
1728
+ stats = res.get("stats", res)
1729
+ print(f" {stats}")
1730
+ for lane in ("A", "B", "C"):
1731
+ agg[lane].extend(res.get(lane, []))
1732
+
1733
+ # ── Write artifacts ──
1734
  def _write(path: Path, rows: list, append: bool):
1735
  if not rows:
1736
  return
 
1740
  f.write(json.dumps(r) + "\n")
1741
  print(f" wrote {len(rows)} → {path.relative_to(root)}")
1742
 
1743
+ print(f"\n── Artifacts ──")
1744
+ _write(root / "data" / "references.jsonl", agg["A"], append=True)
1745
+ _write(root / "data" / "_modal_candidate_lessons.jsonl", agg["B"], append=True)
1746
+ _write(root / "sim" / "calibration" / "observations.modal.jsonl", agg["C"], append=True)
1747
+
1748
+ print(f"\n── Summary ──")
1749
+ print(f" Lane A (references): {len(agg['A'])}")
1750
+ print(f" Lane B (candidate lessons): {len(agg['B'])} ← REVIEW before ledger!")
1751
+ print(f" Lane C (calibration obs): {len(agg['C'])}")
1752
+ print(f"\nNext:")
1753
+ print(f" • REVIEW data/_modal_candidate_lessons.jsonl (honesty gate)")
1754
+ print(f" • Fold good lessons into ledger via ingest_candidate_lessons")
1755
+ print(f" • Calibrate: uv run python -m sim.calibrate --data sim/calibration/observations.modal.jsonl")
1756
+ print(f" • make test → make run")
1757
+
1758
+ # FRONTIER (named in writeup, NOT in-window):
1759
+ # Fine-tune a small Gemma on the accumulated ledger.
1760
  # @app.function(gpu="A10G", image=image, timeout=3600)
1761
  # def finetune_on_ledger(...): ...
1762
 
1763
 
1764
  if __name__ == "__main__":
1765
+ print("Modal ingestion app for Chief Engineer.")
1766
+ print(f" {len(SOURCES)} documentation sources registered")
1767
+ print(f" {len(HF_MAPPERS)} HF dataset mappers registered")
1768
+ print()
1769
+ print("Categories:")
1770
+ for cat in sorted(set(v[1] for v in SOURCES.values())):
1771
+ count = sum(1 for v in SOURCES.values() if v[1] == cat)
1772
+ print(f" {cat}: {count} sources")
1773
+ print()
1774
+ print("Run:")
1775
+ print(" modal run ingest/modal_app.py # all sources")
1776
+ print(" modal run ingest/modal_app.py --source klipper-thermistors")
1777
+ print(" modal run ingest/modal_app.py --category calibration")
1778
+ print(" modal run ingest/modal_app.py --dataset 3d-adam --limit 2000")
ingest/samples/user_creality_petg.config ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ; Provenance: user PrusaSlicer profile from anthurium-bg.3mf (Prusament PETG @CREALITY, 0.6mm).
2
+ ; Committed as SETTINGS ONLY (license-safe config values) — the STL geometry is the user's IP and is NOT committed.
3
+ ; bed_temperature = 70
4
+ ; bridge_fan_speed = 100
5
+ ; filament_settings_id = "Prusament PETG @CREALITY"
6
+ ; filament_type = PETG
7
+ ; first_layer_bed_temperature = 70
8
+ ; first_layer_temperature = 245
9
+ ; max_fan_speed = 50
10
+ ; min_fan_speed = 20
11
+ ; nozzle_diameter = 0.6
12
+ ; print_settings_id = 0.28 mm SUPERDRAFT SPEED (0.6 mm nozzle) @CREALITY
13
+ ; retract_length = 5
14
+ ; temperature = 245
scripts/deploy_preflight.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deploy / record preflight — is the app ready to ship to the Space and record?
2
+
3
+ Distinct from `scripts/preflight.py` (which gates the live *model* on the real
4
+ stack). This one gates *deployment + recording readiness* and runs fully offline:
5
+
6
+ • local build is sound (imports, builds the UI, core tests pass, no errors)
7
+ • every file the Space needs is present + the README frontmatter is valid
8
+ • the prompt won't regress (reference block is lean, ledger is the clean baseline)
9
+ • the credentials/tooling to actually push exist — and if not, says exactly what
10
+ to set and where (this remote session does NOT carry HF_TOKEN by default)
11
+ • (only if a token is present) the live Space exists and what's deployed
12
+
13
+ GO → safe to `hf upload` + reboot + record. Run: make deploy-check
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ ROOT = Path(__file__).resolve().parent.parent
27
+ SPACE = "build-small-hackathon/microfactory-lab"
28
+ _fail: list[str] = []
29
+ _warn: list[str] = []
30
+
31
+
32
+ def ok(gate: str, detail: str = "") -> None:
33
+ print(f"🟢 {gate}{' — ' + detail if detail else ''}")
34
+
35
+
36
+ def warn(gate: str, detail: str) -> None:
37
+ _warn.append(gate)
38
+ print(f"🟡 {gate} — {detail}")
39
+
40
+
41
+ def fail(gate: str, detail: str) -> None:
42
+ _fail.append(gate)
43
+ print(f"🔴 {gate} — {detail}")
44
+
45
+
46
+ # ── D1 · local build is sound ────────────────────────────────────────────────
47
+ def d1_build() -> None:
48
+ try:
49
+ import app # noqa: F401 (also exercises the whole import graph)
50
+ if type(getattr(app, "demo", None)).__name__ != "Blocks":
51
+ fail("D1 build", "app.demo is not a Gradio Blocks — build() did not run")
52
+ return
53
+ ok("D1 build", "app imports + builds the UI (Studio→Build→Print→Review)")
54
+ except Exception as e: # noqa: BLE001
55
+ fail("D1 build", f"import/build error: {e!r}")
56
+
57
+
58
+ def d1b_tests() -> None:
59
+ r = subprocess.run([sys.executable, str(ROOT / "test_core.py")],
60
+ cwd=ROOT, capture_output=True, text=True)
61
+ if r.returncode == 0 and "ALL CORE TESTS PASSED" in (r.stdout + r.stderr):
62
+ ok("D1 tests", "core tests pass (offline)")
63
+ else:
64
+ fail("D1 tests", f"test_core.py failed (rc={r.returncode}); run `make test`")
65
+
66
+
67
+ # ── D2 · everything the Space needs is present ───────────────────────────────
68
+ def d2_files() -> None:
69
+ required = ["app.py", "README.md", "requirements.txt", "core", "ingest", "sim",
70
+ "scripts", "learn", "data/seed_lessons.jsonl", "data/references.jsonl",
71
+ "data/lessons.jsonl"]
72
+ missing = [p for p in required if not (ROOT / p).exists()]
73
+ if missing:
74
+ fail("D2 files", f"missing for the Space: {', '.join(missing)}")
75
+ else:
76
+ ok("D2 files", "all app + data files present")
77
+ if not (ROOT / "assets" / "benchy.glb").exists():
78
+ warn("D2 assets", "assets/benchy.glb missing — the hero quick-load won't render")
79
+
80
+
81
+ # ── D3 · README frontmatter the Space build reads ────────────────────────────
82
+ def d3_frontmatter() -> None:
83
+ txt = (ROOT / "README.md").read_text(encoding="utf-8")
84
+ m = re.match(r"^---\n(.*?)\n---", txt, re.S)
85
+ if not m:
86
+ fail("D3 README", "no YAML frontmatter block")
87
+ return
88
+ fm = m.group(1)
89
+ need = {"sdk": "gradio", "app_file": "app.py"}
90
+ for k, v in need.items():
91
+ if not re.search(rf"^{k}:\s*{re.escape(v)}\s*$", fm, re.M):
92
+ fail("D3 README", f"frontmatter `{k}: {v}` missing/wrong")
93
+ return
94
+ if not re.search(r"^sdk_version:\s*\S+", fm, re.M):
95
+ fail("D3 README", "sdk_version missing")
96
+ return
97
+ sd = re.search(r"^short_description:\s*(.+)$", fm, re.M)
98
+ if not sd:
99
+ warn("D3 README", "no short_description")
100
+ elif len(sd.group(1).strip().strip('"')) > 60:
101
+ fail("D3 README", f"short_description >60 chars ({len(sd.group(1).strip())}) — upload will reject")
102
+ else:
103
+ ok("D3 README", "frontmatter valid (sdk/app_file/sdk_version/short_description)")
104
+
105
+
106
+ # ── D4 · requirements carry the Space (zerogpu) deps ─────────────────────────
107
+ def d4_requirements() -> None:
108
+ req = (ROOT / "requirements.txt").read_text(encoding="utf-8").lower()
109
+ needed = ["gradio", "spaces", "torch", "transformers", "trimesh", "shapely", "pydantic"]
110
+ missing = [p for p in needed if p not in req]
111
+ if missing:
112
+ fail("D4 requirements", f"missing pins: {', '.join(missing)} (Space build/zerogpu needs them)")
113
+ else:
114
+ ok("D4 requirements", "core + zerogpu deps inlined")
115
+
116
+
117
+ # ── D5 · the prompt won't regress (lean reference block) ─────────────────────
118
+ def d5_reference_block() -> None:
119
+ try:
120
+ from ingest.distill import reference_block
121
+ worst = max((len(reference_block(m)) for m in ("PLA", "PETG", "ABS", "TPU")), default=0)
122
+ if worst == 0:
123
+ warn("D5 reference", "reference_block returned nothing — references not loaded?")
124
+ elif worst > 12:
125
+ fail("D5 reference", f"reference block is {worst} lines/material — prompt flood regression")
126
+ else:
127
+ ok("D5 reference", f"lean ({worst} lines/material max)")
128
+ except Exception as e: # noqa: BLE001
129
+ fail("D5 reference", f"reference_block error: {e!r}")
130
+
131
+
132
+ # ── D6 · the deployed ledger is the clean baseline (no demo junk) ────────────
133
+ def d6_ledger() -> None:
134
+ srcs: dict[str, int] = {}
135
+ for line in (ROOT / "data" / "lessons.jsonl").read_text(encoding="utf-8").splitlines():
136
+ if line.strip():
137
+ try:
138
+ srcs[json.loads(line).get("source", "?")] = srcs.get(json.loads(line).get("source", "?"), 0) + 1
139
+ except Exception:
140
+ continue
141
+ runtime = srcs.get("earned", 0) + srcs.get("sim", 0)
142
+ summary = ", ".join(f"{k}:{v}" for k, v in sorted(srcs.items()))
143
+ if runtime:
144
+ warn("D6 ledger", f"{runtime} runtime lesson(s) in the ledger ({summary}) — "
145
+ "reset before upload: git checkout -- data/lessons.jsonl")
146
+ else:
147
+ ok("D6 ledger", f"clean baseline ({summary})")
148
+
149
+
150
+ # ── D7 · data integrity (valid JSONL, enums) ─────────────────────────────────
151
+ def d7_data() -> None:
152
+ try:
153
+ from core.models import MATERIALS, OUTCOMES
154
+ bad = 0
155
+ for line in (ROOT / "data" / "references.jsonl").read_text(encoding="utf-8").splitlines():
156
+ if line.strip():
157
+ r = json.loads(line)
158
+ if not {"material", "param", "value", "source"} <= set(r):
159
+ bad += 1
160
+ obs = ROOT / "sim" / "calibration" / "observations.modal.jsonl"
161
+ obad = sum(1 for l in obs.read_text().splitlines()
162
+ if l.strip() and json.loads(l).get("outcome") not in OUTCOMES) if obs.exists() else 0
163
+ if bad or obad:
164
+ warn("D7 data", f"{bad} malformed ref rows, {obad} bad-outcome obs rows")
165
+ else:
166
+ ok("D7 data", "references + calibration obs well-formed")
167
+ except Exception as e: # noqa: BLE001
168
+ warn("D7 data", f"could not validate: {e!r}")
169
+
170
+
171
+ # ── D8 · credentials + tooling to actually deploy ────────────────────────────
172
+ def d8_credentials() -> None:
173
+ has_hf_cli = shutil.which("hf") is not None
174
+ token = (os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
175
+ or os.environ.get("HUGGINGFACE_TOKEN"))
176
+ whoami = None
177
+ if has_hf_cli:
178
+ r = subprocess.run(["hf", "auth", "whoami"], capture_output=True, text=True)
179
+ if r.returncode == 0 and "Not logged in" not in r.stdout:
180
+ whoami = r.stdout.strip().splitlines()[0] if r.stdout.strip() else "ok"
181
+ if not has_hf_cli:
182
+ fail("D8 hf-cli", "`hf` not installed — `uv pip install -U huggingface_hub`")
183
+ if token or whoami:
184
+ ok("D8 hf-auth", f"authenticated ({'token env' if token else 'hf login: ' + str(whoami)})")
185
+ else:
186
+ warn("D8 hf-auth", "NO HF credentials in this session. To deploy: run the `hf upload` "
187
+ "from a machine where you've run `hf auth login`, OR set HF_TOKEN "
188
+ "in the environment (HF write token, member of build-small-hackathon).")
189
+ return bool(token or whoami)
190
+
191
+
192
+ # ── D9 · (token only) what's live on the Space right now ─────────────────────
193
+ def d9_space(authed: bool) -> None:
194
+ if not authed:
195
+ warn("D9 space", "skipped — no credentials to query the live Space")
196
+ return
197
+ try:
198
+ from huggingface_hub import HfApi
199
+ api = HfApi()
200
+ rt = api.get_space_runtime(SPACE)
201
+ files = api.list_repo_files(SPACE, repo_type="space")
202
+ has_core = "app.py" in files and any(f.startswith("core/") for f in files)
203
+ stage = getattr(rt, "stage", "?")
204
+ ok("D9 space", f"reachable · stage={stage} · app.py+core present={has_core} · {len(files)} files")
205
+ if not has_core:
206
+ warn("D9 space", "Space is missing app.py/core — likely the pre-restructure build; push the update")
207
+ except Exception as e: # noqa: BLE001
208
+ warn("D9 space", f"could not query Space: {e!r}")
209
+
210
+
211
+ def main() -> None:
212
+ print("Deploy / record preflight — " + SPACE)
213
+ print("=" * 70)
214
+ d1_build()
215
+ d1b_tests()
216
+ d2_files()
217
+ d3_frontmatter()
218
+ d4_requirements()
219
+ d5_reference_block()
220
+ d6_ledger()
221
+ d7_data()
222
+ authed = d8_credentials()
223
+ d9_space(authed)
224
+ print("=" * 70)
225
+ if _fail:
226
+ print(f"🔴 NO-GO: fix {len(_fail)} blocker(s) — {', '.join(_fail)}")
227
+ sys.exit(1)
228
+ if _warn:
229
+ print(f"🟡 GO with warnings ({', '.join(_warn)}) — read them; credentials/Space "
230
+ "warnings just mean 'deploy from an authenticated machine'.")
231
+ sys.exit(0)
232
+ print("🟢 GO — local build clean, files + frontmatter ready, authenticated. "
233
+ "hf upload → --factory-reboot → smoke-test → record.")
234
+
235
+
236
+ if __name__ == "__main__":
237
+ main()
sim/calibration/CALIBRATION-REPORT.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Calibration report — simulator vs. real observations
2
+
3
+ **Date:** 2026-06-12 · **Harness:** `uv run python -m sim.calibrate --data <obs>` ·
4
+ **Model under test:** `sim/outcome.py` (BANDS + penalty constants).
5
+
6
+ ## Result: data cleaned, structural bottleneck identified
7
+
8
+ | Dataset | n | Outcome accuracy | Quality MAE | fan=0 rows |
9
+ |---|---|---|---|---|
10
+ | `observations.sample.jsonl` (hand-crafted) | 12 | 66.7% | 0.228 | 2 |
11
+ | `observations.modal.jsonl` (FDM error detection, cleaned) | 178 | **32.6%** | 0.227 | **0** |
12
+
13
+ Confusion on the 178-row cleaned FDM set:
14
+
15
+ ```
16
+ ✗ failed_sag → success ×61
17
+ ✗ failed_stringing → success ×59
18
+ ✓ success → success ×58
19
+ ```
20
+
21
+ ### Phase 2 fixes applied (per RESEARCH-NEEDS.md)
22
+ - ✅ **M106 parsed across full file + slicer footer** — fan=0 rows: 178→0
23
+ - ✅ **M109/M190 final temps** — nozzle temps now 210/215/220 (was preheat 150)
24
+ - ✅ **Retraction from G1 E- moves + PrusaSlicer footer** — real values 1-8.5mm
25
+ - ✅ **Rows with undetermined fan skipped** — no more fan=0 defaults
26
+
27
+ ### What the clean data reveals
28
+
29
+ The simulator correctly identifies all 58 success cases but misses all 120 failures.
30
+ This is NOT a constant-tuning problem — it's a **structural sensitivity gap**:
31
+
32
+ 1. **Sag (61 misses):** At fan=67%, the sag formula produces penalty=0 because
33
+ `need=60` for overhang. Raising `need` to 75 produces sag=0.056, but the
34
+ quality threshold (0.7) requires total penalty >0.3 to flip outcome. The
35
+ penalty formulas are too weak for moderate conditions.
36
+
37
+ 2. **Stringing (59 misses):** At humidity=45%, nozzle=210°C (in-band),
38
+ retraction=3mm, the stringing formula produces 0. A base penalty for
39
+ stringing geometry would need to be >0.5 to overcome the 0.7 threshold —
40
+ implausibly strong. The formula needs additional features (travel speed,
41
+ filament moisture, part complexity).
42
+
43
+ ### Decision: no constant changes
44
+
45
+ The 0.7 quality threshold + weak penalty scaling make the simulator insensitive
46
+ to moderate failure conditions. This is a **structural design choice** — the
47
+ simulator was calibrated for the sample data's more extreme conditions. Fixing
48
+ it requires either:
49
+ - Lowering the quality threshold (affects all failure modes — risky)
50
+ - Adding features to penalty formulas (travel speed, extrusion multiplier,
51
+ filament moisture)
52
+ - Per-geometry quality thresholds
53
+
54
+ **Path forward:** Add `extrusion_multiplier` and `travel_speed` to the Lane C
55
+ schema and the simulator inputs. These are the missing features that distinguish
56
+ success from failure in the FDM data.
57
+
58
+ ## What we learned from the bad data (the interesting part)
59
+ - **Quantity ≠ quality.** The ingestion produced 1,304 reference facts, but the
60
+ *correct, prompt-useful* material baselines all came from 4 tiny curated config
61
+ files (Prusa/Klipper/Marlin) — not the 825 MB dataset. `reference_block` now prefers
62
+ those curated sources and drops the bulk model-metadata.
63
+ - **One unparsed field silently flipped 112 predictions.** `fan→0` looked like real
64
+ data and would have corrupted the simulator had we tuned to it blind. The harness
65
+ caught it — calibration is also a *data*-quality check, not just a model check.
66
+ - **Honest-by-design, demonstrated.** We did not manufacture a "67%→92%" win. We
67
+ measured 34.2%, found the dataset wasn't trustworthy, and said so. That is the same
68
+ integrity rule the whole project rests on, applied to our own results.
69
+
70
+ ## Reproduce
71
+ ```bash
72
+ uv run python -m sim.calibrate --data sim/calibration/observations.modal.jsonl
73
+ # machine-readable metrics: sim/calibration/results/baseline.modal.json
74
+ ```
sim/calibration/README.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Calibration data — Chief Engineer outcome simulator
2
+
3
+ Observations used to calibrate `sim/outcome.py` (the one simulated boundary — see
4
+ `../../SIMULATION.md`). Each row is a real(ish) print: the **settings used + room +
5
+ the real outcome** (+ optional 0–1 `quality`). The `tune-simulator` skill scores the
6
+ simulator against these. **Packaged so it can be published as a Hub dataset later
7
+ (Sharing is Caring).**
8
+
9
+ ## Files
10
+ | File | Rows | What |
11
+ |---|---|---|
12
+ | `observations.sample.jsonl` | 12 | Hand-crafted template, mixed outcomes — the schema reference. |
13
+ | `observations.modal.jsonl` | 260 | Ingested on Modal: 82 from **3DTime** (G-code headers) + 178 from **FDM Error Detection** (known-failure logs). |
14
+ | `results/baseline.*.json` | — | Machine-readable metrics (accuracy, MAE, confusion, fan=0 count) per dataset. |
15
+ | `results/report.*.txt` | — | Human-readable harness output (confusion + per-row mismatches). |
16
+ | `CALIBRATION-REPORT.md` | — | The analysis + the decision (and why we did **not** tune to this data). |
17
+
18
+ ## Schema (one JSON object per line)
19
+ ```json
20
+ {"material":"PLA","geometry_type":"overhang","env_temp":22.0,"env_humidity":45.0,
21
+ "nozzle_temp":210.0,"bed_temp":60.0,"retraction_mm":3.0,"fan_pct":0,
22
+ "first_layer_fan_pct":0,"outcome":"failed_sag","quality":0.7}
23
+ ```
24
+ Enums (`material`/`geometry_type`/`outcome`) match `core/models.py`.
25
+
26
+ ## Provenance & licenses
27
+ - **3DTime** (`3DTimeDataset/3DTime`) — published Printables models; outcomes are all
28
+ `success` (they printed). Settings parsed from G-code headers.
29
+ - **FDM Error Detection** (`NilsHagenBeyer/3D-printing_recorder`) — G-code + YAML with
30
+ labelled failures (good / stringing / under-extrusion). The source of the real failures.
31
+
32
+ ## ⚠ Known data-quality caveats (read before trusting a calibration)
33
+ - **`fan_pct` defaults to 0** when `M106` isn't in the G-code header (178/260 rows).
34
+ This makes overhangs look fan-off and the simulator (correctly) predict sag → false
35
+ mismatches. **Do not tune sag to these rows.**
36
+ - **Geometry is a bbox heuristic** for 3DTime rows (no real geometry label), so many
37
+ ordinary prints are tagged `overhang`.
38
+ - **3DTime outcomes are uniformly `success`** — no failure signal; good for Lane-A
39
+ references, weak for outcome calibration.
40
+ See `CALIBRATION-REPORT.md` and `../../docs/RESEARCH-NEEDS.md` for the fixes that make
41
+ this set tunable.
sim/calibration/observations.modal.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
sim/calibration/results/baseline.modal.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "observations.modal.jsonl",
3
+ "generated": "2026-06-12",
4
+ "n_observations": 260,
5
+ "outcome_accuracy": 0.3423,
6
+ "quality_mae": 0.3205,
7
+ "confusion": {
8
+ "success->failed_sag": 112,
9
+ "success->success": 28,
10
+ "failed_stringing->success": 59,
11
+ "failed_sag->failed_sag": 61
12
+ },
13
+ "outcome_counts": {
14
+ "success": 140,
15
+ "failed_stringing": 59,
16
+ "failed_sag": 61
17
+ },
18
+ "geometry_counts": {
19
+ "overhang": 149,
20
+ "bridge": 12,
21
+ "vase": 9,
22
+ "adhesion": 31,
23
+ "stringing": 59
24
+ },
25
+ "fan0_rows": 178
26
+ }
sim/calibration/results/baseline.sample.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "observations.sample.jsonl",
3
+ "generated": "2026-06-12",
4
+ "n_observations": 12,
5
+ "outcome_accuracy": 0.6667,
6
+ "quality_mae": 0.2284,
7
+ "confusion": {
8
+ "success->success": 6,
9
+ "failed_sag->failed_sag": 2,
10
+ "failed_stringing->success": 2,
11
+ "failed_sag->success": 2
12
+ },
13
+ "outcome_counts": {
14
+ "success": 6,
15
+ "failed_sag": 4,
16
+ "failed_stringing": 2
17
+ },
18
+ "geometry_counts": {
19
+ "overhang": 3,
20
+ "bridge": 2,
21
+ "stringing": 4,
22
+ "adhesion": 2,
23
+ "vase": 1
24
+ },
25
+ "fan0_rows": 2
26
+ }
sim/calibration/results/report.modal.txt ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ observations: 260
2
+ outcome accuracy: 34.2% (89/260)
3
+ quality MAE: 0.321 (over 260 graded rows)
4
+ confusion (expected → predicted):
5
+ ✗ success → failed_sag ×112
6
+ ✓ failed_sag → failed_sag ×61
7
+ ✗ failed_stringing → success ×59
8
+ ✓ success → success ×28
9
+ mismatches (diagnose which constant to move):
10
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
11
+ · PETG/bridge @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.09})
12
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
13
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
14
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
15
+ · PETG/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
16
+ · PETG/adhesion @ 22°C/45% fan=51 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
17
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
18
+ · PETG/overhang @ 22°C/45% fan=51 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.11})
19
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
20
+ · ABS/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6, 'warp': 0.22})
21
+ · PETG/bridge @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.09})
22
+ · ABS/overhang @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'warp': 0.22})
23
+ · PETG/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
24
+ · ABS/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
25
+ · PETG/bridge @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.34})
26
+ · PETG/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
27
+ · PETG/vase @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.12})
28
+ · ABS/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
29
+ · PETG/vase @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.12})
30
+ · ABS/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6, 'warp': 0.22})
31
+ · PETG/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
32
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
33
+ · ABS/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
34
+ · ABS/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
35
+ · PETG/overhang @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5})
36
+ · PETG/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
37
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
38
+ · PETG/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
39
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
40
+ · PETG/adhesion @ 22°C/45% fan=51 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
41
+ · ABS/overhang @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'warp': 0.22})
42
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
43
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
44
+ · ABS/overhang @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'warp': 0.22})
45
+ · ABS/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6, 'warp': 0.22})
46
+ · PETG/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
47
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
48
+ · PETG/vase @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.12})
49
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
50
+ · PETG/vase @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.12})
51
+ · PETG/vase @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5})
52
+ · PETG/bridge @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.09})
53
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
54
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
55
+ · PETG/overhang @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5})
56
+ · ABS/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
57
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
58
+ · ABS/adhesion @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6})
59
+ · ABS/bridge @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.09, 'warp': 0.22})
60
+ · ABS/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: adhesion; penalties={'under_extrusion': 0.5, 'adhesion': 0.6, 'warp': 0.22})
61
+ · PETG/adhesion @ 22°C/45% fan=76 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'adhesion': 0.2})
62
+ · ABS/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
63
+ · PETG/overhang @ 22°C/45% fan=40 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: under_extrusion; penalties={'under_extrusion': 0.5, 'sag': 0.19})
64
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
65
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=1.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
66
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=8.5: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
67
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
68
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=1.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
69
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
70
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
71
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
72
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
73
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
74
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
75
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
76
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
77
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
78
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
79
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
80
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=6.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
81
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
82
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
83
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
84
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
85
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
86
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
87
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
88
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
89
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
90
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
91
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
92
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
93
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
94
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
95
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
96
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
97
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
98
+ · PLA/stringing @ 22°C/45% fan=0 noz=220 ret=2.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
99
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
100
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
101
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
102
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
103
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
104
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
105
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
106
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
107
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
108
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
109
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
110
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
111
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
112
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
113
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
114
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
115
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
116
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
117
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
118
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
119
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
120
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
121
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
122
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
123
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
124
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=8.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
125
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
126
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
127
+ · PLA/overhang @ 22°C/45% fan=0 noz=215 ret=8.5: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
128
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
129
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
130
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
131
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
132
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
133
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
134
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
135
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
136
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
137
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
138
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
139
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
140
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
141
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
142
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
143
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
144
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
145
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
146
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
147
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
148
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
149
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
150
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
151
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
152
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
153
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
154
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=0.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.18})
155
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
156
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
157
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
158
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
159
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
160
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
161
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
162
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
163
+ · PLA/overhang @ 22°C/45% fan=0 noz=210 ret=5.0: predicted failed_sag, real success (dominant sim cost: sag; penalties={'sag': 0.47})
164
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
165
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
166
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
167
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
168
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
169
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
170
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
171
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
172
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
173
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=3.0: predicted success, real failed_stringing (dominant sim cost: none; penalties={})
174
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
175
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
176
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
177
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
178
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
179
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
180
+ · PLA/stringing @ 22°C/45% fan=0 noz=210 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.09})
sim/calibration/results/report.sample.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ observations: 12
2
+ outcome accuracy: 66.7% (8/12)
3
+ quality MAE: 0.228 (over 12 graded rows)
4
+ confusion (expected → predicted):
5
+ ✓ success → success ×6
6
+ ✓ failed_sag → failed_sag ×2
7
+ ✗ failed_stringing → success ×2
8
+ ✗ failed_sag → success ×2
9
+ mismatches (diagnose which constant to move):
10
+ · PETG/stringing @ 26°C/65% fan=40 noz=250 ret=2.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.1})
11
+ · ABS/adhesion @ 20°C/40% fan=0 noz=248 ret=4.0: predicted success, real failed_sag (dominant sim cost: adhesion; penalties={'adhesion': 0.2})
12
+ · ABS/overhang @ 25°C/42% fan=80 noz=248 ret=4.0: predicted success, real failed_sag (dominant sim cost: warp; penalties={'warp': 0.24})
13
+ · TPU/stringing @ 23°C/55% fan=40 noz=228 ret=1.0: predicted success, real failed_stringing (dominant sim cost: stringing; penalties={'stringing': 0.14})