Files
Twarner491 2ec45b9138 AvianVisitors hardening pass — install via fork's newinstaller
Restructures the install so users run ONE command. The fork's
newinstaller.sh clones this repo (instead of upstream Nachtzuster) and
runs BirdNET-Pi's installer. install_services.sh symlinks the avian/
overlay into the Caddy site root, so http://birdnet.local/avian/ comes
up after reboot with no Caddy config needed.

Reviewer-flagged fixes:

Frontend (avian/frontend/apt.js)
- Switch all API paths from /api/*.json (which didn't route) to relative
  action-based URLs (./api/birdnet-api.php?action=recent etc.).
- Fetch ./masks.json + ./dims.json relatively (were /avian/*.json).
- Replace every innerHTML user-content sink with createElement +
  textContent + setAttribute — species labels are user-editable in
  BirdNET-Pi, so untrusted.
- Add esc() helper for the few remaining innerHTML attribute contexts.
- fetchJson throws on non-200 (was silently parsing 404 HTML as JSON).
- Defensive null-check in loadMask if MASKS hasn't loaded.

Backend (avian/api/*.php)
- birdnet-api.php now derives DB_PATH from dirname(__DIR__, 3) so any
  BirdNET-Pi install user works (no hardcoded /home/birdnet).
- recording/spectrogram/cutout use getenv('HOME') for the same reason.
- cutout.php reworked as the canonical image resolver: bundled
  illustration → bundled cutout → cached rembg → fresh
  Wikipedia+rembg, with the binomial regex guard and atomic rename
  on cache write. Wikipedia URL host pinned to wikimedia.org /
  wikipedia.org to block SSRF.
- Stale 'X-BirdNET-Proxy-Token' auth claims removed everywhere.

Pregen (avian/scripts/pregen.py)
- Gemini key moved from URL query to x-goog-api-key header.
- Model bumped to gemini-2.5-flash-image-preview.
- Bounded retry on 429 + 5xx with Retry-After honoured.
- Default --sleep raised from 1s to 4s (under free-tier RPM).
- Unified parser handles |/_/comma in all three input modes.
- responseModalities now [TEXT, IMAGE] (was IMAGE-only).
- --poses validated against POSES keys.
- ASCII [ok]/[fail] markers (was ✓/✗ — Windows console crash).
- Surfaces finishReason + blockReason on safety blocks.

Prompt template
- 'Two placeholders' typo → three.
- 'warm paper' / 'transparent background' contradiction resolved.

Forwarding
- mqtt-bridge.py: paho-mqtt 2.x CallbackAPIVersion compat shim.
- avian-mqtt.service: dropped broken %i, set User=birdnet + %h path.
- forwarding/README.md uses the actual action-based URLs.

README
- One-line install via curl … newinstaller.sh.
- No more 'install BirdNET-Pi separately' step (our fork does it).
- License section uses absolute github.com links.
- bird.onethreenine.net replaces the not-yet-existent project writeup.
- docs/thumb.png replaced with the 24-bird Twitter capture.

Removed
- avian/caddy/ and avian/scripts/install.sh — no longer needed; the
  overlay symlink in install_services.sh handles everything.
2026-05-28 10:49:41 -07:00

54 lines
1.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Poll AvianVisitors' recent-detections endpoint once a minute and publish
each new species to MQTT. Edit BROKER, TOPIC_PREFIX, and PI_URL below."""
import json
import time
import urllib.request
import paho.mqtt.client as mqtt # sudo pip3 install paho-mqtt
BROKER = "homeassistant.local"
PORT = 1883
USER = ""
PASSWORD = ""
TOPIC_PREFIX = "birdnet"
PI_URL = "http://birdnet.local/avian/api/birdnet-api.php?action=recent&hours=1"
seen_keys: set[str] = set()
def slugify(s: str) -> str:
return "".join(c.lower() if c.isalnum() else "-" for c in s).strip("-")
def loop(client: mqtt.Client) -> None:
while True:
try:
with urllib.request.urlopen(PI_URL, timeout=10) as r:
payload = json.loads(r.read())
for s in payload.get("species", []):
key = f"{s['sci']}|{s.get('last_seen','')}"
if key in seen_keys:
continue
seen_keys.add(key)
topic = f"{TOPIC_PREFIX}/{slugify(s['sci'])}"
client.publish(topic, json.dumps(s), qos=0, retain=False)
print(f"published {topic}: {s.get('com')}")
except Exception as e:
print(f"poll error: {e}")
time.sleep(60)
def main() -> None:
# paho-mqtt 2.x requires CallbackAPIVersion; the constructor below
# also works on 1.x (the kwarg is just ignored). Pin to VERSION2 so
# we get the modern callback signatures going forward.
try:
client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
except AttributeError: # paho-mqtt 1.x
client = mqtt.Client()
if USER:
client.username_pw_set(USER, PASSWORD)
client.connect(BROKER, PORT, keepalive=60)
client.loop_start()
loop(client)
if __name__ == "__main__":
main()