# speech: the agent's ears and voice, as a capability over Cap'n Web.
# Tools come from the flake: nix develop --command make test
#   sudo make install   # on the home server: the server, its models, its key, and its unit

WHISPER = https://huggingface.co/ggerganov/whisper.cpp/resolve/main
MODEL = cache/ggml-base.en.bin
VOICES = https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/danny/low
VOICE = cache/en_US-danny-low.onnx
PORT = 18024
PHRASE = Put on the ballgame.
UA = pdtv26-speech-setup (curl)
FLAKE = ..
# Where it listens, and the private network's addresses: the only ones it answers. A tailnet's, by default.
SERVE_PORT = 8024
RANGES = 100.64.0.0/10 fd7a:115c:a1e0::/48
LIB = /var/lib/pdtv26-speech
ETC = /etc/pdtv26-speech
UNIT = /etc/systemd/system/pdtv26-speech.service

.PHONY: help test smoke app install
.DELETE_ON_ERROR:

## list targets
help:
	@awk -f ../make-help.awk $(MAKEFILE_LIST)

## the unit tests, in Nix's build sandbox: no network, no models
test:
	nix build -L --no-link ..#speech-js

## the server and clients, with node, sox, whisper, and piper
cache/speech: $(wildcard *.js *.sh *.nix package*.json) ../flake.nix ../flake.lock
	nix build -L --out-link $@ ..#speech

## whisper's English model (about 150 MB; once, kept in cache/)
$(MODEL):
	mkdir -p cache
	curl -fsSL -A '$(UA)' -o $@ $(WHISPER)/$(notdir $@)

## a piper voice and its config (once, kept in cache/)
cache/en_US-danny-low.%:
	mkdir -p cache
	curl -fsSL -A '$(UA)' -o $@ $(VOICES)/$(notdir $@)

## a round trip through a real server: speak PHRASE, hear it back, compare
smoke: cache/speech $(MODEL) $(VOICE) $(VOICE).json
	./smoke.sh cache/speech/bin $(MODEL) $(VOICE) $(PORT) '$(PHRASE)'

## the server, installed: a GC root in LIB
app:
	install -d $(LIB)
	nix build --out-link $(LIB)/app '$(FLAKE)#speech'

$(LIB)/models/%:
	install -d -m 755 $(dir $@)
	curl -fsSL -A '$(UA)' -o $@ $(WHISPER)/$*
	chmod 644 $@

$(LIB)/voices/en_US-danny-low.%:
	install -d -m 755 $(dir $@)
	curl -fsSL -A '$(UA)' -o $@ $(VOICES)/$(notdir $@)
	chmod 644 $@

## the key the box presents: 160 random bits, root's alone; systemd hands the service a copy
$(ETC)/speech-key:
	install -d -m 700 $(dir $@)
	umask 077; head -c 20 /dev/urandom | base32 | tr A-Z a-z | tr -d = > $@

$(ETC)/settings: Makefile
	install -d -m 700 $(dir $@)
	printf 'PORT=%s\nMODEL=%s\nVOICE=%s\n' $(SERVE_PORT) $(notdir $(MODEL)) $(basename $(notdir $(VOICE))) > $@

$(UNIT): pdtv26-speech.service Makefile
	sed 's|@ranges@|$(RANGES)|' $< > $@

## build, fetch the models, make the key if there's none, install the unit, and (re)start it
install: app $(LIB)/models/$(notdir $(MODEL)) $(LIB)/voices/$(notdir $(VOICE)) $(LIB)/voices/$(notdir $(VOICE)).json $(ETC)/speech-key $(ETC)/settings $(UNIT)
	systemctl daemon-reload
	systemctl enable pdtv26-speech
	systemctl restart pdtv26-speech
	sleep 2; systemctl --no-pager status pdtv26-speech | grep -E '●|Active|listening'
