Download modules/cnc_websim/cnc_source.py from ASown/agent-iot: direct link, hf CLI and curl.
- Browser
- Download file 3.98 kB
-
https://huggingface.co/spaces/ASown/agent-iot/resolve/main/modules/cnc_websim/cnc_source.py
- Command line
-
hf download hf://spaces/ASown/agent-iot/modules/cnc_websim/cnc_source.py
-
curl -L -o cnc_source.py https://huggingface.co/spaces/ASown/agent-iot/resolve/main/modules/cnc_websim/cnc_source.py
3.98 kB
| from __future__ import annotations | |
| import re | |
| import ssl | |
| import urllib.parse | |
| import urllib.request | |
| from pathlib import Path | |
| from typing import Optional | |
| from cnc_image_to_print import image_to_print, IMAGES_DIR | |
| from cnc_slicer import slice_stl, find_slicer | |
| CACHE_DIR = IMAGES_DIR / "cache" | |
| IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".webp") | |
| ALL_EXT = IMG_EXT + (".stl", ".gcode") | |
| _SSL = ssl.create_default_context() | |
| def _ext_of(path_or_url: str) -> str: | |
| base = path_or_url.split("?")[0].split("#")[0].lower() | |
| for e in ALL_EXT: | |
| if base.endswith(e): | |
| return e | |
| return "" | |
| # Named aliases: a phrase -> a specific saved model. Checked with highest | |
| # priority (before LLM routing), so "quà cho anh Eric" always prints this model. | |
| ALIASES: list[dict] = [ | |
| { | |
| "keys": ("quà cho anh eric", "qua cho anh eric", "gift for eric", | |
| "anh eric", "eric"), | |
| "path": str(IMAGES_DIR / "eric-gift.jpg"), | |
| "color": 0xAA5858, | |
| "label": "eric-gift", | |
| }, | |
| ] | |
| def resolve_alias(request: str) -> Optional[dict]: | |
| """Return the alias entry whose keyword appears in the request, else None.""" | |
| low = request.lower() | |
| for a in ALIASES: | |
| if any(k in low for k in a["keys"]) and Path(a["path"]).exists(): | |
| return a | |
| return None | |
| def looks_like_source(arg: str) -> bool: | |
| """True if the argument is a local file path or URL to an image/STL/gcode.""" | |
| a = arg.strip().strip('"').strip("'") | |
| ext = _ext_of(a) | |
| if not ext: | |
| return False | |
| if a.lower().startswith(("http://", "https://")): | |
| return True | |
| return Path(a).exists() | |
| def _download(url: str, dest: Path, max_bytes: int = 40_000_000) -> Path: | |
| req = urllib.request.Request(url, headers={"User-Agent": "cnc-demo/1.0 (educational)"}) | |
| with urllib.request.urlopen(req, timeout=60, context=_SSL) as r: | |
| data = r.read(max_bytes) | |
| dest.write_bytes(data) | |
| return dest | |
| def _slug(name: str) -> str: | |
| return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_") or "source" | |
| def job_from_source(arg: str, *, color_hex: int = 0xE0762B) -> dict: | |
| """ | |
| Turn a user-supplied image/STL/gcode (local path OR URL) into a print job. | |
| URLs are downloaded first. Images are traced+extruded; STLs are sliced; | |
| gcode is loaded as-is. No content filtering — it prints what you give it. | |
| """ | |
| a = arg.strip().strip('"').strip("'") | |
| ext = _ext_of(a) | |
| if not ext: | |
| raise ValueError(f"Not an image/STL/gcode source: {arg}") | |
| CACHE_DIR.mkdir(parents=True, exist_ok=True) | |
| if a.lower().startswith(("http://", "https://")): | |
| stem = _slug(Path(urllib.parse.urlparse(a).path).stem) or "src" | |
| path = _download(a, CACHE_DIR / f"src_{stem}{ext}") | |
| origin = f"url:{a[:60]}" | |
| else: | |
| path = Path(a) | |
| origin = f"file:{a}" | |
| label = _slug(path.stem) | |
| if ext in IMG_EXT: | |
| job = image_to_print(str(path), name=label, color_hex=color_hex) | |
| job["source"] = origin | |
| return job | |
| if ext == ".stl": | |
| if find_slicer()["kind"] is None: | |
| raise RuntimeError("STL needs a slicer. Install: winget install Prusa3D.PrusaSlicer") | |
| gpath = slice_stl(str(path)) | |
| gcode = Path(gpath).read_text(encoding="utf-8", errors="replace") | |
| return {"name": label, "gcode": gcode, "color": color_hex, | |
| "prefix": f"src_{label}", "note": "Sliced from STL.", "source": origin} | |
| gcode = path.read_text(encoding="utf-8", errors="replace") # .gcode | |
| return {"name": label, "gcode": gcode, "color": color_hex, | |
| "prefix": f"src_{label}", "note": "Loaded G-code file.", "source": origin} | |
| if __name__ == "__main__": | |
| import sys | |
| arg = " ".join(sys.argv[1:]) | |
| print("looks_like_source:", looks_like_source(arg)) | |
| if looks_like_source(arg): | |
| r = job_from_source(arg) | |
| print(f"OK: {r['name']} | {r.get('points','?')} pts | {r['note']} | {r['source']}") | |