Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ Enter your Protect controller's IP and an optional vision server URL (leave it b

</details>

On x86-64 Linux, both installers offer OpenVINO inference and VA-API decoding when they detect an Intel GPU during interactive setup. Set `KEYSTONE_ACCEL=auto` before running either installer to use detection in an unattended install, or `KEYSTONE_ACCEL=intel` (`openvino` is an alias) to request the Intel runtime explicitly. New unattended installs use CPU packages when the variable is unset. Upgrades preserve an installed OpenVINO runtime unless you select `KEYSTONE_ACCEL=cpu`.

The Proxmox installer maps the Intel render node and its card node when available into the unprivileged container. If the host does not support `pct set --dev0`, use a Proxmox VE release with LXC Device Passthrough or configure an unprivileged device mapping manually. The render node needs read/write access for the guest's `render` group, and the card node for `video`. For an existing install, set `acceleration.ffmpeg_hwaccel: auto` in `/etc/keystone/config.yaml` and point `acceleration.ffmpeg_device` to the mapped render node if it differs from `/dev/dri/renderD128`.

### Unraid

Add the template from the Unraid terminal (until it's in Community Applications):
Expand Down Expand Up @@ -443,19 +447,18 @@ Off by default so existing installs don't kick off a multi-hour backfill unexpec

### Optional Intel GPU / NPU acceleration (OpenVINO & VA-API)

Keystone defaults to CPU and software video decode on Linux so it works everywhere with no drivers. On Intel Core Ultra, Arc, or N100 hosts, you can offload ONNX models to OpenVINO and AI Port video decode to VA-API:

```bash
pip install -e ".[openvino]"
```
Keystone defaults to CPU and software video decode with the standard Linux installation. The [Linux and Proxmox installers](#proxmox-lxc-debian-or-ubuntu) can install the Intel runtime for OpenVINO inference and VA-API decoding on hosts such as Intel Core Ultra, Arc, or N100.

```yaml
acceleration:
enabled: true # Set false for CPU inference and software video decode
provider: auto # auto | cpu | openvino | coreml | cuda | migraphx
openvino_device: "AUTO:GPU,CPU" # GPU | NPU | CPU | AUTO:GPU,CPU | AUTO:NPU,GPU,CPU
ffmpeg_hwaccel: auto # none | auto | vaapi | videotoolbox (AI Port decode only)
```

Set `acceleration.enabled: false` or `KEYSTONE_ACCEL_ENABLED=false` in Keystone's service environment to force CPU inference and software decoding regardless of the backend settings. The default is `true`, which allows the configured providers to be used when available. When using `scripts/install.sh` or `scripts/proxmox-lxc.sh` before the next versioned release is tagged, set `KEYSTONE_REF=main` so the installed Keystone package includes `acceleration.enabled`.

If OpenVINO or VA-API fails to initialize, Keystone logs a warning and falls back to CPU automatically. Active providers show up on the status dashboard and in `/api/status`.

<details>
Expand Down
1 change: 1 addition & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ vision:
# Hardware acceleration for ONNX Runtime and AI Port FFmpeg decode.
# Install OpenVINO support with: pip install -e ".[openvino]" (or replace onnxruntime with onnxruntime-openvino).
acceleration:
enabled: true # Set false for CPU inference and software video decode
provider: auto # auto | cpu | openvino | coreml | cuda | migraphx (CUDA and MIGraphX require an explicit selection)
cpu_models: [] # Optional model labels from /api/status inference, e.g. ["face:w600k_r50"]
openvino_device: "AUTO:GPU,CPU" # GPU | NPU | CPU | AUTO:GPU,CPU | AUTO:NPU,GPU,CPU (use GPU directly on Intel xe GPUs with OpenVINO 2025.4)
Expand Down
244 changes: 194 additions & 50 deletions scripts/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
# KEYSTONE_FACES_ENABLED true/false — Face recognition, InsightFace non-commercial (default: N)
# KEYSTONE_AIPORT_ENABLED true/false — Virtual AI Port for ONVIF / legacy cameras (default: N)
# KEYSTONE_WEB_BIND_HOST Dashboard listen IP (default: 127.0.0.1; set 0.0.0.0 for LAN access)
# KEYSTONE_ACCEL cpu | intel | openvino (alias for intel) | auto (detect Intel GPU)
# Unset: preserve OpenVINO on upgrades, offer Intel on interactive installs,
# or use CPU packages for new non-interactive installs.
# KEYSTONE_REF Git tag or branch to install (default: the newest release)
# KEYSTONE_SRC Install from this local checkout instead of GitHub
set -euo pipefail
Expand Down Expand Up @@ -56,9 +59,73 @@ write_if_changed() {
rm -f "$tmp"
}

ask_yn() {
local prompt=$1 default=$2 hint answer
if [ "$default" = true ]; then hint="Y/n"; else hint="y/N"; fi
while true; do
answer=$(ask " $prompt [$hint]: ")
case "$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')" in
"") printf '%s' "$default"; return 0 ;;
y | yes) printf 'true'; return 0 ;;
n | no) printf 'false'; return 0 ;;
*) printf ' Please enter y or n.\n' >&2 ;;
esac
done
}

keystone_intel_render_node() {
local dri=${1:-/dev/dri} drm=${2:-/sys/class/drm} node vendor
[ "$(uname -sm)" = "Linux x86_64" ] || return 1
for node in "$dri"/renderD*; do
[ -e "$node" ] || continue
if read -r vendor <"$drm/${node##*/}/device/vendor" && [ "$vendor" = 0x8086 ]; then
printf '%s\n' "$node"
return 0
fi 2>/dev/null
done
return 1
}

keystone_resolve_accel() {
local interactive=$1 has_openvino=$2 requested=${KEYSTONE_ACCEL:-}
accel_mode=cpu
accel_render_node=""
case "$requested" in
cpu) return 0 ;;
"" | auto | intel | openvino) ;;
*) die "Invalid KEYSTONE_ACCEL: '$requested' (expected cpu, intel, openvino, or auto)." ;;
esac
if [ "$has_openvino" = true ]; then
requested=intel
elif [ -z "$requested" ] && [ "$interactive" = 0 ]; then
return 0
fi

accel_render_node=$(keystone_intel_render_node) || true
case "$requested" in
intel | openvino)
if [ "$has_openvino" = true ] || [ -n "$accel_render_node" ] || [ "$(uname -sm)" = "Linux x86_64" ]; then
accel_mode=intel
else
printf 'Intel GPU setup requires Linux x86_64. Using CPU packages.\n' >&2
fi
;;
auto)
if [ -n "$accel_render_node" ]; then accel_mode=intel; fi
;;
"")
if [ -n "$accel_render_node" ] &&
[ "$(ask_yn "Enable Intel GPU acceleration (OpenVINO + VA-API)" true)" = true ]; then
accel_mode=intel
fi
;;
esac
}

# Shared by install.sh and proxmox-lxc.sh (sourced with KEYSTONE_INSTALL_LIB_ONLY=1).
# Populates controller, vision_provider, vision_url, vision_model, vision_api_key,
# stt_enabled, lpr_enabled, enhance_enabled, faces_enabled, aiport_enabled, and web_bind_host.
# stt_enabled, lpr_enabled, enhance_enabled, faces_enabled, aiport_enabled, web_bind_host,
# accel_mode, and accel_render_node.
keystone_collect_setup() {
local py=${1:-python3}
local env_controller=0 env_vision=0 interactive=1 choice
Expand All @@ -83,20 +150,6 @@ keystone_collect_setup() {
esac
}

_ask_yn() {
local prompt=$1 default=$2 hint answer
if [ "$default" = true ]; then hint="Y/n"; else hint="y/N"; fi
while true; do
answer=$(ask " $prompt [$hint]: ")
case "$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')" in
"") printf '%s' "$default"; return 0 ;;
y | yes) printf 'true'; return 0 ;;
n | no) printf 'false'; return 0 ;;
*) printf ' Please enter y or n.\n' >&2 ;;
esac
done
}

if [ -n "${KEYSTONE_CONTROLLER_IP:-}" ]; then
env_controller=1
controller=$KEYSTONE_CONTROLLER_IP
Expand Down Expand Up @@ -235,7 +288,7 @@ keystone_collect_setup() {
if [ -n "$raw" ]; then
_parse_bool "$env_name" "$raw"
elif [ "$interactive" = 1 ]; then
_ask_yn "$label" "$default_yn"
ask_yn "$label" "$default_yn"
else
printf 'false'
fi
Expand All @@ -251,17 +304,15 @@ keystone_collect_setup() {
web_bind_host=$("$py" -c 'import ipaddress, sys; print(ipaddress.ip_address(sys.argv[1].strip()))' "$KEYSTONE_WEB_BIND_HOST" 2>/dev/null) ||
die "Invalid KEYSTONE_WEB_BIND_HOST: '$KEYSTONE_WEB_BIND_HOST' (expected an IP address such as 127.0.0.1 or 0.0.0.0)."
elif [ "$interactive" = 1 ]; then
if [ "$(_ask_yn "Expose status dashboard on LAN (0.0.0.0:8088; no login, shows recent events)" false)" = true ]; then
if [ "$(ask_yn "Expose status dashboard on LAN (0.0.0.0:8088; no login, shows recent events)" false)" = true ]; then
web_bind_host="0.0.0.0"
fi
fi
keystone_resolve_accel "$interactive" "${2:-false}"
}

write_config() {
local controller vision_provider vision_url vision_model vision_api_key
local stt_enabled lpr_enabled enhance_enabled faces_enabled aiport_enabled web_bind_host contents

keystone_collect_setup "$VENV/bin/python"
local contents

# Pass values via environment rather than argv so API keys stay out of process listings.
contents=$(
Expand All @@ -276,6 +327,8 @@ write_config() {
_KS_FACES="$faces_enabled" \
_KS_AIPORT="$aiport_enabled" \
_KS_WEB_BIND_HOST="$web_bind_host" \
_KS_ACCEL="$accel_mode" \
_KS_RENDER_NODE="${KEYSTONE_ACCEL_FFMPEG_DEVICE:-$accel_render_node}" \
"$VENV/bin/python" - "$SRC_DIR/config.example.yaml" <<'PY'
import os
import re
Expand Down Expand Up @@ -344,6 +397,10 @@ if re.search(r"(?m)^web:\n", contents):
elif bind_host != "127.0.0.1":
separator = "" if contents.endswith("\n") else "\n"
contents = f"{contents}{separator}\nweb:\n bind_host: {bind_yaml}\n"
if os.environ["_KS_ACCEL"] == "intel":
contents = set_field(contents, "acceleration", "ffmpeg_hwaccel", "auto")
if node := os.environ["_KS_RENDER_NODE"]:
contents = set_field(contents, "acceleration", "ffmpeg_device", quote(node))

print(contents, end="")
PY
Expand All @@ -352,6 +409,98 @@ PY
printf '%s\n' "$contents" | write_if_changed "$CONFIG" 0640 root:keystone
}

install_keystone_packages() {
local pip="$VENV/bin/pip" requirements requirement wheel_dir=""
local openvino_args=()
if [ "$accel_mode" = intel ]; then
requirements=$("$VENV/bin/python" - "$SRC_DIR/pyproject.toml" <<'PY'
import sys
import tomllib

with open(sys.argv[1], "rb") as file:
print(*tomllib.load(file)["project"]["optional-dependencies"]["openvino"], sep="\n")
PY
)
while IFS= read -r requirement; do openvino_args+=("$requirement"); done <<<"$requirements"
elif [ "$has_openvino" = true ]; then
# Either wheel's uninstall can remove files owned by the other.
"$pip" uninstall -y onnxruntime onnxruntime-openvino
fi
"$pip" install --quiet --disable-pip-version-check --upgrade "${SRC_DIR}[mqtt]"
if [ "$accel_mode" = intel ]; then
# Download OpenVINO wheels first so a missing wheel (e.g. unsupported Python version)
# never leaves the environment without the working CPU onnxruntime wheel.
wheel_dir=$(mktemp -d)
if ! "$pip" download --quiet --disable-pip-version-check --dest "$wheel_dir" "${openvino_args[@]}"; then
rm -rf "$wheel_dir"
die "Could not download OpenVINO packages for $("$VENV/bin/python" --version 2>&1); keeping the installed CPU runtime. Re-run with KEYSTONE_ACCEL=cpu to install without OpenVINO."
fi
# Removing the CPU wheel deletes shared files even when OpenVINO is already installed.
"$pip" uninstall -y onnxruntime
"$pip" install --quiet --disable-pip-version-check --no-index --find-links "$wheel_dir" --force-reinstall "${openvino_args[@]}"
rm -rf "$wheel_dir"
fi
}

install_intel_drivers() {
[ "$(uname -sm)" = "Linux x86_64" ] || return 0
local package candidate
local packages=()
for package in intel-media-va-driver intel-opencl-icd libze-intel-gpu1 ocl-icd-libopencl1 libva-drm2; do
candidate=$(LC_ALL=C apt-cache policy "$package" | awk '$1 == "Candidate:" {print $2}')
if [ -n "$candidate" ] && [ "$candidate" != "(none)" ]; then
packages+=("$package")
else
printf 'Intel GPU package %s is unavailable in the configured APT repositories.\n' "$package" >&2
fi
done
if [ "${#packages[@]}" -gt 0 ]; then
apt-get install -y -qq --no-install-recommends "${packages[@]}" >/dev/null
fi
}

write_unit() {
local group supplementary_groups=""
if [ "$accel_mode" = intel ]; then
for group in render video; do
if getent group "$group" >/dev/null; then
usermod -aG "$group" keystone
supplementary_groups+="${supplementary_groups:+ }$group"
fi
done
fi

# Settings this script manages for Keystone; config.yaml can't override them.
write_if_changed "$UNIT" 0644 root:root <<EOF || true
[Unit]
Description=Keystone, a virtual AI Key and AI Port for UniFi Protect
Documentation=https://github.com/seeARMS/keystone
After=network-online.target postgresql.service
Wants=network-online.target postgresql.service

[Service]
User=keystone
Group=keystone
${supplementary_groups:+SupplementaryGroups=$supplementary_groups}
Environment=KEYSTONE_CONFIG=$CONFIG
Environment=KEYSTONE_STATE_DIR=/var/lib/keystone
Environment=KEYSTONE_DEVICE_SYNC_POSTGRES_PASSWORD=true
Environment="KEYSTONE_DEVICE_POSTGRES_ADMIN_URL=$ADMIN_URL"
ExecStart=$VENV/bin/keystone run
Restart=on-failure
RestartSec=5
StateDirectory=keystone
StateDirectoryMode=0700
# Binds the AI Port's adoption port, 443, without running as root.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF
}

if [ "${KEYSTONE_INSTALL_LIB_ONLY:-0}" = 1 ]; then
return 0
fi
Expand Down Expand Up @@ -420,41 +569,27 @@ else
fi
fi
[ -x "$VENV/bin/python" ] || python3 -m venv "$VENV"
"$VENV/bin/pip" install --quiet --disable-pip-version-check --upgrade "${SRC_DIR}[mqtt]"
has_openvino=false
if "$VENV/bin/pip" show onnxruntime-openvino >/dev/null 2>&1; then
has_openvino=true
fi
if [ ! -f "$CONFIG" ]; then
keystone_collect_setup "$VENV/bin/python" "$has_openvino"
else
keystone_resolve_accel 0 "$has_openvino"
fi
if [ "$accel_mode" = intel ]; then
say "Installing Intel GPU runtime packages"
install_intel_drivers
fi
install_keystone_packages

if [ ! -f "$CONFIG" ]; then
say "Writing $CONFIG"
write_config
fi

# Settings this script manages for Keystone; config.yaml can't override them.
write_if_changed "$UNIT" 0644 root:root <<EOF || true
[Unit]
Description=Keystone, a virtual AI Key and AI Port for UniFi Protect
Documentation=https://github.com/seeARMS/keystone
After=network-online.target postgresql.service
Wants=network-online.target postgresql.service

[Service]
User=keystone
Group=keystone
Environment=KEYSTONE_CONFIG=$CONFIG
Environment=KEYSTONE_STATE_DIR=/var/lib/keystone
Environment=KEYSTONE_DEVICE_SYNC_POSTGRES_PASSWORD=true
Environment="KEYSTONE_DEVICE_POSTGRES_ADMIN_URL=$ADMIN_URL"
ExecStart=$VENV/bin/keystone run
Restart=on-failure
RestartSec=5
StateDirectory=keystone
StateDirectoryMode=0700
# Binds the AI Port's adoption port, 443, without running as root.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF
write_unit

# Read settings back through Keystone's own loader with a clean environment so shell
# KEYSTONE_* variables can't differ from what the systemd unit will actually load.
Expand Down Expand Up @@ -537,6 +672,7 @@ say "$version is running on $ip"
env -i PATH="$PATH" KEYSTONE_CONFIG="$CONFIG" "$VENV/bin/python" - "$CONFIG" "$ip" <<'PY'
import sys
from keystone.config import load_config
from keystone.ort_runtime import openvino_available

config_path, ip = sys.argv[1], sys.argv[2]
c = load_config()
Expand All @@ -545,6 +681,14 @@ emb_backend = (c.embeddings.backend or "clip").lower()
emb_label = "CLIP" if emb_backend == "clip" else emb_backend

print(f"\nWhat's enabled (edit {config_path} anytime):")
if getattr(c.acceleration, "enabled", True): # Also support older KEYSTONE_REF releases.
openvino = "available" if openvino_available() else "unavailable"
print(
f" Hardware acceleration (provider: {c.acceleration.provider}, "
f"OpenVINO: {openvino}, AI Port decode: {c.acceleration.ffmpeg_hwaccel})"
)
else:
print(" Hardware acceleration (off; CPU inference and software decode)")
if c.embeddings.enabled:
print(f" ✓ Find Anything search ({emb_label} embeddings)")
else:
Expand Down
Loading
Loading