├── addon ├── __init__.py ├── rootfs │ ├── app │ │ ├── __init__.py │ │ ├── lib │ │ │ ├── __init__.py │ │ │ ├── meta.py │ │ │ ├── detection_model.py │ │ │ ├── geometry.py │ │ │ ├── onnx.py │ │ │ └── darknet.py │ │ ├── model │ │ │ ├── names │ │ │ ├── model.meta │ │ │ ├── model-weights.onnx.url │ │ │ ├── model-weights.darknet.url │ │ │ └── model.cfg │ │ ├── requirements.txt │ │ ├── wsgi.py │ │ ├── auth.py │ │ └── server.py │ └── etc │ │ └── services.d │ │ └── ha-bambulab-spaghetti-detection │ │ └── run ├── .gitignore ├── .dockerignore ├── .gitattributes ├── Dockerfile ├── run.sh ├── config.yaml ├── Dockerfile.standalone.base ├── Dockerfile.ha.base └── detect.py ├── FUNDING.yml ├── custom_components ├── __init__.py └── bambu_lab_p1_spaghetti_detection │ ├── manifest.json │ ├── config_flow.py │ ├── translations │ └── en.json │ ├── services.yaml │ ├── datetime.py │ ├── __init__.py │ └── number.py ├── hacs.json ├── docs └── images │ └── blueprint_installation.png ├── repository.json ├── .github └── workflows │ ├── hassfest.yaml │ └── validate.yaml ├── CONTRIBUTING.md ├── docker-compose.yaml ├── release_notes.md ├── .gitignore ├── README.md ├── blueprints └── spaghetti_detection.yaml └── LICENSE /addon/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /addon/rootfs/app/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: nberk 2 | -------------------------------------------------------------------------------- /addon/rootfs/app/lib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /custom_components/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /addon/rootfs/app/model/names: -------------------------------------------------------------------------------- 1 | failure 2 | -------------------------------------------------------------------------------- /addon/.gitignore: -------------------------------------------------------------------------------- 1 | model/*.onnx 2 | model/*.darknet 3 | -------------------------------------------------------------------------------- /addon/.dockerignore: -------------------------------------------------------------------------------- 1 | model/*.onnx 2 | model/*.darknet 3 | 4 | -------------------------------------------------------------------------------- /addon/.gitattributes: -------------------------------------------------------------------------------- 1 | *.weights filter=lfs diff=lfs merge=lfs -text 2 | -------------------------------------------------------------------------------- /addon/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nberk/ha-bambu-lab-p1-spaghetti-detection-addon:latest -------------------------------------------------------------------------------- /addon/rootfs/app/model/model.meta: -------------------------------------------------------------------------------- 1 | classes= 1 2 | names = /app/model/names 3 | -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Bambu Lab P1 - Spaghetti Detection", 3 | "render_readme": true 4 | } 5 | -------------------------------------------------------------------------------- /addon/rootfs/app/model/model-weights.onnx.url: -------------------------------------------------------------------------------- 1 | https://tsd-pub-static.s3.amazonaws.com/ml-models/model-weights-5a6b1be1fa.onnx 2 | -------------------------------------------------------------------------------- /addon/rootfs/app/model/model-weights.darknet.url: -------------------------------------------------------------------------------- 1 | https://tsd-pub-static.s3.amazonaws.com/ml-models/model-weights-8be06cde4e.darknet 2 | -------------------------------------------------------------------------------- /addon/rootfs/app/requirements.txt: -------------------------------------------------------------------------------- 1 | ipdb 2 | flask>=1.0 3 | redis==3.0.1 4 | newrelic==4.12.0.113 5 | requests==2.21.0 6 | gunicorn==19.9.0 -------------------------------------------------------------------------------- /addon/rootfs/app/wsgi.py: -------------------------------------------------------------------------------- 1 | import server 2 | 3 | application = server.app 4 | 5 | if __name__ == "__main__": 6 | application.run() 7 | -------------------------------------------------------------------------------- /docs/images/blueprint_installation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection/HEAD/docs/images/blueprint_installation.png -------------------------------------------------------------------------------- /addon/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bashio 2 | set -e 3 | 4 | ML_API_TOKEN=$(bashio::config 'obico_api_secret') 5 | PORT=$(bashio::addon.port 3333) 6 | 7 | venv/bin/gunicorn --bind "0.0.0.0:$PORT" --workers 1 wsgi 8 | -------------------------------------------------------------------------------- /repository.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Bambu Lab P1 - Spaghetti Detection", 3 | "url": "https://github.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection", 4 | "maintainer": "nberktumer " 5 | } -------------------------------------------------------------------------------- /addon/rootfs/etc/services.d/ha-bambulab-spaghetti-detection/run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv bashio 2 | 3 | declare ML_API_TOKEN 4 | declare PORT 5 | 6 | ML_API_TOKEN=$(bashio::config 'obico_api_secret') 7 | 8 | cd /app 9 | FLASK_APP=server.py venv/bin/gunicorn --bind "0.0.0.0:3333" --workers 1 wsgi:application 10 | -------------------------------------------------------------------------------- /.github/workflows/hassfest.yaml: -------------------------------------------------------------------------------- 1 | name: Validate with hassfest 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * *" 8 | 9 | jobs: 10 | validate: 11 | runs-on: "ubuntu-latest" 12 | steps: 13 | - uses: "actions/checkout@v3" 14 | - uses: home-assistant/actions/hassfest@master 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ### Contribution 2 | Excited to contribute to **ha-bambu-lab-p1-spaghetti-detection**? Fantastic! Here's what you need to know: 3 | 4 | - Please make contributions to the `develop` branch, as the `main` branch is reserved for stable, released code. 5 | - Clearly name your commits and provide contextual information about the changes you've made. 6 | -------------------------------------------------------------------------------- /addon/config.yaml: -------------------------------------------------------------------------------- 1 | name: "Bambu Lab P1 - Spaghetti Detection Server" 2 | description: "Obico ML server for detection spaghetti" 3 | version: "1.0.0" 4 | slug: "ha_bambu_lab_p1_spaghetti_detection_addon" 5 | init: false 6 | arch: 7 | - amd64 8 | startup: services 9 | ports: 10 | 3333/tcp: 3333 11 | options: 12 | obico_api_secret: "obico_api_secret" 13 | schema: 14 | obico_api_secret: str -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | version: "3" 3 | services: 4 | ha_bambu_lab_p1_spaghetti_detection: 5 | image: nberk/ha_bambu_lab_p1_spaghetti_detection_standalone:latest 6 | container_name: ha_bambu_lab_p1_spaghetti_detection 7 | restart: unless-stopped 8 | ports: 9 | - 3333:3333/tcp 10 | environment: 11 | - ML_API_TOKEN=obico_api_secret 12 | - TZ=Europe/London 13 | -------------------------------------------------------------------------------- /.github/workflows/validate.yaml: -------------------------------------------------------------------------------- 1 | name: Validate 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * *" 8 | workflow_dispatch: 9 | 10 | jobs: 11 | validate-hacs: 12 | runs-on: "ubuntu-latest" 13 | steps: 14 | - uses: "actions/checkout@v3" 15 | - name: HACS validation 16 | uses: "hacs/action@main" 17 | with: 18 | category: "integration" 19 | -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "bambu_lab_p1_spaghetti_detection", 3 | "name": "Bambu Lab P1 - Spaghetti Detection", 4 | "codeowners": [ 5 | "@nberktumer" 6 | ], 7 | "config_flow": true, 8 | "dependencies": [], 9 | "documentation": "https://github.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection", 10 | "iot_class": "calculated", 11 | "issue_tracker": "https://github.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection/issues", 12 | "version": "1.0.0" 13 | } 14 | 15 | -------------------------------------------------------------------------------- /release_notes.md: -------------------------------------------------------------------------------- 1 | ### V1.1.0 2 | 3 | > ### Breaking Change 4 | > Image entity of ha-bambulab no longer works due to a change in official Bambu Lab APIs. Make sure to update [ha-bambulab](https://github.com/greghesp/ha-bambulab) integration to v2.0.23 or higher version. 5 | 6 | - Spaghetti Detection automation is now compatible with all Bambu Lab printers supported by ha-bambulab integration! 7 | - X1 Series 8 | - P1 Series 9 | - A1 Series 10 | - Third party cameras can also be used for detecting failures now! 11 | 12 | ### V1.0.0 13 | - Initial release -------------------------------------------------------------------------------- /addon/rootfs/app/auth.py: -------------------------------------------------------------------------------- 1 | import os 2 | from functools import wraps 3 | from flask import Flask, request, Response 4 | 5 | ML_API_TOKEN=os.environ.get("ML_API_TOKEN") 6 | 7 | def token_required(f): 8 | @wraps(f) 9 | def check_authorization(*args, **kwargs): 10 | if request.headers.get("Authorization") == 'Bearer {}'.format(ML_API_TOKEN): 11 | return f() 12 | else: 13 | return Response(status=401) 14 | 15 | @wraps(f) 16 | def passthru(*args, **kwargs): 17 | return f() 18 | 19 | if ML_API_TOKEN: 20 | return check_authorization 21 | else: 22 | return passthru 23 | -------------------------------------------------------------------------------- /addon/Dockerfile.standalone.base: -------------------------------------------------------------------------------- 1 | FROM thespaghettidetective/ml_api_base:1.3 2 | WORKDIR /app 3 | EXPOSE 3333 4 | 5 | ADD rootfs/app /app 6 | RUN pip install --upgrade pip 7 | RUN pip install -r requirements.txt 8 | 9 | RUN echo 'Downloading the latest failure detection AI model in Darknet format...' 10 | RUN wget -O model/model-weights.darknet $(cat model/model-weights.darknet.url | tr -d '\r') 11 | RUN echo 'Downloading the latest failure detection AI model in ONNX format...' 12 | RUN wget -O model/model-weights.onnx $(cat model/model-weights.onnx.url | tr -d '\r') 13 | 14 | ENV FLASK_APP server.py 15 | 16 | CMD gunicorn --bind "0.0.0.0:3333" --workers 1 wsgi -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/config_flow.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from typing import Any 5 | 6 | from homeassistant import config_entries 7 | from homeassistant.data_entry_flow import FlowResult 8 | 9 | from custom_components.bambu_lab_p1_spaghetti_detection import DOMAIN 10 | 11 | _LOGGER = logging.getLogger(__name__) 12 | 13 | 14 | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): 15 | VERSION = 1 16 | 17 | async def async_step_user( 18 | self, user_input: dict[str, Any] | None = None 19 | ) -> FlowResult: 20 | return self.async_create_entry(title="Bambu Lab P1 - Spaghetti Detection", data={}) 21 | -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "services": { 3 | "predict": { 4 | "name": "Predict Spaghetti", 5 | "description": "Runs the Obico ML model whether the given image has spaghetti", 6 | "fields": { 7 | "obico_host": { 8 | "name": "Obico ML API Host", 9 | "description": "Obico ML API host" 10 | }, 11 | "obico_auth_token": { 12 | "name": "Obico ML API Auth Token", 13 | "description": "Obico ML API authentication token" 14 | }, 15 | "image_url": { 16 | "name": "Image URL", 17 | "description": "Image URL" 18 | } 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/services.yaml: -------------------------------------------------------------------------------- 1 | predict: 2 | name: "Predict spaghetti" 3 | description: "Runs the Obico ML model whether the given image has spaghetti" 4 | fields: 5 | obico_host: 6 | description: "Obico ML Server URL." 7 | example: "http://192.168.1.123:3333" 8 | required: true 9 | selector: 10 | text: 11 | obico_auth_token: 12 | description: "Obico ML Server authentication token." 13 | example: "obico_api_secret" 14 | required: true 15 | selector: 16 | text: 17 | image_url: 18 | description: "URL of the image for spaghetti detection." 19 | example: "https://your-image-url.jpg" 20 | required: true 21 | selector: 22 | text: -------------------------------------------------------------------------------- /addon/rootfs/app/lib/meta.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple 2 | from dataclasses import dataclass, field 3 | import os 4 | import re 5 | 6 | @dataclass 7 | class Meta: 8 | names: List[str] = field(default_factory=list) 9 | 10 | def __init__(self, meta_path: str): 11 | names = None 12 | with open(meta_path) as f: 13 | meta_contents = f.read() 14 | match = re.search("names *= *(.*)$", meta_contents, re.IGNORECASE | re.MULTILINE) 15 | if match: 16 | names_path = match.group(1) 17 | try: 18 | if os.path.exists(names_path): 19 | with open(names_path) as namesFH: 20 | names_list = namesFH.read().strip().split("\n") 21 | names = [x.strip() for x in names_list] 22 | except TypeError: 23 | pass 24 | if names is None: 25 | names = ['failure'] 26 | 27 | self.names = names 28 | -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/datetime.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timezone 2 | 3 | from homeassistant.components.datetime import DateTimeEntity, DateTimeEntityDescription 4 | 5 | DATETIME_TYPES: tuple[DateTimeEntityDescription, ...] = ( 6 | DateTimeEntityDescription( 7 | key="last_notify_time", 8 | name="Spaghetti Detection - Last Notify Time" 9 | ), 10 | ) 11 | 12 | 13 | async def async_setup_entry(hass, entry, async_add_entities): 14 | entities = [ 15 | BambuLabP1SpaghettiDetectionDateTimeEntity(entity_description) for entity_description in DATETIME_TYPES 16 | ] 17 | 18 | async_add_entities(entities) 19 | 20 | 21 | class BambuLabP1SpaghettiDetectionDateTimeEntity(DateTimeEntity): 22 | def __init__(self, entity_description): 23 | self.entity_description = entity_description 24 | 25 | self.entity_id = "number.bambu_lab_p1_spaghetti_detection_%s" % entity_description.key 26 | self._attr_unique_id = "number.bambu_lab_p1_spaghetti_detection_%s" % entity_description.key 27 | self._attr_native_value = datetime.fromtimestamp(0, timezone.utc) 28 | 29 | async def async_set_value(self, value: datetime) -> None: 30 | """Set the value of the number entity.""" 31 | self._attr_native_value = value 32 | self.async_write_ha_state() 33 | 34 | async def set_value(self, value: datetime) -> None: 35 | """Set the value of the number entity.""" 36 | self._attr_native_value = value 37 | self.async_write_ha_state() 38 | -------------------------------------------------------------------------------- /addon/rootfs/app/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import traceback 3 | from os import path, environ 4 | 5 | import cv2 6 | import flask 7 | import numpy as np 8 | import requests 9 | from flask import request, jsonify 10 | 11 | from auth import token_required 12 | from lib.detection_model import load_net, detect 13 | 14 | THRESH = 0.08 # The threshold for a box to be considered a positive detection 15 | SESSION_TTL_SECONDS = 60 * 2 16 | 17 | app = flask.Flask(__name__) 18 | 19 | status = dict() 20 | 21 | # SECURITY WARNING: don't run with debug turned on in production! 22 | app.config['DEBUG'] = environ.get('DEBUG') == 'True' 23 | 24 | model_dir = path.join(path.dirname(path.realpath(__file__)), 'model') 25 | net_main = load_net(path.join(model_dir, 'model.cfg'), path.join(model_dir, 'model.meta')) 26 | 27 | 28 | @app.route('/p/', methods=['GET']) 29 | @token_required 30 | def get_p(): 31 | if 'img' in request.args: 32 | try: 33 | resp = requests.get(request.args['img'], stream=True, timeout=(0.1, 5)) 34 | resp.raise_for_status() 35 | img_array = np.array(bytearray(resp.content), dtype=np.uint8) 36 | img = cv2.imdecode(img_array, -1) 37 | detections = detect(net_main, img, thresh=THRESH) 38 | return jsonify({'detections': detections}) 39 | except: 40 | print(traceback.print_exc()) 41 | else: 42 | app.logger.warn("Invalid request params: {}".format(request.args)) 43 | 44 | return jsonify({'detections': []}) 45 | 46 | 47 | @app.route('/hc/', methods=['GET']) 48 | def health_check(): 49 | return 'ok' if net_main is not None else 'error' 50 | 51 | 52 | if __name__ == "__main__": 53 | app.run(host='0.0.0.0', port=3333, threaded=False) 54 | -------------------------------------------------------------------------------- /addon/Dockerfile.ha.base: -------------------------------------------------------------------------------- 1 | FROM ghcr.io/home-assistant/amd64-base-debian:bookworm as darknet_builder 2 | ENV DEBIAN_FRONTEND=noninteractive 3 | RUN apt update && apt install -y ca-certificates build-essential gcc g++ cmake git 4 | WORKDIR / 5 | # Lock darknet version for reproducibility 6 | RUN git clone https://github.com/AlexeyAB/darknet && cd darknet && git checkout 59c86222c5387bffd9108a21885f80e980ece234 7 | # compile CPU version 8 | RUN cd darknet \ 9 | && sed -i 's/GPU=1/GPU=0/' Makefile \ 10 | && sed -i 's/CUDNN=1/CUDNN=0/' Makefile \ 11 | && sed -i 's/CUDNN_HALF=1/CUDNN_HALF=0/' Makefile \ 12 | && sed -i 's/LIBSO=0/LIBSO=1/' Makefile \ 13 | && make -j 4 && mv libdarknet.so libdarknet_cpu.so 14 | 15 | # ----------------------------------------------------------------------------- 16 | 17 | FROM ghcr.io/home-assistant/amd64-base-debian:bookworm as ml_api_base_amd64 18 | 19 | RUN apt update && apt install --no-install-recommends -y ca-certificates python3-pip wget python3 python3-venv 20 | 21 | COPY rootfs / 22 | COPY --from=darknet_builder /darknet /darknet 23 | 24 | WORKDIR /app 25 | 26 | RUN python3 -m venv venv 27 | ENV VIRTUAL_ENV /app/venv 28 | ENV PATH /app/venv/bin:$PATH 29 | 30 | RUN pip3 install --upgrade pip && \ 31 | pip3 install opencv_python_headless && \ 32 | pip3 install -r requirements.txt 33 | 34 | RUN echo 'Downloading the latest failure detection AI model in Darknet format...' && \ 35 | wget -O model/model-weights.darknet $(cat model/model-weights.darknet.url | tr -d '\r') && \ 36 | echo 'Downloading the latest failure detection AI model in ONNX format...' && \ 37 | wget -O model/model-weights.onnx $(cat model/model-weights.onnx.url | tr -d '\r') 38 | 39 | RUN chmod +x /etc/services.d/ha-bambulab-spaghetti-detection/run 40 | 41 | -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import aiohttp 4 | import voluptuous as vol 5 | from homeassistant.config_entries import ConfigEntry 6 | from homeassistant.const import Platform 7 | from homeassistant.core import HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse 8 | 9 | DOMAIN = "bambu_lab_p1_spaghetti_detection" 10 | BRAND = "Bambu Lab P1 - Spaghetti Detection" 11 | 12 | LOGGER = logging.getLogger(__package__) 13 | 14 | PLATFORMS = [Platform.NUMBER, Platform.DATETIME] 15 | 16 | SPAGHETTI_DETECTION_SCHEMA = vol.Schema({ 17 | vol.Required("obico_host"): str, 18 | vol.Required("obico_auth_token"): str, 19 | vol.Required("image_url"): str, 20 | }) 21 | 22 | 23 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 24 | """Set up the Bambu Lab P1 - Spaghetti Detection integration.""" 25 | await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) 26 | 27 | async def spaghetti_detection_handler(call: ServiceCall) -> ServiceResponse: 28 | """Handle the custom service.""" 29 | obico_host = call.data.get("obico_host", "") 30 | obico_auth_token = call.data.get("obico_auth_token", "") 31 | image_url = call.data.get("image_url", "") 32 | 33 | if obico_host.endswith("/"): 34 | obico_host = obico_host[:-1] 35 | 36 | async with aiohttp.ClientSession() as session: 37 | async with session.get(f"{obico_host}/p/?img={image_url}", 38 | headers={"Authorization": f"Bearer {obico_auth_token}"}) as response: 39 | result = await response.json() 40 | 41 | return {"result": result} 42 | 43 | hass.services.async_register( 44 | DOMAIN, 45 | "predict", 46 | spaghetti_detection_handler, 47 | schema=SPAGHETTI_DETECTION_SCHEMA, 48 | supports_response=SupportsResponse.ONLY 49 | ) 50 | 51 | return True 52 | 53 | 54 | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: 55 | """Unload Bambu Lab P1 - Spaghetti Detection integration.""" 56 | return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) 57 | -------------------------------------------------------------------------------- /addon/rootfs/app/lib/detection_model.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | 3 | # pylint: disable=R, W0401, W0614, W0703 4 | from enum import Enum 5 | from lib.meta import Meta 6 | from os import path 7 | 8 | alt_names = None 9 | 10 | darknet_ready = True 11 | try: 12 | from lib.darknet import YoloNet 13 | except Exception as e: 14 | print(f'Error during importing YoloNet! - {e}') 15 | darknet_ready = False 16 | 17 | onnx_ready = True 18 | try: 19 | from lib.onnx import OnnxNet 20 | except Exception as e: 21 | print(f'Error during importing OnnxNet! - {e}') 22 | onnx_ready = False 23 | 24 | 25 | def load_net(config_path, meta_path, weights_path=None): 26 | 27 | def try_loading_net(net_config_priority): 28 | for net_config in net_config_priority: 29 | weights = net_config['weights_path'] 30 | use_gpu = net_config['use_gpu'] 31 | 32 | net_main = None 33 | try: 34 | print(f'----- Trying to load weights: {weights} - use_gpu = {use_gpu} -----') 35 | if weights.endswith(".onnx"): 36 | if not onnx_ready: 37 | raise Exception('Not loading ONNX net due to previous import failure. Check earlier log for errors.') 38 | net_main = OnnxNet(weights, meta_path, use_gpu) 39 | 40 | elif weights.endswith(".darknet"): 41 | if not darknet_ready: 42 | raise Exception('Not loading darknet net due to previous import failure. Check earlier log for errors.') 43 | net_main = YoloNet(weights, meta_path, config_path, use_gpu) 44 | 45 | else: 46 | raise Exception(f'Can not recognize net from weights file surfix: {weights}') 47 | 48 | print('Succeeded!') 49 | return net_main 50 | except Exception as e: 51 | print(f'Failed! - {e}') 52 | 53 | raise Exception(f'Failed to load any net after trying: {net_config_priority}') 54 | 55 | global alt_names # pylint: disable=W0603 56 | 57 | model_dir = path.join(path.dirname(path.realpath(__file__)), '..', 'model') 58 | net_config_priority = [ 59 | dict(weights_path=path.join(model_dir, 'model-weights.darknet'), use_gpu=True), 60 | dict(weights_path=path.join(model_dir, 'model-weights.onnx'), use_gpu=True), 61 | dict(weights_path=path.join(model_dir, 'model-weights.onnx'), use_gpu=False), 62 | dict(weights_path=path.join(model_dir, 'model-weights.darknet'), use_gpu=False), 63 | ] 64 | if weights_path is not None: 65 | net_config_priority = [ dict(weights_path=weights_path, use_gpu=True), dict(weights_path=weights_path, use_gpu=False) ] 66 | 67 | net_main = try_loading_net(net_config_priority) 68 | 69 | if alt_names is None: 70 | # In Python 3, the metafile default access craps out on Windows (but not Linux) 71 | # Read the names file and create a list to feed to detect 72 | try: 73 | meta = Meta(meta_path) 74 | alt_names = meta.names 75 | except Exception: 76 | pass 77 | 78 | return net_main 79 | 80 | def detect(net, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False): 81 | return net.detect(net.meta, image, alt_names, thresh, hier_thresh, nms, debug) -------------------------------------------------------------------------------- /addon/rootfs/app/lib/geometry.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, asdict 2 | from typing import Any, Dict, List, Tuple 3 | 4 | @dataclass 5 | class Box: 6 | """Detection rect""" 7 | xc: float 8 | yc: float 9 | w: float 10 | h: float 11 | 12 | @classmethod 13 | def from_tuple(cls, box: Tuple[float, float, float, float]) -> 'Box': 14 | return Box(xc=float(box[0]), yc=float(box[1]), w=float(box[2]), h=float(box[3])) 15 | 16 | def left(self) -> float: 17 | return self.xc - self.w * 0.5 18 | 19 | def right(self) -> float: 20 | return self.xc + self.w * 0.5 21 | 22 | def top(self) -> float: 23 | return self.yc - self.h * 0.5 24 | 25 | def bottom(self) -> float: 26 | return self.yc + self.h * 0.5 27 | 28 | def calc_iou(self, other: 'Box') -> float: 29 | """Calculates intersection over union ration which can be used to compare boxes""" 30 | al = self.left() 31 | ar = self.right() 32 | at = self.top() 33 | ab = self.bottom() 34 | 35 | bl = other.left() 36 | br = other.right() 37 | bt = other.top() 38 | bb = other.bottom() 39 | 40 | i_l = max(al, bl) 41 | i_r = min(ar, br) 42 | i_t = max(at, bt) 43 | i_b = min(ab, bb) 44 | 45 | o_l = min(al, bl) 46 | o_r = max(ar, br) 47 | o_t = min(at, bt) 48 | o_b = max(ab, bb) 49 | 50 | i_w = i_r - i_l 51 | i_h = i_b - i_t 52 | o_w = o_r - o_l 53 | o_h = o_b - o_t 54 | 55 | o_a = o_w * o_h 56 | if o_a <= 0.0: 57 | return 0.0 58 | return i_w * i_h / o_a 59 | 60 | 61 | @dataclass 62 | class Detection: 63 | """Detection result""" 64 | name: str 65 | confidence: float 66 | box: Box 67 | 68 | @classmethod 69 | def from_tuple_list(cls, detections: List[Tuple[str, float, Tuple[float, float, float, float]]]) -> List['Detection']: 70 | return [Detection.from_tuple(d) for d in detections] 71 | 72 | @classmethod 73 | def from_tuple(cls, detection: Tuple[str, float, Tuple[float, float, float, float]]) -> 'Detection': 74 | box = Box.from_tuple(detection[2]) 75 | return Detection(detection[0], float(detection[1]), box) 76 | 77 | @classmethod 78 | def from_dict(cls, data: Dict[str, Any]) -> 'Detection': 79 | return Detection(data['name'], data['confidence'], Box(**data['box'])) 80 | 81 | 82 | 83 | def compare_detections(l1: List[Detection], l2: List[Detection], threshold: float = 0.4) -> bool: 84 | """Compares two lists of detections. Returns true if lists looks similar with some threshold""" 85 | 86 | # Are there all boxes from l1 matching any in l2 87 | for a in l1: 88 | found = False 89 | for b in l2: 90 | iou = a.box.calc_iou(b.box) 91 | if iou >= threshold: 92 | found = True 93 | break 94 | if not found: 95 | return False 96 | 97 | # are there all boxes in l2 matching any in l1 98 | # the list may differ and contain duplicates, 99 | # that's why we need two checks 100 | for b in l2: 101 | found = False 102 | for a in l1: 103 | iou = a.box.calc_iou(b.box) 104 | if iou >= threshold: 105 | found = True 106 | break 107 | if not found: 108 | return False 109 | 110 | return True 111 | 112 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | wheels/ 22 | share/python-wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | *.py,cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | cover/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | db.sqlite3-journal 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | .pybuilder/ 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | # For a library or package, you might want to ignore these files since the code is 86 | # intended to run in multiple environments; otherwise, check them in: 87 | # .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # poetry 97 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 98 | # This is especially recommended for binary packages to ensure reproducibility, and is more 99 | # commonly ignored for libraries. 100 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 101 | #poetry.lock 102 | 103 | # pdm 104 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 105 | #pdm.lock 106 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 107 | # in version control. 108 | # https://pdm.fming.dev/#use-with-ide 109 | .pdm.toml 110 | 111 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 112 | __pypackages__/ 113 | 114 | # Celery stuff 115 | celerybeat-schedule 116 | celerybeat.pid 117 | 118 | # SageMath parsed files 119 | *.sage.py 120 | 121 | # Environments 122 | .env 123 | .venv 124 | env/ 125 | venv/ 126 | ENV/ 127 | env.bak/ 128 | venv.bak/ 129 | 130 | # Spyder project settings 131 | .spyderproject 132 | .spyproject 133 | 134 | # Rope project settings 135 | .ropeproject 136 | 137 | # mkdocs documentation 138 | /site 139 | 140 | # mypy 141 | .mypy_cache/ 142 | .dmypy.json 143 | dmypy.json 144 | 145 | # Pyre type checker 146 | .pyre/ 147 | 148 | # pytype static type analyzer 149 | .pytype/ 150 | 151 | # Cython debug symbols 152 | cython_debug/ 153 | 154 | # PyCharm 155 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 156 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 157 | # and can be added to the global gitignore or merged into this file. For a more nuclear 158 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 159 | .idea/ 160 | -------------------------------------------------------------------------------- /addon/rootfs/app/model/model.cfg: -------------------------------------------------------------------------------- 1 | [net] 2 | # Testing 3 | batch=64 4 | subdivisions=8 5 | # Training 6 | # batch=64 7 | # subdivisions=8 8 | height=416 9 | width=416 10 | channels=3 11 | momentum=0.9 12 | decay=0.0005 13 | angle=0 14 | saturation = 1.5 15 | exposure = 1.5 16 | hue=.1 17 | 18 | learning_rate=0.001 19 | burn_in=1000 20 | max_batches = 50000 21 | policy=steps 22 | steps=40000,60000 23 | scales=.1,.1 24 | 25 | [convolutional] 26 | batch_normalize=1 27 | filters=32 28 | size=3 29 | stride=1 30 | pad=1 31 | activation=leaky 32 | 33 | [maxpool] 34 | size=2 35 | stride=2 36 | 37 | [convolutional] 38 | batch_normalize=1 39 | filters=64 40 | size=3 41 | stride=1 42 | pad=1 43 | activation=leaky 44 | 45 | [maxpool] 46 | size=2 47 | stride=2 48 | 49 | [convolutional] 50 | batch_normalize=1 51 | filters=128 52 | size=3 53 | stride=1 54 | pad=1 55 | activation=leaky 56 | 57 | [convolutional] 58 | batch_normalize=1 59 | filters=64 60 | size=1 61 | stride=1 62 | pad=1 63 | activation=leaky 64 | 65 | [convolutional] 66 | batch_normalize=1 67 | filters=128 68 | size=3 69 | stride=1 70 | pad=1 71 | activation=leaky 72 | 73 | [maxpool] 74 | size=2 75 | stride=2 76 | 77 | [convolutional] 78 | batch_normalize=1 79 | filters=256 80 | size=3 81 | stride=1 82 | pad=1 83 | activation=leaky 84 | 85 | [convolutional] 86 | batch_normalize=1 87 | filters=128 88 | size=1 89 | stride=1 90 | pad=1 91 | activation=leaky 92 | 93 | [convolutional] 94 | batch_normalize=1 95 | filters=256 96 | size=3 97 | stride=1 98 | pad=1 99 | activation=leaky 100 | 101 | [maxpool] 102 | size=2 103 | stride=2 104 | 105 | [convolutional] 106 | batch_normalize=1 107 | filters=512 108 | size=3 109 | stride=1 110 | pad=1 111 | activation=leaky 112 | 113 | [convolutional] 114 | batch_normalize=1 115 | filters=256 116 | size=1 117 | stride=1 118 | pad=1 119 | activation=leaky 120 | 121 | [convolutional] 122 | batch_normalize=1 123 | filters=512 124 | size=3 125 | stride=1 126 | pad=1 127 | activation=leaky 128 | 129 | [convolutional] 130 | batch_normalize=1 131 | filters=256 132 | size=1 133 | stride=1 134 | pad=1 135 | activation=leaky 136 | 137 | [convolutional] 138 | batch_normalize=1 139 | filters=512 140 | size=3 141 | stride=1 142 | pad=1 143 | activation=leaky 144 | 145 | [maxpool] 146 | size=2 147 | stride=2 148 | 149 | [convolutional] 150 | batch_normalize=1 151 | filters=1024 152 | size=3 153 | stride=1 154 | pad=1 155 | activation=leaky 156 | 157 | [convolutional] 158 | batch_normalize=1 159 | filters=512 160 | size=1 161 | stride=1 162 | pad=1 163 | activation=leaky 164 | 165 | [convolutional] 166 | batch_normalize=1 167 | filters=1024 168 | size=3 169 | stride=1 170 | pad=1 171 | activation=leaky 172 | 173 | [convolutional] 174 | batch_normalize=1 175 | filters=512 176 | size=1 177 | stride=1 178 | pad=1 179 | activation=leaky 180 | 181 | [convolutional] 182 | batch_normalize=1 183 | filters=1024 184 | size=3 185 | stride=1 186 | pad=1 187 | activation=leaky 188 | 189 | 190 | ####### 191 | 192 | [convolutional] 193 | batch_normalize=1 194 | size=3 195 | stride=1 196 | pad=1 197 | filters=1024 198 | activation=leaky 199 | 200 | [convolutional] 201 | batch_normalize=1 202 | size=3 203 | stride=1 204 | pad=1 205 | filters=1024 206 | activation=leaky 207 | 208 | [route] 209 | layers=-9 210 | 211 | [convolutional] 212 | batch_normalize=1 213 | size=1 214 | stride=1 215 | pad=1 216 | filters=64 217 | activation=leaky 218 | 219 | [reorg3d] 220 | stride=2 221 | 222 | [route] 223 | layers=-1,-4 224 | 225 | [convolutional] 226 | batch_normalize=1 227 | size=3 228 | stride=1 229 | pad=1 230 | filters=1024 231 | activation=leaky 232 | 233 | [convolutional] 234 | size=1 235 | stride=1 236 | pad=1 237 | filters=30 238 | activation=linear 239 | 240 | 241 | [region] 242 | anchors = 1.3221, 1.73145, 3.19275, 4.00944, 5.05587, 8.09892, 9.47112, 4.84053, 11.2364, 10.0071 243 | bias_match=1 244 | classes=1 245 | coords=4 246 | num=5 247 | softmax=1 248 | jitter=.3 249 | rescore=1 250 | 251 | object_scale=5 252 | noobject_scale=1 253 | class_scale=1 254 | coord_scale=1 255 | 256 | absolute=1 257 | thresh = .6 258 | random=1 259 | -------------------------------------------------------------------------------- /custom_components/bambu_lab_p1_spaghetti_detection/number.py: -------------------------------------------------------------------------------- 1 | from homeassistant.components.number import NumberEntity, NumberEntityDescription 2 | 3 | NUMBER_TYPES: tuple[NumberEntityDescription, ...] = ( 4 | NumberEntityDescription( 5 | key="current_frame_number", 6 | name="Spaghetti Detection - Current Frame Number", 7 | native_min_value=0, 8 | native_max_value=10000000000000000 9 | ), 10 | NumberEntityDescription( 11 | key="lifetime_frame_number", 12 | name="Spaghetti Detection - Lifetime Frame Number", 13 | native_min_value=0, 14 | native_max_value=10000000000000000 15 | ), 16 | NumberEntityDescription( 17 | key="ewm_mean", 18 | name="Spaghetti Detection - EWM Mean", 19 | native_min_value=-1000000000000000, 20 | native_max_value=10000000000000000, 21 | native_step=0.000000001 22 | ), 23 | NumberEntityDescription( 24 | key="adjusted_ewm_mean", 25 | name="Spaghetti Detection - Adjusted EWM Mean", 26 | native_min_value=-1000000000000000, 27 | native_max_value=10000000000000000, 28 | native_step=0.000000001 29 | ), 30 | NumberEntityDescription( 31 | key="p", 32 | name="Spaghetti Detection - P", 33 | native_min_value=-1000000000000000, 34 | native_max_value=10000000000000000, 35 | native_step=0.000000001 36 | ), 37 | NumberEntityDescription( 38 | key="normalized_p", 39 | name="Spaghetti Detection - Normalized P", 40 | native_min_value=-1000000000000000, 41 | native_max_value=10000000000000000, 42 | native_step=0.000000001 43 | ), 44 | NumberEntityDescription( 45 | key="p_sum", 46 | name="Spaghetti Detection - P Sum", 47 | native_min_value=-1000000000000000, 48 | native_max_value=10000000000000000, 49 | native_step=0.000000001 50 | ), 51 | NumberEntityDescription( 52 | key="rolling_mean_diff", 53 | name="Spaghetti Detection - Rolling Mean Diff", 54 | native_min_value=-1000000000000000, 55 | native_max_value=10000000000000000, 56 | native_step=0.000000001 57 | ), 58 | NumberEntityDescription( 59 | key="rolling_mean_long", 60 | name="Spaghetti Detection - Rolling Mean Long", 61 | native_min_value=-1000000000000000, 62 | native_max_value=10000000000000000, 63 | native_step=0.000000001 64 | ), 65 | NumberEntityDescription( 66 | key="rolling_mean_short", 67 | name="Spaghetti Detection - Rolling Mean Short", 68 | native_min_value=-1000000000000000, 69 | native_max_value=10000000000000000, 70 | native_step=0.000000001 71 | ), 72 | NumberEntityDescription( 73 | key="thresh_warning", 74 | name="Spaghetti Detection - Thresh Warning", 75 | native_min_value=-1000000000000000, 76 | native_max_value=10000000000000000, 77 | native_step=0.000000001 78 | ), 79 | NumberEntityDescription( 80 | key="thresh_failure", 81 | name="Spaghetti Detection - Thresh Failure", 82 | native_min_value=-1000000000000000, 83 | native_max_value=10000000000000000, 84 | native_step=0.000000001 85 | ), 86 | ) 87 | 88 | 89 | async def async_setup_entry(hass, entry, async_add_entities): 90 | entities = [ 91 | BambuLabP1SpaghettiDetectionNumberEntity(entity_description) for entity_description in NUMBER_TYPES 92 | ] 93 | 94 | async_add_entities(entities) 95 | 96 | 97 | class BambuLabP1SpaghettiDetectionNumberEntity(NumberEntity): 98 | def __init__(self, entity_description): 99 | self.entity_description = entity_description 100 | 101 | self.entity_id = "number.bambu_lab_p1_spaghetti_detection_%s" % entity_description.key 102 | self._attr_unique_id = "number.bambu_lab_p1_spaghetti_detection_%s" % entity_description.key 103 | if self._attr_native_value is None: 104 | self._attr_native_value = 0 105 | 106 | async def async_set_native_value(self, value: float) -> None: 107 | """Set the value of the number entity.""" 108 | self._attr_native_value = value 109 | self.async_write_ha_state() 110 | -------------------------------------------------------------------------------- /addon/rootfs/app/lib/onnx.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple 2 | import onnxruntime 3 | import numpy as np 4 | import cv2 5 | import os 6 | 7 | from lib.meta import Meta 8 | 9 | class OnnxNet: 10 | session: onnxruntime.InferenceSession 11 | meta: Meta 12 | 13 | def __init__(self, onnx_path: str, meta_path: str, use_gpu: bool): 14 | providers = ['CUDAExecutionProvider'] if use_gpu else ['CPUExecutionProvider'] 15 | self.session = onnxruntime.InferenceSession(onnx_path, providers=providers) 16 | self.meta = Meta(meta_path) 17 | 18 | def detect(self, meta, image, alt_names, thresh=.5, hier_thresh=.5, nms=.45, debug=False) -> List[Tuple[str, float, Tuple[float, float, float, float]]]: 19 | input_h = self.session.get_inputs()[0].shape[2] 20 | input_w = self.session.get_inputs()[0].shape[3] 21 | width = image.shape[1] 22 | height = image.shape[0] 23 | 24 | # Input 25 | resized = cv2.resize(image, (input_w, input_h), interpolation=cv2.INTER_LINEAR) 26 | img_in = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB) 27 | img_in = np.transpose(img_in, (2, 0, 1)).astype(np.float32) 28 | img_in = np.expand_dims(img_in, axis=0) 29 | img_in /= 255.0 30 | 31 | input_name = self.session.get_inputs()[0].name 32 | outputs = self.session.run(None, {input_name: img_in}) 33 | 34 | detections = post_processing(outputs, width, height, thresh, nms, meta.names) 35 | return detections[0] 36 | 37 | 38 | def nms_cpu(boxes, confs, nms_thresh=0.5, min_mode=False): 39 | # print(boxes.shape) 40 | x1 = boxes[:, 0] 41 | y1 = boxes[:, 1] 42 | x2 = boxes[:, 2] 43 | y2 = boxes[:, 3] 44 | 45 | areas = (x2 - x1) * (y2 - y1) 46 | order = confs.argsort()[::-1] 47 | 48 | keep = [] 49 | while order.size > 0: 50 | idx_self = order[0] 51 | idx_other = order[1:] 52 | 53 | keep.append(idx_self) 54 | 55 | xx1 = np.maximum(x1[idx_self], x1[idx_other]) 56 | yy1 = np.maximum(y1[idx_self], y1[idx_other]) 57 | xx2 = np.minimum(x2[idx_self], x2[idx_other]) 58 | yy2 = np.minimum(y2[idx_self], y2[idx_other]) 59 | 60 | w = np.maximum(0.0, xx2 - xx1) 61 | h = np.maximum(0.0, yy2 - yy1) 62 | inter = w * h 63 | 64 | if min_mode: 65 | over = inter / np.minimum(areas[order[0]], areas[order[1:]]) 66 | else: 67 | over = inter / (areas[order[0]] + areas[order[1:]] - inter) 68 | 69 | inds = np.where(over <= nms_thresh)[0] 70 | order = order[inds + 1] 71 | 72 | return np.array(keep) 73 | 74 | def post_processing(output, width, height, conf_thresh, nms_thresh, names): 75 | box_array = output[0] 76 | confs = output[1] 77 | 78 | if type(box_array).__name__ != 'ndarray': 79 | box_array = box_array.cpu().detach().numpy() 80 | confs = confs.cpu().detach().numpy() 81 | 82 | num_classes = confs.shape[2] 83 | 84 | # [batch, num, 4] 85 | box_array = box_array[:, :, 0] 86 | 87 | # [batch, num, num_classes] --> [batch, num] 88 | max_conf = np.max(confs, axis=2) 89 | max_id = np.argmax(confs, axis=2) 90 | 91 | box_x1x1x2y2_to_xcycwh_scaled = lambda b: \ 92 | ( 93 | float(0.5 * width * (b[0] + b[2])), 94 | float(0.5 * height * (b[1] + b[3])), 95 | float(width * (b[2] - b[0])), 96 | float(width * (b[3] - b[1])) 97 | ) 98 | dets_batch = [] 99 | for i in range(box_array.shape[0]): 100 | 101 | argwhere = max_conf[i] > conf_thresh 102 | l_box_array = box_array[i, argwhere, :] 103 | l_max_conf = max_conf[i, argwhere] 104 | l_max_id = max_id[i, argwhere] 105 | 106 | bboxes = [] 107 | # nms for each class 108 | for j in range(num_classes): 109 | 110 | cls_argwhere = l_max_id == j 111 | ll_box_array = l_box_array[cls_argwhere, :] 112 | ll_max_conf = l_max_conf[cls_argwhere] 113 | ll_max_id = l_max_id[cls_argwhere] 114 | 115 | keep = nms_cpu(ll_box_array, ll_max_conf, nms_thresh) 116 | 117 | if (keep.size > 0): 118 | ll_box_array = ll_box_array[keep, :] 119 | ll_max_conf = ll_max_conf[keep] 120 | ll_max_id = ll_max_id[keep] 121 | 122 | for k in range(ll_box_array.shape[0]): 123 | bboxes.append([ll_box_array[k, 0], ll_box_array[k, 1], ll_box_array[k, 2], ll_box_array[k, 3], ll_max_conf[k], ll_max_conf[k], ll_max_id[k]]) 124 | 125 | detections = [(names[b[6]], float(b[4]), box_x1x1x2y2_to_xcycwh_scaled((b[0], b[1], b[2], b[3]))) for b in bboxes] 126 | dets_batch.append(detections) 127 | 128 | 129 | return dets_batch 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /addon/detect.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | import cv2 3 | from dataclasses import asdict 4 | import json 5 | from addon import compare_detections, Detection 6 | import os 7 | import argparse 8 | import time 9 | 10 | KNOWN_IMAGE_EXTENSIONS = ('.jpg', '.png') 11 | KNOWN_VIDEO_EXTENSIONS = ('.mp4', '.avi') 12 | 13 | if __name__ == "__main__": 14 | parser = argparse.ArgumentParser() 15 | parser.add_argument("image", type=str, help="Image file path") 16 | parser.add_argument("--weights", type=str, help="Model weights file") 17 | parser.add_argument("--det-threshold", type=float, default=0.25, help="Detection threshold") 18 | parser.add_argument("--nms-threshold", type=float, default=0.4, help="NMS threshold") 19 | parser.add_argument("--preheat", action='store_true', help="Make a dry run of NN for initlalization") 20 | parser.add_argument("--cpu", action='store_true', help="Force use CPU") 21 | parser.add_argument("--save-detections-to", type=str, help="Save detections into this file") 22 | parser.add_argument("--compare-detections-with", type=str, help="Load detections from this file and compare with result") 23 | parser.add_argument("--render-to", type=str, help="Save detections into this file or directory") 24 | parser.add_argument("--print", action='store_true', help="Print detections") 25 | opt = parser.parse_args() 26 | 27 | net_main_1 = load_net("rootfs/model/model.cfg", "rootfs/model/model.meta", weights_path=opt.weights) 28 | 29 | # force use CPU, only implemented for ONNX 30 | if opt.cpu and onnx_ready and isinstance(net_main_1, OnnxNet): 31 | net_main_1.force_cpu() 32 | 33 | filename = os.path.basename(opt.image) 34 | filename, extension = os.path.splitext(filename) 35 | 36 | is_image = extension in KNOWN_IMAGE_EXTENSIONS 37 | is_video = extension in KNOWN_VIDEO_EXTENSIONS 38 | frame_number = 0 39 | vwr = None 40 | if is_video: 41 | cap = cv2.VideoCapture(opt.image) 42 | fps = cap.get(cv2.CAP_PROP_FPS) 43 | frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 44 | frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 45 | reading_success, custom_image_bgr = cap.read() 46 | if opt.render_to: 47 | fourcc = cv2.VideoWriter_fourcc("m", "p", "4", "v") 48 | vwr = cv2.VideoWriter(opt.render_to, fourcc, fps, (frame_w, frame_h)) 49 | else: 50 | cap = None 51 | fps = 0.0 52 | custom_image_bgr = cv2.imread(opt.image) 53 | reading_success = True 54 | 55 | 56 | # this will make library initialize all the required resources at the first run 57 | # then the following runs will be much faster 58 | if opt.preheat: 59 | detections = detect(net_main_1, custom_image_bgr, thresh=opt.det_threshold, nms=opt.nms_threshold) 60 | 61 | while reading_success: 62 | started_at = time.time() 63 | detections = detect(net_main_1, custom_image_bgr, thresh=opt.det_threshold, nms=opt.nms_threshold) 64 | finished_at = time.time() 65 | execution_time = finished_at - started_at 66 | print(f"Frame #{frame_number} execution time: {execution_time:.3} sec, detection count: {len(detections)}") 67 | 68 | detections = Detection.from_tuple_list(detections) 69 | # dump detections into some file 70 | if opt.save_detections_to: 71 | output_filename, output_extension = os.path.splitext(opt.save_detections_to) 72 | if is_video and not output_extension and not os.path.exists(opt.save_detections_to): 73 | os.makedirs(opt.save_detections_to) 74 | if os.path.isdir(opt.save_detections_to): 75 | if is_video: 76 | output_file_name = f"{filename}#{frame_number:04}.json" 77 | else: 78 | output_file_name = f"{filename}.json" 79 | output_file_name = os.path.join(opt.save_detections_to, output_file_name) 80 | else: 81 | output_file_name = opt.save_detections_to 82 | 83 | with open(output_file_name, "w") as f: 84 | json.dump([asdict(d) for d in detections], f) 85 | 86 | # load detections from some file and compare with detection result 87 | if opt.compare_detections_with: 88 | if is_video: 89 | read_file_name = os.path.join(opt.compare_detections_with, f"{filename}#{frame_number:04}.json") 90 | else: 91 | read_file_name = opt.compare_detections_with 92 | 93 | with open(read_file_name) as f: 94 | items = json.load(f) 95 | loaded = [Detection.from_dict(d) for d in items] 96 | compare_result = compare_detections(loaded, detections) 97 | if not compare_result: 98 | print(f"Frame #{frame_number} loaded detections and resulting are different") 99 | if opt.render_to: 100 | for d in detections: 101 | cv2.rectangle(custom_image_bgr, 102 | (int(d.box.left()), int(d.box.top())), (int(d.box.right()), int(d.box.bottom())), 103 | (0, 255, 0), 2) 104 | if vwr: 105 | vwr.write(custom_image_bgr) 106 | else: 107 | cv2.imwrite(opt.render_to, custom_image_bgr) 108 | 109 | 110 | if opt.print: 111 | print(detections) 112 | 113 | if is_image: 114 | reading_success = False 115 | elif cap: 116 | reading_success, custom_image_bgr = cap.read() 117 | frame_number += 1 118 | 119 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bambu Lab - Spaghetti Detection Integration 2 | 3 | Upgrade your Bambu Lab 3D printer experience with the Home Assistant Spaghetti Detection Integration. This 4 | integration leverages the power of both the [Bambu Lab Integration](https://github.com/greghesp/ha-bambulab) and 5 | the [Obico](https://www.obico.io) ML server, providing a solution for detecting and handling spaghetti incidents during 6 | your prints. 7 | 8 | If you like this automation and would like to support it, you can [buy me a coffee](https://www.patreon.com/nberk/shop). 9 | 10 | ## Features 11 | 12 | - **Spaghetti Detection:** Utilize Obico's machine learning server to identify and prevent spaghetti issues. 13 | - **Critical/Standard Notifications:** Stay informed with customizable notifications. 14 | - **Warn/Pause/Cancel Print on Failure Detection:** Take proactive measures by automatically warning, pausing or canceling print jobs upon the detection of spaghetti-related failures, preventing wasted material and time. 15 | - **Third Party Camera Support:** Any camera entity can also be used for detecting failures. 16 | 17 | ## Supported Printers 18 | | Device | Compatibility | 19 | |-----------------|---------------| 20 | | X1 Series | ✔️ 21 | | P1 Series | ✔️ 22 | | A1 Series | ✔️ 23 | 24 | 25 | ## Prerequisites 26 | 27 | Ensure the following prerequisites are met before installing the Spaghetti Detection Integration: 28 | 29 | - [Bambu Lab Integration](https://github.com/greghesp/ha-bambulab) must be installed. 30 | - A server with at least 4GB of RAM that meets the [Obico hardware requirements](https://www.obico.io/docs/server-guides/hardware-requirements/). 31 | 32 |
33 | 34 | > **_NOTE:_** The integration does **not** support the following devices: 35 | 36 | | Device | Compatibility | 37 | | ---- | ----- | 38 | | Raspberry Pi (Any Model) | ❌ 39 | | Home Assistant Green | ❌ 40 | | Home Assistant Yellow | ❌ 41 | | Latte Panda | ❌ 42 | | Jetson Nano 2gb | ❌ 43 | 44 | ## Setup 45 | 46 | Follow these steps to set up the Spaghetti Detection Integration: 47 | 48 | 1. **Install Obico ML Server** 49 | - Choose between installing it as a Home Assistant Addon or as a standalone Docker container. 50 | 51 | 2. **Install `Bambu Lab P1 - Spaghetti Detection` Home Assistant Integration** 52 | 3. **Install Home Assistant Spaghetti Detection Automation Blueprint** 53 | 54 | For detailed installation instructions and troubleshooting tips, refer to 55 | the [Installation Guide](#link-to-installation-guide). 56 | 57 | ## 1. Install Obico ML Server 58 | 59 | ### Install Obico ML Server as Home Assistant Addon 60 | 61 | To install Obico ML server as a Home Assistant Add-on you have 2 options: 62 | 63 | 1. Click the **Add Add-On Repository** button below, click **Add → Close** (You might need to enter the **internal 64 | IP address** of your Home Assistant instance first). 65 | 66 | [![Open your Home Assistant instance and show the add add-on repository dialog with a specific repository URL pre-filled.](https://my.home-assistant.io/badges/supervisor_add_addon_repository.svg)](https://my.home-assistant.io/redirect/supervisor_add_addon_repository/?repository_url=https://github.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection) 67 | 68 | 2. Add the repository URL under **Settings → Add-ons → ADD-ON STORE** and click **⋮ → Repositories**: 69 | 70 | https://github.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection 71 | 72 | ### Install Obico ML Server as a Standalone Docker Container 73 | 74 | 1. Create docker container using the following command: 75 | 76 | docker create \ 77 | --restart unless-stopped \ 78 | --env ML_API_TOKEN=obico_api_secret \ 79 | --publish 3333:3333 \ 80 | --name ha_bambu_lab_p1_spaghetti_detection \ 81 | nberk/ha_bambu_lab_p1_spaghetti_detection_standalone:latest 82 | 83 | 2. Start the container using the following command: 84 | 85 | docker start ha_bambu_lab_p1_spaghetti_detection 86 | 87 | ### Install Obico ML Server as a Standalone Docker Container with Docker Compose 88 | 89 | 1. Download the docker-compose.yaml from the repository 90 | 91 | 2. Edit the environment variables section in the docker compose yaml: 92 | 93 | ``` 94 | environment: 95 | - ML_API_TOKEN=obico_api_secret 96 | - TZ=Europe/London 97 | ``` 98 | 99 | 3. Run the command: 100 | 101 | docker compose up -d 102 | 103 | ## 2. Install Home Assistant Integration 104 | 105 | ### HACS 106 | 107 | 1. Click the button below to download and install the integration: 108 | 109 | [![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=nberktumer&repository=ha-bambu-lab-p1-spaghetti-detection&category=Integration) 110 | 111 | 2. Go to **Settings → Devices & services → Add Integration** and add **Bambu Lab P1 - Spaghetti Detection** integration. 112 | 113 | ### Manual 114 | 115 | Manually copy the contents of the custom_components folder to your Home Assistant config/custom_components folder. After 116 | restarting Home Assistant, add and configure the integration through the native integration setup. 117 | 118 | ## 3. Install Home Assistant Automation Blueprint 119 | 120 | 1. Click the button below to import the Spaghetti Detection blueprint: 121 | 122 | [![Open your Home Assistant instance and show the blueprint import dialog with a specific blueprint pre-filled.](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https://github.com/nberktumer/ha-bambu-lab-p1-spaghetti-detection/blob/main/blueprints/spaghetti_detection.yaml) 123 | 124 | 2. Go to the imported blueprint and create the automation: 125 | 126 | ![Configure the automation](docs/images/blueprint_installation.png) 127 | 128 | ### Blueprint Parameters 129 | 130 | 131 | | Parameter | Description | 132 | | ---- | ----- | 133 | | **Home Assistant Host** | The address of your Home Assistant instance. Required for sending the printer camera image to the Obico ML server. Ensure to include your Home Assistant port. This address is also used for notification images. If you wish to view failure images on notifications outside your local network, provide a publicly accessible link here. 134 | | **Obico ML API Host** | The URL of the Obico ML Server. The default port number is `3333`. If you installed the ML server via the Home Assistant Addon, the IP address should match your Home Assistant address. 135 | | **Obico ML API Auth Token** | The authentication token for the Obico ML Server. The default value is `obico_api_secret` and can be configured through the addon settings or the docker container create command. 136 | | **Notification Settings** | - **Critical Notification:** Generates an audible alert even when your device is in silent mode.
- **Standard Notification:** Sends a traditional notification respecting your device's audio settings.
- **None:** No notifications are sent in case of a failure. 137 | | **Notification Service** | The notification service of your choice for selecting a single device or a group of devices, instead of alerting all mobile devices registered in home assistant. The default is `notify.notify`, which notifies all devices. 138 | 139 | 140 | ## Credits 141 | 142 | - **Greg Hesp ([@greghesp](https://github.com/greghesp))**: https://github.com/greghesp/ha-bambulab 143 | - **Obico ([@TheSpaghettiDetective](https://github.com/TheSpaghettiDetective))**: https://github.com/TheSpaghettiDetective/obico-server 144 | -------------------------------------------------------------------------------- /addon/rootfs/app/lib/darknet.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=R, W0401, W0614, W0703 2 | from ctypes import * 3 | import random 4 | import os 5 | import cv2 6 | import platform 7 | from typing import List, Tuple 8 | 9 | # C-structures from Darknet lib 10 | 11 | class BOX(Structure): 12 | _fields_ = [("x", c_float), 13 | ("y", c_float), 14 | ("w", c_float), 15 | ("h", c_float)] 16 | 17 | 18 | class DETECTION(Structure): 19 | _fields_ = [("bbox", BOX), 20 | ("classes", c_int), 21 | ("best_class_idx", c_int), 22 | ("prob", POINTER(c_float)), 23 | ("mask", POINTER(c_float)), 24 | ("objectness", c_float), 25 | ("sort_class", c_int), 26 | ("uc", POINTER(c_float)), 27 | ("points", c_int), 28 | ("embeddings", POINTER(c_float)), 29 | ("embedding_size", c_int), 30 | ("sim", c_float), 31 | ("track_id", c_int)] 32 | 33 | class IMAGE(Structure): 34 | _fields_ = [("w", c_int), 35 | ("h", c_int), 36 | ("c", c_int), 37 | ("data", POINTER(c_float))] 38 | 39 | 40 | class METADATA(Structure): 41 | _fields_ = [("classes", c_int), 42 | ("names", POINTER(c_char_p))] 43 | 44 | class YoloNet: 45 | """Darknet-based detector implementation""" 46 | net: c_void_p 47 | meta: METADATA 48 | 49 | def __init__(self, weight_path: str, meta_path: str, config_path: str, asked_to_use_gpu: bool): 50 | if not os.path.exists(config_path): 51 | raise ValueError("Invalid config path `"+os.path.abspath(config_path)+"`") 52 | if not os.path.exists(weight_path): 53 | raise ValueError("Invalid weight path `"+os.path.abspath(weight_path)+"`") 54 | if not os.path.exists(meta_path): 55 | raise ValueError("Invalid data file path `"+os.path.abspath(meta_path)+"`") 56 | if not lib: 57 | raise ImportError(f"Unable to load darknet module.") 58 | 59 | if asked_to_use_gpu and not using_gpu: 60 | raise Exception('I respectfully decline to load the net as I am asked to use GPU but the loaded darknet module does NOT have GPU support') 61 | 62 | self.net = load_net_custom(config_path.encode("ascii"), weight_path.encode("ascii"), 0, 1) # batch size = 1 63 | self.meta = load_meta(meta_path.encode("ascii")) 64 | 65 | def detect(self, meta, image, alt_names, thresh=.5, hier_thresh=.5, nms=.45, debug=False) -> List[Tuple[str, float, Tuple[float, float, float, float]]]: 66 | #pylint: disable= C0321 67 | custom_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 68 | im, arr = array_to_image(custom_image) # you should comment line below: free_image(im) 69 | if debug: 70 | print("Loaded image") 71 | num = c_int(0) 72 | if debug: 73 | print("Assigned num") 74 | pnum = pointer(num) 75 | if debug: 76 | print("Assigned pnum") 77 | predict_image(self.net, im) 78 | if debug: 79 | print("did prediction") 80 | dets = get_network_boxes(self.net, custom_image.shape[1], custom_image.shape[0], thresh, hier_thresh, None, 0, pnum, 0) # OpenCV 81 | if debug: 82 | print("Got dets") 83 | num = pnum[0] 84 | if debug: 85 | print("got zeroth index of pnum") 86 | if nms: 87 | do_nms_sort(dets, num, meta.classes, nms) 88 | if debug: 89 | print("did sort") 90 | res = [] 91 | if debug: 92 | print("about to range") 93 | for j in range(num): 94 | if debug: 95 | print("Ranging on "+str(j)+" of "+str(num)) 96 | if debug: 97 | print("Classes: "+str(meta), meta.classes, meta.names) 98 | for i in range(meta.classes): 99 | if debug: 100 | print("Class-ranging on "+str(i)+" of "+str(meta.classes)+"= "+str(dets[j].prob[i])) 101 | if dets[j].prob[i] > 0: 102 | b = dets[j].bbox 103 | if alt_names is None: 104 | nameTag = meta.names[i] 105 | else: 106 | nameTag = alt_names[i] 107 | if debug: 108 | print("Got bbox", b) 109 | print(nameTag) 110 | print(dets[j].prob[i]) 111 | print((b.x, b.y, b.w, b.h)) 112 | res.append((nameTag, dets[j].prob[i], (b.x, b.y, b.w, b.h))) 113 | if debug: 114 | print("did range") 115 | res = sorted(res, key=lambda x: -x[1]) 116 | if debug: 117 | print("did sort") 118 | free_detections(dets, num) 119 | if debug: 120 | print("freed detections") 121 | return res 122 | 123 | # Loads darknet shared library. May fail if some dependencies like OpenCV not installed 124 | # libdarknet_gpu.so needs Cuda + Cudnn and other libraries in path, which may not exist 125 | # For the such case, it will try to load libdarknet.so instead 126 | lib = None 127 | using_gpu = False 128 | 129 | print('\n') 130 | so_path = os.path.join('/darknet', "libdarknet_cpu.so") 131 | lib = CDLL(so_path, RTLD_GLOBAL) 132 | print(f" Darknet is now running on CPU.") 133 | print('\n') 134 | 135 | if lib: 136 | lib.network_width.argtypes = [c_void_p] 137 | lib.network_width.restype = c_int 138 | lib.network_height.argtypes = [c_void_p] 139 | lib.network_height.restype = c_int 140 | 141 | predict = lib.network_predict 142 | predict.argtypes = [c_void_p, POINTER(c_float)] 143 | predict.restype = POINTER(c_float) 144 | 145 | if using_gpu: 146 | set_gpu = lib.cuda_set_device 147 | set_gpu.argtypes = [c_int] 148 | 149 | make_image = lib.make_image 150 | make_image.argtypes = [c_int, c_int, c_int] 151 | make_image.restype = IMAGE 152 | 153 | get_network_boxes = lib.get_network_boxes 154 | get_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(c_int), c_int, POINTER(c_int), c_int] 155 | get_network_boxes.restype = POINTER(DETECTION) 156 | 157 | make_network_boxes = lib.make_network_boxes 158 | make_network_boxes.argtypes = [c_void_p] 159 | make_network_boxes.restype = POINTER(DETECTION) 160 | 161 | free_detections = lib.free_detections 162 | free_detections.argtypes = [POINTER(DETECTION), c_int] 163 | 164 | free_ptrs = lib.free_ptrs 165 | free_ptrs.argtypes = [POINTER(c_void_p), c_int] 166 | 167 | network_predict = lib.network_predict 168 | network_predict.argtypes = [c_void_p, POINTER(c_float)] 169 | 170 | reset_rnn = lib.reset_rnn 171 | reset_rnn.argtypes = [c_void_p] 172 | 173 | load_net = lib.load_network 174 | load_net.argtypes = [c_char_p, c_char_p, c_int] 175 | load_net.restype = c_void_p 176 | 177 | load_net_custom = lib.load_network_custom 178 | load_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int] 179 | load_net_custom.restype = c_void_p 180 | 181 | do_nms_obj = lib.do_nms_obj 182 | do_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float] 183 | 184 | do_nms_sort = lib.do_nms_sort 185 | do_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float] 186 | 187 | free_image = lib.free_image 188 | free_image.argtypes = [IMAGE] 189 | 190 | letterbox_image = lib.letterbox_image 191 | letterbox_image.argtypes = [IMAGE, c_int, c_int] 192 | letterbox_image.restype = IMAGE 193 | 194 | load_meta = lib.get_metadata 195 | lib.get_metadata.argtypes = [c_char_p] 196 | lib.get_metadata.restype = METADATA 197 | 198 | load_image = lib.load_image_color 199 | load_image.argtypes = [c_char_p, c_int, c_int] 200 | load_image.restype = IMAGE 201 | 202 | rgbgr_image = lib.rgbgr_image 203 | rgbgr_image.argtypes = [IMAGE] 204 | 205 | predict_image = lib.network_predict_image 206 | predict_image.argtypes = [c_void_p, IMAGE] 207 | predict_image.restype = POINTER(c_float) 208 | 209 | def sample(probs): 210 | s = sum(probs) 211 | probs = [a/s for a in probs] 212 | r = random.uniform(0, 1) 213 | for i in range(len(probs)): 214 | r = r - probs[i] 215 | if r <= 0: 216 | return i 217 | return len(probs)-1 218 | 219 | 220 | def c_array(ctype, values): 221 | arr = (ctype*len(values))() 222 | arr[:] = values 223 | return arr 224 | 225 | def array_to_image(arr): 226 | import numpy as np 227 | # need to return old values to avoid python freeing memory 228 | arr = arr.transpose(2, 0, 1) 229 | c = arr.shape[0] 230 | h = arr.shape[1] 231 | w = arr.shape[2] 232 | arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0 233 | data = arr.ctypes.data_as(POINTER(c_float)) 234 | im = IMAGE(w, h, c, data) 235 | return im, arr 236 | 237 | 238 | def classify(net, meta, im): 239 | global alt_names 240 | 241 | out = predict_image(net, im) 242 | res = [] 243 | for i in range(meta.classes): 244 | if alt_names is None: 245 | nameTag = meta.names[i] 246 | else: 247 | nameTag = alt_names[i] 248 | res.append((nameTag, out[i])) 249 | res = sorted(res, key=lambda x: -x[1]) 250 | return res 251 | 252 | 253 | 254 | 255 | -------------------------------------------------------------------------------- /blueprints/spaghetti_detection.yaml: -------------------------------------------------------------------------------- 1 | blueprint: 2 | name: Bambu Lab - Spaghetti Detection 3 | description: Bambu Lab - Spaghetti Detection 4 | domain: automation 5 | input: 6 | home_assistant_host: 7 | name: Home Assistant Host 8 | description: Home Assistant host 9 | default: "http://192.168.1.123:8123" 10 | obico_host: 11 | name: Obico ML API Host 12 | description: Obico ML API host 13 | default: "http://192.168.1.123:3333" 14 | obico_auth_token: 15 | name: Obico ML API Auth Token 16 | description: Obico ML API authentication token 17 | default: "obico_api_secret" 18 | detection_frequency: 19 | name: Detection Frequency 20 | description: The detection algorithm will run in every defined seconds 21 | default: "/5" 22 | selector: 23 | select: 24 | options: 25 | - label: Every second 26 | value: "/1" 27 | - label: Every 5 seconds 28 | value: "/5" 29 | - label: Every 10 seconds 30 | value: "/10" 31 | - label: Every 30 seconds 32 | value: "/30" 33 | - label: Every 60 seconds 34 | value: "/59" 35 | multiple: false 36 | mode: dropdown 37 | auto_turn_on_light: 38 | name: Automatically Turn On Printer Lights 39 | description: Turns on printer lights before spaghetti detection operation 40 | default: true 41 | selector: 42 | boolean: 43 | notification_settings: 44 | name: Notification Settings 45 | description: Type of notification to send after detecting a failure 46 | default: standard 47 | selector: 48 | select: 49 | mode: dropdown 50 | options: 51 | - label: Critical Notification 52 | value: critical 53 | - label: Standard Notification 54 | value: standard 55 | - label: None 56 | value: none 57 | failure_action: 58 | name: On Failure Action 59 | description: What to do after detecting a failure 60 | default: pause 61 | selector: 62 | select: 63 | mode: dropdown 64 | options: 65 | - label: Pause 66 | value: pause 67 | - label: Stop 68 | value: stop 69 | - label: Warn 70 | value: warn 71 | notification_service: 72 | name: Mobile devices notification service 73 | description: >- 74 | The notification service for mobile devices (eg. notify.mobile_app_). 75 | You can provide both a notify group or a single notify device here. 76 | default: notify.notify 77 | selector: 78 | text: 79 | printer_print_status_sensor: 80 | name: Printer Print Status Sensor 81 | description: Bambu Lab printer print status sensor 82 | selector: 83 | entity: 84 | filter: 85 | - integration: bambu_lab 86 | domain: sensor 87 | device_class: enum 88 | printer_current_stage_sensor: 89 | name: Printer Current Stage Sensor 90 | description: Bambu Lab printer current stage sensor 91 | selector: 92 | entity: 93 | filter: 94 | - integration: bambu_lab 95 | domain: sensor 96 | device_class: enum 97 | printer_camera: 98 | name: Printer Camera Entity 99 | description: Bambu Lab printer camera entity 100 | selector: 101 | entity: 102 | filter: 103 | - domain: camera 104 | printer_pause_button: 105 | name: Printer Pause Button Entity 106 | description: Bambu Lab printer pause button entity 107 | selector: 108 | entity: 109 | filter: 110 | - integration: bambu_lab 111 | domain: button 112 | printer_resume_button: 113 | name: Printer Resume Button Entity 114 | description: Bambu Lab printer resume button entity 115 | selector: 116 | entity: 117 | filter: 118 | - integration: bambu_lab 119 | domain: button 120 | printer_stop_button: 121 | name: Printer Stop Button Entity 122 | description: Bambu Lab printer stop button entity 123 | selector: 124 | entity: 125 | filter: 126 | - integration: bambu_lab 127 | domain: button 128 | printer_chamber_light: 129 | name: Printer Chamber Light 130 | description: Bambu Lab printer chamber light 131 | selector: 132 | entity: 133 | filter: 134 | - integration: bambu_lab 135 | domain: light 136 | 137 | variables: 138 | HOME_ASSISTANT_HOST_VAR: !input home_assistant_host 139 | PRINTER_CAMERA_VAR: !input printer_camera 140 | FAILURE_ACTION_VAR: !input failure_action 141 | NOTIFICATION_SETTINGS_VAR: !input notification_settings 142 | DETECTION_FREQUENCY_VAR: !input detection_frequency 143 | mode: single 144 | max_exceeded: silent 145 | trigger: 146 | # Print start trigger 147 | - platform: state 148 | entity_id: 149 | - !input printer_current_stage_sensor 150 | to: printing 151 | id: BAMBU_LAB_PRINTER_STAGE_CHANGE 152 | 153 | # Notification action triggers 154 | - platform: event 155 | event_type: mobile_app_notification_action 156 | id: BAMBU_LAB_PAUSE_PRINTING 157 | event_data: 158 | action: BAMBU_LAB_PAUSE_PRINTING 159 | - platform: event 160 | event_type: mobile_app_notification_action 161 | id: BAMBU_LAB_RESUME_PRINTING 162 | event_data: 163 | action: BAMBU_LAB_RESUME_PRINTING 164 | - platform: event 165 | event_type: mobile_app_notification_action 166 | id: BAMBU_LAB_STOP_PRINTING 167 | event_data: 168 | action: BAMBU_LAB_STOP_PRINTING 169 | 170 | # Detection trigger 171 | - trigger: time_pattern 172 | id: BAMBU_LAB_DETECTION_TRIGGER 173 | seconds: !input detection_frequency 174 | condition: [ ] 175 | action: 176 | - choose: 177 | # Print start actions 178 | - conditions: 179 | - condition: trigger 180 | id: BAMBU_LAB_PRINTER_STAGE_CHANGE 181 | sequence: 182 | - service: number.set_value 183 | data: 184 | value: 0 185 | target: 186 | entity_id: 187 | - number.bambu_lab_p1_spaghetti_detection_current_frame_number 188 | - number.bambu_lab_p1_spaghetti_detection_ewm_mean 189 | - number.bambu_lab_p1_spaghetti_detection_rolling_mean_short 190 | - number.bambu_lab_p1_spaghetti_detection_rolling_mean_long 191 | - number.bambu_lab_p1_spaghetti_detection_normalized_p 192 | - number.bambu_lab_p1_spaghetti_detection_adjusted_ewm_mean 193 | - number.bambu_lab_p1_spaghetti_detection_p_sum 194 | - if: 195 | - condition: and 196 | conditions: 197 | - condition: state 198 | entity_id: !input printer_chamber_light 199 | state: 'off' 200 | - condition: template 201 | value_template: !input auto_turn_on_light 202 | then: 203 | - service: light.turn_on 204 | target: 205 | entity_id: 206 | - !input printer_chamber_light 207 | 208 | # Notification actions 209 | - conditions: 210 | - condition: trigger 211 | id: 212 | - BAMBU_LAB_PAUSE_PRINTING 213 | - BAMBU_LAB_RESUME_PRINTING 214 | - BAMBU_LAB_STOP_PRINTING 215 | sequence: 216 | - choose: 217 | - conditions: 218 | - condition: trigger 219 | id: 220 | - BAMBU_LAB_PAUSE_PRINTING 221 | sequence: 222 | - service: button.press 223 | data: { } 224 | target: 225 | entity_id: !input printer_pause_button 226 | - conditions: 227 | - condition: trigger 228 | id: BAMBU_LAB_RESUME_PRINTING 229 | sequence: 230 | - service: button.press 231 | data: { } 232 | target: 233 | entity_id: !input printer_resume_button 234 | - conditions: 235 | - condition: trigger 236 | id: BAMBU_LAB_STOP_PRINTING 237 | sequence: 238 | - service: button.press 239 | data: { } 240 | target: 241 | entity_id: !input printer_stop_button 242 | 243 | # Notification actions 244 | - conditions: 245 | - condition: trigger 246 | id: BAMBU_LAB_DETECTION_TRIGGER 247 | sequence: 248 | - if: 249 | - condition: not 250 | conditions: 251 | - condition: state 252 | entity_id: !input printer_print_status_sensor 253 | state: running 254 | then: 255 | - stop: "" 256 | - if: 257 | - condition: template 258 | value_template: >- 259 | {{ now().second % DETECTION_FREQUENCY_VAR | replace("/", "") | int > 0 }} 260 | then: 261 | - stop: "" 262 | - if: 263 | - condition: and 264 | conditions: 265 | - condition: state 266 | entity_id: !input printer_chamber_light 267 | state: 'off' 268 | - condition: template 269 | value_template: !input auto_turn_on_light 270 | then: 271 | - service: light.turn_on 272 | target: 273 | entity_id: 274 | - !input printer_chamber_light 275 | - service: bambu_lab_p1_spaghetti_detection.predict 276 | data: 277 | obico_host: !input obico_host 278 | obico_auth_token: !input obico_auth_token 279 | image_url: "{{ HOME_ASSISTANT_HOST_VAR }}{{ state_attr(PRINTER_CAMERA_VAR, 'entity_picture') }}" 280 | response_variable: result 281 | 282 | - service: number.set_value 283 | data: 284 | value: "{{ result.result.detections | map(attribute=1) | sum | float }}" 285 | target: 286 | entity_id: number.bambu_lab_p1_spaghetti_detection_p_sum 287 | 288 | - service: number.set_value 289 | data: 290 | value: "{{ states('number.bambu_lab_p1_spaghetti_detection_current_frame_number') | float + 1 }}" 291 | target: 292 | entity_id: number.bambu_lab_p1_spaghetti_detection_current_frame_number 293 | 294 | - service: number.set_value 295 | data: 296 | value: "{{ states('number.bambu_lab_p1_spaghetti_detection_lifetime_frame_number') | float + 1 }}" 297 | target: 298 | entity_id: number.bambu_lab_p1_spaghetti_detection_lifetime_frame_number 299 | 300 | - service: number.set_value 301 | data: 302 | value: "{{ (states('number.bambu_lab_p1_spaghetti_detection_p_sum') | float) * (2 / (12 + 1)) + (states('number.bambu_lab_p1_spaghetti_detection_ewm_mean') | float) * (1 - (2 / (12 + 1))) }}" 303 | target: 304 | entity_id: number.bambu_lab_p1_spaghetti_detection_ewm_mean 305 | 306 | - service: number.set_value 307 | data: 308 | value: "{{ (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_short') | float) + ((states('number.bambu_lab_p1_spaghetti_detection_p_sum') | float) - (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_short') | float)) / (310 if 310 <= (states('number.bambu_lab_p1_spaghetti_detection_current_frame_number') | float) else (states('number.bambu_lab_p1_spaghetti_detection_current_frame_number') | float) + 1) }}" 309 | target: 310 | entity_id: number.bambu_lab_p1_spaghetti_detection_rolling_mean_short 311 | 312 | - service: number.set_value 313 | data: 314 | value: "{{ (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_long') | float) + ((states('number.bambu_lab_p1_spaghetti_detection_p_sum') | float) - (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_long') | float)) / (7200 if 7200 <= (states('number.bambu_lab_p1_spaghetti_detection_lifetime_frame_number') | float) else (states('number.bambu_lab_p1_spaghetti_detection_lifetime_frame_number') | float) + 1) }}" 315 | entity_id: number.bambu_lab_p1_spaghetti_detection_rolling_mean_long 316 | 317 | - if: 318 | - condition: numeric_state 319 | entity_id: number.bambu_lab_p1_spaghetti_detection_current_frame_number 320 | below: 30 321 | then: 322 | - stop: "" 323 | alias: if current_frame_num < 30 324 | 325 | - service: number.set_value 326 | data: 327 | value: >- 328 | {{ (states('number.bambu_lab_p1_spaghetti_detection_ewm_mean') | float) - (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_long') | float) }} 329 | target: 330 | entity_id: number.bambu_lab_p1_spaghetti_detection_adjusted_ewm_mean 331 | 332 | - service: number.set_value 333 | data: 334 | value: >- 335 | {{ ((states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_short') | float) - (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_long') | float)) * 3.8 }} 336 | target: 337 | entity_id: number.bambu_lab_p1_spaghetti_detection_rolling_mean_diff 338 | 339 | - service: number.set_value 340 | data: 341 | value: >- 342 | {{ min(0.78, max(0.33, (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_diff') | float))) }} 343 | target: 344 | entity_id: number.bambu_lab_p1_spaghetti_detection_thresh_warning 345 | 346 | - service: number.set_value 347 | data: 348 | value: >- 349 | {{ (states('number.bambu_lab_p1_spaghetti_detection_thresh_warning') | float) * 1.75 }} 350 | target: 351 | entity_id: number.bambu_lab_p1_spaghetti_detection_thresh_failure 352 | 353 | - service: number.set_value 354 | data: 355 | value: >- 356 | {{ (states('number.bambu_lab_p1_spaghetti_detection_ewm_mean') | float) - (states('number.bambu_lab_p1_spaghetti_detection_rolling_mean_long') | float) }} 357 | target: 358 | entity_id: number.bambu_lab_p1_spaghetti_detection_p 359 | 360 | - choose: 361 | - conditions: 362 | - condition: numeric_state 363 | entity_id: number.bambu_lab_p1_spaghetti_detection_p 364 | above: number.bambu_lab_p1_spaghetti_detection_thresh_failure 365 | sequence: 366 | - service: number.set_value 367 | data: 368 | value: >- 369 | {{ min(1.0, max(2.0 / 3.0, ((((states('number.bambu_lab_p1_spaghetti_detection_p') | float) - (states('number.bambu_lab_p1_spaghetti_detection_thresh_failure') | float)) * (1.0 - 2.0 / 3.0)) / ((states('number.bambu_lab_p1_spaghetti_detection_thresh_failure') | float) * 1.5 - (states('number.bambu_lab_p1_spaghetti_detection_thresh_failure') | float))) + 2.0 / 3.0)) }} 370 | target: 371 | entity_id: number.bambu_lab_p1_spaghetti_detection_normalized_p 372 | - conditions: 373 | - condition: numeric_state 374 | entity_id: number.bambu_lab_p1_spaghetti_detection_p 375 | above: number.bambu_lab_p1_spaghetti_detection_thresh_warning 376 | sequence: 377 | - service: number.set_value 378 | data: 379 | value: >- 380 | {{ min(2.0 / 3.0, max(1.0 / 3.0, ((((states('number.bambu_lab_p1_spaghetti_detection_p') | float) - (states('number.bambu_lab_p1_spaghetti_detection_thresh_warning') | float)) * (2.0 / 3.0 - 1.0 / 3.0)) / ((states('number.bambu_lab_p1_spaghetti_detection_thresh_failure') | float) - (states('number.bambu_lab_p1_spaghetti_detection_thresh_warning') | float))) + 1.0 / 3.0)) }} 381 | target: 382 | entity_id: number.bambu_lab_p1_spaghetti_detection_normalized_p 383 | default: 384 | - service: number.set_value 385 | data: 386 | value: >- 387 | {{ min(1.0 / 3.0, max(0, ((states('number.bambu_lab_p1_spaghetti_detection_p') | float) * 1.0 / 3.0) / (states('number.bambu_lab_p1_spaghetti_detection_thresh_warning') | float))) }} 388 | target: 389 | entity_id: number.bambu_lab_p1_spaghetti_detection_normalized_p 390 | 391 | # if adjusted_ewm_mean < THRESHOLD_LOW 392 | - if: 393 | - condition: numeric_state 394 | entity_id: number.bambu_lab_p1_spaghetti_detection_adjusted_ewm_mean 395 | below: 0.38 396 | then: 397 | - stop: "" 398 | 399 | # if adjusted_ewm_mean <= THRESHOLD_HIGH and adjusted_ewm_mean <= rolling_mean_diff 400 | - if: 401 | - condition: and 402 | conditions: 403 | - condition: numeric_state 404 | entity_id: number.bambu_lab_p1_spaghetti_detection_adjusted_ewm_mean 405 | below: 0.78 406 | - condition: numeric_state 407 | entity_id: number.bambu_lab_p1_spaghetti_detection_adjusted_ewm_mean 408 | below: number.bambu_lab_p1_spaghetti_detection_rolling_mean_diff 409 | then: 410 | - stop: "" 411 | 412 | # if now() - last_notify_time < 1min 413 | - if: 414 | - condition: template 415 | value_template: >- 416 | {{ now() - states('datetime.bambu_lab_p1_spaghetti_detection_last_notify_time') | as_datetime | as_local < timedelta(minutes=1) }} 417 | then: 418 | - stop: "" 419 | alias: >- 420 | if now() - last_notify_time < 1min 421 | 422 | - choose: 423 | - conditions: 424 | - condition: template 425 | value_template: "{{ FAILURE_ACTION_VAR == 'pause' }}" 426 | sequence: 427 | - service: button.press 428 | data: { } 429 | target: 430 | entity_id: !input printer_pause_button 431 | - conditions: 432 | - condition: template 433 | value_template: "{{ FAILURE_ACTION_VAR == 'stop' }}" 434 | sequence: 435 | - service: button.press 436 | data: { } 437 | target: 438 | entity_id: !input printer_stop_button 439 | 440 | - choose: 441 | - conditions: 442 | - condition: template 443 | value_template: "{{ NOTIFICATION_SETTINGS_VAR == 'critical' }}" 444 | sequence: 445 | - service: !input notification_service 446 | data: 447 | title: "Bambu Lab - Spaghetti Detected" 448 | message: "Confidence: {{ (states('number.bambu_lab_p1_spaghetti_detection_normalized_p') | float * 100) | int }}%" 449 | data: 450 | image: "{{ HOME_ASSISTANT_HOST_VAR }}{{ state_attr(PRINTER_CAMERA_VAR, 'entity_picture') }}" 451 | ttl: 0 452 | priority: high 453 | channel: alarm_stream 454 | push: 455 | sound: 456 | name: default 457 | critical: 1 458 | volume: 0.75 459 | actions: 460 | - action: BAMBU_LAB_RESUME_PRINTING 461 | title: Resume Printing 462 | - action: BAMBU_LAB_STOP_PRINTING 463 | title: Stop Printing 464 | - conditions: 465 | - condition: template 466 | value_template: "{{ NOTIFICATION_SETTINGS_VAR == 'standard' }}" 467 | sequence: 468 | - service: !input notification_service 469 | data: 470 | title: "Bambu Lab - Spaghetti Detected" 471 | message: "Confidence: {{ (states('number.bambu_lab_p1_spaghetti_detection_normalized_p') | float * 100) | int }}%" 472 | data: 473 | image: "{{ HOME_ASSISTANT_HOST_VAR }}{{ state_attr(PRINTER_CAMERA_VAR, 'entity_picture') }}" 474 | actions: 475 | - action: BAMBU_LAB_RESUME_PRINTING 476 | title: Resume Printing 477 | - action: BAMBU_LAB_STOP_PRINTING 478 | title: Stop Printing 479 | - service: number.set_value 480 | data: 481 | value: 0 482 | target: 483 | entity_id: 484 | - number.bambu_lab_p1_spaghetti_detection_current_frame_number 485 | - number.bambu_lab_p1_spaghetti_detection_ewm_mean 486 | - number.bambu_lab_p1_spaghetti_detection_rolling_mean_short 487 | - number.bambu_lab_p1_spaghetti_detection_rolling_mean_long 488 | - number.bambu_lab_p1_spaghetti_detection_normalized_p 489 | - number.bambu_lab_p1_spaghetti_detection_adjusted_ewm_mean 490 | - number.bambu_lab_p1_spaghetti_detection_p_sum 491 | - service: datetime.set_value 492 | data: 493 | datetime: >- 494 | {{ now() }} 495 | target: 496 | entity_id: datetime.bambu_lab_p1_spaghetti_detection_last_notify_time 497 | 498 | 499 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------