Turn a Galaxy Watch into a wearable AI note taker. Local transcription with speaker labels, summaries from the AI you already pay for.
Python
Voice Capture: Wear OS watch recorder with local transcription and AI summaries
Alex54f02496b5c7
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..e009398--- /dev/null+++ b/.env.example@@ -0,0 +1,29 @@+# Copy to .env and fill in. .env is gitignored; never commit it.++# Bearer token the watch sends with every upload. `python launch.py token` creates it for you.+INGEST_TOKEN=++# Hugging Face read token, for speaker labels (free). Accept the model terms first:+# https://huggingface.co/pyannote/speaker-diarization-community-1+# Without it everything still works, but every line is labeled as one speaker.+HF_TOKEN=++# --- Network ---------------------------------------------------------------+# Wi-Fi mode (default in SETUP.md): the watch uploads to this PC on your home network.+BIND_HOST=0.0.0.0+PORT=8808+# Set to 1 to open the dashboard from other devices on your home network (no login in front of it).+DASHBOARD_ON_LAN=++# Tunnel mode (optional, upload from anywhere): set BIND_HOST=127.0.0.1 and the hostname the watch+# uploads to. Requests on that hostname can only reach the watch API.+INGEST_HOST=+# Cloudflare Access service token, if the upload hostname sits behind Access.+CF_ACCESS_CLIENT_ID=+CF_ACCESS_CLIENT_SECRET=++# --- Optional --------------------------------------------------------------+# Private iCal link of your calendar, for "record my meetings" in auto mode.+CALENDAR_ICS_URL=+# API key for the "API key or local model" summary provider. The dashboard writes this for you.+SUMMARY_API_KEY=diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..bc68e9b--- /dev/null+++ b/.gitattributes@@ -0,0 +1,2 @@+watch/gradlew text eol=lf+*.bat text eol=crlfdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..469eeee--- /dev/null+++ b/.gitignore@@ -0,0 +1,14 @@+.env+.venv/+data/+dist/+config.json+__pycache__/+*.pyc+watch/local.properties+watch/.gradle/+watch/.kotlin/+watch/build/+watch/app/build/+.idea/+*.logdiff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..7e4d1f9--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,63 @@+# Instructions for coding agents++This repo is a self-hosted voice recorder: a Wear OS watch app uploads audio to a Windows PC, which transcribes it (WhisperX, local GPU), summarizes it with the user's chosen AI provider, and shows it in a local dashboard. [README.md](README.md) explains the product. [SETUP.md](SETUP.md) has every command.++When the user says "set this up" (or similar), run the setup below. Work through it in order, verify each step before moving on, and tell the user in one line what you are doing at each step.++## Rules++- Never print, log or commit the contents of `.env`. Refer to keys by name.+- Never run `git add .env` or anything under `data/`.+- Commands that need administrator rights (the firewall rule) or install software: show the user the exact command and get a yes first.+- Don't change how the network is exposed beyond what SETUP.md says. Default is Wi-Fi mode. Only set up tunnel mode if the user asks.+- If a step fails twice, stop and show the user the error. Don't work around it by weakening a check.+- Windows only. If the machine isn't Windows with an NVIDIA GPU, say so before installing anything.++## Setup steps++1. **Check the machine.** Run `nvidia-smi`, `py -3.12 --version`, `ffmpeg -version`, `adb version`. Offer the `winget` installs from SETUP.md step 1 for anything missing.+2. **Install the PC side.** SETUP.md step 2. Torch from the CUDA index first, then `requirements.txt`. Verify: `.venv\Scripts\python.exe -c "import torch, whisperx; print(torch.cuda.is_available())"` prints `True`.+3. **Settings file.** Copy `.env.example` to `.env` if there isn't one, then `python launch.py token`.+4. **Ask the user** (one question, not one at a time):+ - Which AI should write the summaries: Claude subscription, ChatGPT subscription, an API key, or a free local model?+ - Do they have a Hugging Face read token for speaker labels? If not, give them the two links from SETUP.md step 3 and wait. They can skip it and add it later.+ Have the user paste secrets into `.env` themselves, or write them there for the user without echoing them back.+5. **Start it.** `python launch.py start`. Verify: `python launch.py status` shows the worker alive.+6. **Set the provider.** Either walk the user through Settings > Summaries in the dashboard, or set it over the local API:+ `PUT http://127.0.0.1:8808/api/settings` with `{"summary": {"provider": "...", "model": "...", "base_url": "...", "api_key": "..."}}`.+ Providers: `claude_subscription`, `codex_subscription`, `openai_compatible`. Then `POST /api/summary/test` and check for `"ok": true`. If it fails, the `error` field says why.+ - Claude: `claude auth status` must show logged in. If not, the user runs `claude login`.+ - Codex: `codex --version` must work. If not, `npm i -g @openai/codex`, then the user runs `codex login`.+ - Local: check that Ollama (`http://localhost:11434/v1/models`) or LM Studio (`http://localhost:1234/v1/models`) answers and use a model name from that list.+7. **Prove the PC side.** Upload a short speech clip: `POST /api/upload` with a `file` form field. Poll `GET /api/conversations/<recording_id>` until `status` is `done`. The first run downloads models and can take several minutes. Show the user the title and summary.+8. **Pair the watch.** This needs the user's hands. Give them SETUP.md step 5, one instruction at a time, and run the `adb pair` and `adb connect` commands for them with the numbers they read out. Verify with `adb devices`.+9. **Firewall.** SETUP.md step 6. Admin command, so ask first.+10. **Install the watch app.** If `dist/voice-capture-watch.apk` is missing, ask the user to download it from the Releases page, or build it (`cd watch; .\gradlew.bat assembleDebug`, needs Android Studio and a `watch/local.properties` with `sdk.dir`). Then `python tools/setup_watch.py`.+11. **Prove the whole path.** Ask the user to record twenty seconds on the watch. Watch `data\server.log` for a `POST /api/v1/chunks` line, then wait for the conversation to reach `done`.+12. **Finish.** Tell the user to enroll their voice (Settings > Voices), map the Home key double press to Quick Rec, and turn Wireless debugging off. Mention the battery cost of auto mode and that recording laws vary.++## Map of the code++| File | Job |+|---|---|+| `server.py` | FastAPI. Watch API under `/api/v1/*` (bearer token), dashboard API, static files, the network gate |+| `worker.py` | The pipeline loop: transcribe, label speakers, stitch, summarize, daily digest |+| `transcribe.py` | WhisperX engine, lazy model load, idle unload |+| `summarize.py` | The three summary providers and output repair |+| `stitch.py` | Joins recordings that belong to one conversation |+| `calendar_feed.py` | Optional iCal feed for the meeting trigger |+| `db.py`, `store.py` | SQLite schema, settings defaults, transcript helpers |+| `config.py` | Paths, `.env`, tunables |+| `launch.py` | start / stop / status / token |+| `tools/setup_watch.py` | Installs and configures the watch app over adb |+| `static/` | Dashboard (plain HTML, CSS, JS, no build step) |+| `watch/` | Wear OS app (Kotlin). `RecorderService.kt` is the core |++## Traps already solved (don't undo them)++- onnxruntime crashes on 32-bit ARM watches with graph optimizations on. `Vad.kt` uses `OptLevel.NO_OPT` on purpose.+- Android 14+ won't start a microphone service from the background. Auto mode keeps its service alive and uses exact alarms.+- WorkManager uploads use `ExistingWorkPolicy.REPLACE` so a fresh upload isn't stuck behind an old retry delay.+- WhisperX 3.8.6 pins torch 2.8. Install torch from the cu128 index before the requirements file.+- Don't run the server with `uvicorn --reload`.+- Don't set `JAVA_HOME` for the gradle build unless it is missing. A wrong one breaks it.diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..43c994c--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1 @@diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..6da0aaa--- /dev/null+++ b/LICENSE@@ -0,0 +1,25 @@+MIT License++Copyright (c) 2026 Leveled AI++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++---+The watch app bundles the Silero VAD model (watch/app/src/main/assets/silero_vad.onnx),+MIT License, Copyright (c) Silero Team. https://github.com/snakers4/silero-vaddiff --git a/README.md b/README.mdnew file mode 100644index 0000000..5a7f394--- /dev/null+++ b/README.md@@ -0,0 +1,80 @@+# Voice Capture++Turn a Galaxy Watch (or any Wear OS watch) into a wearable AI note taker, like a Plaud pin, without buying one.++Tap the watch to record a conversation. Your PC transcribes it with speaker names, an AI writes the summary and action items, and the audio is deleted. Everything shows up in a private dashboard on your own computer.++++## What you get++- **A watch app.** Record with a button, a watch-face shortcut, or a double press of the Home key. There's also an auto mode that starts recording when it hears speech.+- **Transcripts with speaker labels.** WhisperX runs on your own GPU. Teach it your voice once and it labels you by name. Name other people as they show up.+- **Summaries from the AI you already pay for.** Pick one in Settings:+ - Claude subscription (through Claude Code)+ - ChatGPT subscription (through the Codex CLI)+ - any API key (OpenAI, Gemini, Anthropic, OpenRouter)+ - a free local model (Ollama or LM Studio)+- **A daily digest** of everything you recorded that day.+- **Keyword search** across every conversation.+- **No audio kept.** The watch deletes each clip once the PC confirms it arrived. The PC deletes the audio once the transcript is saved.++++## What you need++| | |+|---|---|+| Watch | Wear OS 3 or newer: Galaxy Watch 4 and later, Pixel Watch. Built and tested on a Galaxy Watch7. No Apple Watch. |+| PC | Windows 10 or 11 with an NVIDIA GPU. Built on a 16 GB card. Smaller cards and CPU-only are untested. |+| Software | Python 3.12, ffmpeg, Android platform-tools (adb) |+| Accounts | A free Hugging Face account (for speaker labels), plus one AI option from the list above |++## Setup++The fastest way is to let a coding agent do it. Open Claude Code or Codex in an empty folder and paste this:++```+Clone https://github.com/alexleveled/watch-voice-capture into this folder and set it up for me.+Follow the AGENTS.md file in the repo step by step, and ask me when you need something from me.+```++Already cloned it? Open the folder and say "Set this up for me."++The agent reads [AGENTS.md](AGENTS.md), installs everything, checks each step, and stops to ask you for the few things only you can do (pairing the watch, the Hugging Face token).++To do it by hand, follow [SETUP.md](SETUP.md). Plan on about an hour, most of it downloads.++## How it works++```+Watch app+ mic -> 2 minute Opus clips -> upload queue (kept on the watch while offline)+ |+ v your home Wi-Fi (default), or a tunnel if you want uploads from anywhere+PC server.py receives clips, serves the dashboard and the watch's settings+ worker.py join clips -> WhisperX transcript -> speaker labels + voiceprints+ -> delete audio -> AI summary -> daily digest+ |+ v+data/voice.db (SQLite) -> dashboard at http://127.0.0.1:8808+```++## Things to know before you rely on it++- **Battery.** Button recording is light. Auto mode keeps the microphone listening and drained a Galaxy Watch7 in a few hours of all-day use. Use auto mode for a busy day or limit it to time windows.+- **The PC has to be on** to receive uploads. The watch holds clips until it is.+- **Wi-Fi mode only uploads at home.** Away from home the watch queues clips and sends them when you're back. Tunnel mode in SETUP.md removes that limit.+- **The watch app is sideloaded** over wireless debugging. It is not in the Play Store.+- **Recording laws.** Many places require everyone's consent before you record a conversation. Auto mode reacts to any voice, including a TV. Know the law where you live and tell people.+- **Summary quality depends on the model.** Small local models can miss details on long conversations. The Settings page has a test button.++## What has and hasn't been tested++Tested: this code was built and used on a Galaxy Watch7 and an RTX 4060 Ti, uploading through a Cloudflare tunnel. In this public version, a Galaxy Watch7 recorded and uploaded over home Wi-Fi with the released watch app, and the PC pipeline, the Claude subscription provider, the Wi-Fi mode network rules and the calendar parser were each tested. The API-key path was tested against a stand-in server.++Not tested yet: real OpenAI, Gemini, Ollama and LM Studio endpoints, the Codex CLI provider, other watches, CPU-only transcription, and calendar links from Outlook. If one of these works or breaks for you, open an issue.++## License++MIT. See [LICENSE](LICENSE). The watch app bundles the Silero VAD model (MIT).diff --git a/SETUP.md b/SETUP.mdnew file mode 100644index 0000000..96d9ac5--- /dev/null+++ b/SETUP.md@@ -0,0 +1,153 @@+# Setup by hand++Run every command from this folder in PowerShell. If you'd rather not do this yourself, open the folder in Claude Code or Codex and say "set this up for me" (see [AGENTS.md](AGENTS.md)).++## 1. Install the tools++You need Python 3.12, ffmpeg and adb on your PATH.++```powershell+winget install Python.Python.3.12+winget install Gyan.FFmpeg+winget install Google.PlatformTools+```++Close and reopen PowerShell, then check:++```powershell+py -3.12 --version+ffmpeg -version+adb version+nvidia-smi+```++## 2. Install the PC side++```powershell+py -3.12 -m venv .venv+.venv\Scripts\python.exe -m pip install torch==2.8.0 torchaudio==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cu128+.venv\Scripts\python.exe -m pip install -r requirements.txt+```++The torch line has to run first. It is a download of a few GB.++## 3. Create your settings file++```powershell+Copy-Item .env.example .env+python launch.py token+```++The second command creates the upload token the watch will use and saves it in `.env`.++**Speaker labels (recommended).** Make a free account at huggingface.co, open+https://huggingface.co/pyannote/speaker-diarization-community-1 and accept the terms, then create a read token under Settings > Access Tokens. Put it in `.env` as `HF_TOKEN=`. Without it every line is labeled as one speaker.++## 4. Start it and pick your AI++```powershell+python launch.py start+```++Open http://127.0.0.1:8808 and go to **Settings > Summaries**. Pick a provider and press **Save and test**.++| Provider | What to do first |+|---|---|+| Claude subscription | Install Claude Code and run `claude login` once |+| ChatGPT subscription | `npm i -g @openai/codex`, then `codex login` once |+| API key | Pick the service, paste the key, type the model name your service uses |+| Local model | Install Ollama or LM Studio, download a model, type its name. No key needed |++Then scroll to **Test upload**, send any audio file with speech in it, and open the conversation. The first run downloads the speech models, so give it a few minutes. When you see a transcript and a summary, the PC side is done.++Other commands: `python launch.py status`, `stop`, `restart`. Logs are in `data\server.log` and `data\worker.log`.++## 5. Connect the watch++On the watch:++1. Settings > About watch > Software information. Tap **Software version** seven times to unlock Developer options.+2. Settings > Developer options. Turn on **ADB debugging** and **Wireless debugging**. The watch must be on the same Wi-Fi as the PC.+3. Tap **Wireless debugging > Pair new device**. It shows an address, a port and a six-digit code.++On the PC, use the address and port from the pairing screen, then the code:++```powershell+adb pair 192.168.1.23:37000+```++Go back one screen on the watch. It shows a second address and port for connecting (the port is different from the pairing one):++```powershell+adb connect 192.168.1.23:41000+adb devices+```++`adb devices` should list the watch as `device`.++## 6. Let the watch reach the PC (Wi-Fi mode)++`.env.example` already sets `BIND_HOST=0.0.0.0`, which lets devices on your home network reach the upload address. Windows Firewall still blocks it until you allow it. Open PowerShell **as administrator** and run:++```powershell+netsh advfirewall firewall add rule name="Voice Capture" dir=in action=allow protocol=TCP localport=8808 profile=private+```++Your Wi-Fi has to be set as a Private network in Windows for this rule to apply.++Other devices on your network can only reach the watch's upload address, and only with the token. The dashboard answers on the PC itself. To open the dashboard from your phone at home, set `DASHBOARD_ON_LAN=1` in `.env` and restart. Anyone on your Wi-Fi can then read it.++## 7. Install the watch app++Download `voice-capture-watch.apk` from this repo's Releases page into a `dist` folder here. Then:++```powershell+python tools/setup_watch.py+```++It installs the app, grants the microphone permission, and tells the watch this PC's address and token. Nothing is typed on the watch.++To build the app yourself instead: install Android Studio, then `cd watch; .\gradlew.bat assembleDebug`. The setup script finds the built file.++## 8. Try it++Open **Voice Capture** on the watch, tap the big button, talk for twenty seconds, tap it again. Within a minute or two the conversation appears in the dashboard.++Then, in the dashboard under **Settings > Voices**, enroll your own voice so your lines are labeled with your name.++When you're finished, turn Wireless debugging off on the watch. The recorder doesn't need it, and it saves some battery. Turn it back on only to install an update.++## Using it day to day++- **Start and stop.** The button in the app, the Voice Capture shortcut you can add to a watch face, or a double press of the Home key. For the double press on a Galaxy Watch: Settings > Buttons and gestures > Double press Home key > **Quick Rec**.+- **Button recordings** stop by themselves after 10 minutes of silence.+- **Auto mode** (toggle in the app) listens whenever the watch is on your wrist and records when it hears speech. Two minutes of silence ends the recording. In dashboard Settings you can limit it to weekly time windows, which is much easier on the battery.+- **Stitching.** Recordings less than 10 minutes apart are joined into one conversation unless the other voices clearly differ.+- Dashboard setting changes reach the watch within about two minutes while it is recording or listening, and the next time you open the app otherwise.+- After a watch restart or an app update, Android won't let the app reopen the microphone by itself. The watch shows "Auto mode is paused, tap to resume". Opening the app fixes it.++## Optional: record calendar meetings++Put your calendar's private iCal link in `.env` as `CALENDAR_ICS_URL=`, restart, and tick **Record calendar meetings** in Settings. In Google Calendar the link is under Settings > your calendar > "Secret address in iCal format". Auto mode then also opens for meetings that have attendees or a video-call link.++## Optional: upload from anywhere (tunnel mode)++Wi-Fi mode only uploads at home. To upload from anywhere, put the PC behind a tunnel. With Cloudflare Tunnel:++1. Route two hostnames to `http://127.0.0.1:8808`, for example `voice.example.com` (dashboard) and `voice-in.example.com` (watch uploads).+2. Protect the dashboard hostname with a Cloudflare Access policy that allows only you. **Without this, the dashboard is public.**+3. Optionally protect the upload hostname with an Access service token and put it in `.env` as `CF_ACCESS_CLIENT_ID` and `CF_ACCESS_CLIENT_SECRET`.+4. In `.env` set `BIND_HOST=127.0.0.1` and `INGEST_HOST=voice-in.example.com`, then `python launch.py restart`.+5. `python tools/setup_watch.py --config-only --url https://voice-in.example.com`++## Troubleshooting++| Problem | Fix |+|---|---|+| Watch says "offline, will retry" | The PC is off, the firewall rule is missing, or the PC's address changed. Run `python tools/setup_watch.py --config-only` again. Giving the PC a fixed address in your router stops this from coming back. |+| Watch says "rejected: check tokens" | The token in `.env` changed. Run `python tools/setup_watch.py --config-only`. |+| `adb devices` shows nothing or "offline" | `adb disconnect`, then `adb connect` again with the address on the Wireless debugging screen. The port changes each time debugging is switched on. |+| "More than one device" | The watch can show up twice. Pass `--serial <address:port>` to the setup script. |+| Every line is "Speaker A" | No `HF_TOKEN` in `.env`, or the model terms weren't accepted. |+| Summaries never appear | Settings > Summaries > Save and test shows the exact error. |+| Dashboard says "wrong Python" | Start it with `python launch.py start`, which uses the `.venv` in this folder. |diff --git a/calendar_feed.py b/calendar_feed.pynew file mode 100644index 0000000..2b0faf7--- /dev/null+++ b/calendar_feed.py@@ -0,0 +1,84 @@+"""Upcoming meetings for the watch's calendar trigger. Optional and read-only.++Set CALENDAR_ICS_URL in .env to your calendar's private iCal link:+ Google Calendar: Settings > your calendar > "Secret address in iCal format"+ Outlook: Settings > Calendar > Shared calendars > Publish a calendar > ICS link++A calendar block counts as a meeting when it has at least one attendee or a video-call link+(Zoom, Meet, Teams, Webex). All-day and cancelled events are skipped, so "gym" or "pay rent"+blocks never record. Some providers strip attendees from the feed; set+"calendar_all_timed_events": true in config.json to count every timed event instead.+"""++from __future__ import annotations++import re+import time+from datetime import date, datetime, timedelta, timezone++import httpx++import config++VIDEO_LINK = re.compile(r"zoom\.us/|meet\.google\.com/|teams\.microsoft\.com/|teams\.live\.com/|webex\.com/", re.I)++_cache: tuple[float, str, list] = (0.0, "", [])+++def _is_meeting(ev, count_all: bool) -> bool:+ if str(ev.get("STATUS", "")).upper() == "CANCELLED":+ return False+ start = ev.get("DTSTART")+ if start is None or not isinstance(start.dt, datetime): # a plain date = all-day event+ return False+ if count_all:+ return True+ if ev.get("ATTENDEE"):+ return True+ text = " ".join(str(ev.get(k, "")) for k in ("LOCATION", "DESCRIPTION", "URL", "X-GOOGLE-CONFERENCE"))+ return bool(VIDEO_LINK.search(text))+++def _utc(dt) -> datetime:+ if isinstance(dt, date) and not isinstance(dt, datetime):+ dt = datetime(dt.year, dt.month, dt.day)+ if dt.tzinfo is None:+ dt = dt.astimezone() # floating time: treat as this PC's local time+ return dt.astimezone(timezone.utc)+++def parse(ics_text: str, hours_ahead: int = 36) -> list[dict]:+ """[{start, end, title}] in iso utc, from now-1h to now+hours_ahead. Recurring events are expanded."""+ import icalendar+ import recurring_ical_events++ cal = icalendar.Calendar.from_ical(ics_text)+ now = datetime.now(timezone.utc)+ count_all = bool(config.tunables().get("calendar_all_timed_events"))+ out = []+ for ev in recurring_ical_events.of(cal).between(now - timedelta(hours=1), now + timedelta(hours=hours_ahead)):+ if not _is_meeting(ev, count_all):+ continue+ s = _utc(ev["DTSTART"].dt)+ e = _utc(ev["DTEND"].dt) if ev.get("DTEND") else s + timedelta(hours=1)+ out.append({"start": s.isoformat(timespec="seconds"), "end": e.isoformat(timespec="seconds"),+ "title": str(ev.get("SUMMARY") or "Meeting")})+ out.sort(key=lambda m: m["start"])+ return out+++def meetings(hours_ahead: int = 36, cache_s: int = 600) -> list[dict]:+ """Cached 10 min. Returns [] when no calendar is set up."""+ global _cache+ url = config.calendar_ics_url()+ if not url:+ return []+ if url.startswith("webcal://"):+ url = "https://" + url[len("webcal://"):]+ if _cache[1] == url and time.time() - _cache[0] < cache_s:+ return _cache[2]+ r = httpx.get(url, timeout=30, follow_redirects=True)+ r.raise_for_status()+ out = parse(r.text, hours_ahead)+ _cache = (time.time(), url, out)+ return outdiff --git a/config.py b/config.pynew file mode 100644index 0000000..1ce5f2c--- /dev/null+++ b/config.py@@ -0,0 +1,100 @@+"""Paths, secrets and tunables for Voice Capture.++Secrets and machine settings live in .env next to this file (gitignored). See .env.example.+Optional tunables (models, thresholds) can be overridden in config.json next to this file.+"""++from __future__ import annotations++import json+import os+from pathlib import Path++from dotenv import load_dotenv++APP_DIR = Path(__file__).resolve().parent+DATA_DIR = APP_DIR / "data"+AUDIO_DIR = DATA_DIR / "audio"+ENROLL_DIR = DATA_DIR / "enroll"+DB_PATH = DATA_DIR / "voice.db"+STATIC_DIR = APP_DIR / "static"+ENV_PATH = APP_DIR / ".env"+TUNABLES_PATH = APP_DIR / "config.json"++load_dotenv(ENV_PATH)++PORT = int(os.environ.get("PORT") or 8808)+# 127.0.0.1 = this PC only (use with a tunnel). 0.0.0.0 = also reachable on your home network,+# which is what the watch needs in Wi-Fi mode.+BIND_HOST = (os.environ.get("BIND_HOST") or "127.0.0.1").strip()+# Wi-Fi mode: other devices may only reach the watch API unless this is 1.+DASHBOARD_ON_LAN = (os.environ.get("DASHBOARD_ON_LAN") or "").strip() == "1"+# Tunnel mode: the public hostname the watch uploads to. Requests on it can only reach /api/v1/*.+INGEST_HOST = (os.environ.get("INGEST_HOST") or "").strip().lower()++DEFAULTS = {+ "whisper_model": "large-v3-turbo",+ "language": "en", # null = auto-detect+ "device": "auto", # auto | cuda | cpu+ "compute_type": "float16", # used on cuda; cpu always runs int8+ "batch_size": 16,+ "diarize_model": "pyannote/speaker-diarization-community-1",+ "speaker_match_threshold": 0.55, # cosine similarity to a saved voiceprint+ "recording_stale_minutes": 120, # process a recording whose last chunk never arrived+ "model_idle_unload_minutes": 10,+ "min_words_to_summarize": 25,+ "day_rebuild_debounce_minutes": 20,+ "keep_audio": False, # delete audio once the transcript is saved+ "calendar_all_timed_events": False, # true = every timed calendar event counts as a meeting+}+++def tunables() -> dict:+ cfg = dict(DEFAULTS)+ if TUNABLES_PATH.exists():+ cfg.update(json.loads(TUNABLES_PATH.read_text(encoding="utf-8")))+ return cfg+++def ingest_token() -> str:+ return (os.environ.get("INGEST_TOKEN") or "").strip()+++def hf_token() -> str:+ return (os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") or "").strip()+++def summary_api_key() -> str:+ return (os.environ.get("SUMMARY_API_KEY") or "").strip()+++def calendar_ics_url() -> str:+ return (os.environ.get("CALENDAR_ICS_URL") or "").strip()+++def set_env_value(key: str, value: str) -> None:+ """Write KEY=value into .env (replacing an existing line) and into this process."""+ value = value.strip().replace("\n", "").replace("\r", "")+ lines = ENV_PATH.read_text(encoding="utf-8").splitlines() if ENV_PATH.exists() else []+ out, done = [], False+ for ln in lines:+ if ln.split("=", 1)[0].strip() == key:+ if not done:+ out.append(f"{key}={value}")+ done = True+ else:+ out.append(ln)+ if not done:+ out.append(f"{key}={value}")+ ENV_PATH.write_text("\n".join(out) + "\n", encoding="utf-8")+ os.environ[key] = value+++def reload_env() -> None:+ """Pick up .env edits made by another process (the server writes keys, the worker reads them)."""+ load_dotenv(ENV_PATH, override=True)+++def ensure_dirs() -> None:+ for d in (DATA_DIR, AUDIO_DIR, ENROLL_DIR):+ d.mkdir(parents=True, exist_ok=True)diff --git a/db.py b/db.pynew file mode 100644index 0000000..65690f9--- /dev/null+++ b/db.py@@ -0,0 +1,193 @@+"""SQLite store (WAL). The server and the worker are separate processes sharing this file.++A "conversation" is one watch recording: the watch closes a recording after ~60 s of silence+(auto mode) or when the button stops it (manual), so the recording boundary is the+conversation boundary. Chunks are ~2-minute audio files belonging to a recording.+"""++from __future__ import annotations++import json+import sqlite3+from contextlib import contextmanager+from datetime import datetime, timezone++import config++SCHEMA = """+create table if not exists recordings (+ id text primary key, -- watch-generated uuid+ device_id text,+ trigger text not null default 'manual', -- manual | auto | calendar | upload+ started_at text not null, -- iso utc+ ended_at text,+ day text, -- local YYYY-MM-DD of started_at+ last_idx integer, -- idx of the chunk flagged is_last, if received+ status text not null default 'receiving',+ error text,+ attempts integer not null default 0,+ duration_s real,+ speech_s real,+ words integer,+ title text,+ summary_json text,+ summary_text text, -- flattened summary, for search+ transcript_text text, -- "Name: text" lines, for search+ updated_at text not null+);+create index if not exists recordings_day on recordings(day);+create index if not exists recordings_status on recordings(status);++create table if not exists chunks (+ id integer primary key,+ recording_id text not null references recordings(id) on delete cascade,+ idx integer not null,+ started_at text,+ duration_s real,+ path text,+ sha256 text not null,+ bytes integer,+ received_at text not null,+ unique(recording_id, idx)+);++create table if not exists segments (+ id integer primary key,+ recording_id text not null references recordings(id) on delete cascade,+ start_s real not null,+ end_s real not null,+ label text, -- diarization label, e.g. SPEAKER_00+ text text not null+);+create index if not exists segments_rec on segments(recording_id);++create table if not exists speakers (+ id integer primary key,+ name text not null unique,+ is_self integer not null default 0,+ embedding text, -- json float list, running mean+ samples integer not null default 0,+ last_heard text,+ created_at text not null+);++create table if not exists recording_speakers (+ recording_id text not null references recordings(id) on delete cascade,+ label text not null,+ display text not null, -- "Speaker A" until named+ speaker_id integer references speakers(id) on delete set null,+ embedding text,+ speech_s real,+ primary key (recording_id, label)+);++create table if not exists days (+ day text primary key,+ summary_json text,+ summary_text text,+ dirty integer not null default 1,+ dirty_since text,+ updated_at text+);++create table if not exists jobs (+ id integer primary key,+ kind text not null, -- enroll+ payload text not null,+ status text not null default 'queued', -- queued | done | failed+ error text,+ created_at text not null,+ done_at text+);++create table if not exists kv (+ key text primary key,+ value text not null+);+"""++DEFAULT_SETTINGS = {+ "auto": {+ "always_while_worn": False,+ "windows": {d: [] for d in ("mon", "tue", "wed", "thu", "fri", "sat", "sun")},+ "calendar": {"enabled": False, "lead_min": 2}, # needs CALENDAR_ICS_URL in .env+ },+ "upload": {"battery_saver": False},+ # Silence handling on the watch. auto_end_min ends an auto recording; manual_stop_min stops a+ # button-started one (0 = never). merge.gap_min joins recordings this close together (0 = off).+ "silence": {"auto_end_min": 2, "manual_stop_min": 10},+ "merge": {"gap_min": 10},+ # Which AI writes the summaries. provider: claude_subscription | codex_subscription | openai_compatible.+ # model "" = the provider's default. base_url is only used by openai_compatible. The API key lives in .env.+ "summary": {"provider": "claude_subscription", "model": "", "base_url": ""},+}+++def now_iso() -> str:+ return datetime.now(timezone.utc).isoformat(timespec="seconds")+++def local_day(iso: str) -> str:+ return datetime.fromisoformat(iso).astimezone().strftime("%Y-%m-%d")+++def connect() -> sqlite3.Connection:+ config.ensure_dirs()+ con = sqlite3.connect(config.DB_PATH, timeout=30, isolation_level=None)+ con.row_factory = sqlite3.Row+ con.execute("pragma journal_mode=wal")+ con.execute("pragma foreign_keys=on")+ con.execute("pragma busy_timeout=30000")+ return con+++@contextmanager+def tx(con: sqlite3.Connection):+ con.execute("begin immediate")+ try:+ yield con+ con.execute("commit")+ except BaseException:+ con.execute("rollback")+ raise+++def init() -> None:+ con = connect()+ con.executescript(SCHEMA)+ con.close()+++def get_kv(con, key: str, default=None):+ row = con.execute("select value from kv where key=?", (key,)).fetchone()+ return json.loads(row["value"]) if row else default+++def set_kv(con, key: str, value) -> None:+ con.execute("insert into kv(key,value) values(?,?) on conflict(key) do update set value=excluded.value",+ (key, json.dumps(value)))+++def settings(con) -> dict:+ s = get_kv(con, "settings")+ if not s:+ return json.loads(json.dumps(DEFAULT_SETTINGS))+ merged = json.loads(json.dumps(DEFAULT_SETTINGS))+ merged["auto"].update(s.get("auto", {}))+ merged["auto"]["windows"] = {**DEFAULT_SETTINGS["auto"]["windows"], **s.get("auto", {}).get("windows", {})}+ merged["auto"]["calendar"] = {**DEFAULT_SETTINGS["auto"]["calendar"], **s.get("auto", {}).get("calendar", {})}+ merged["upload"].update(s.get("upload", {}))+ merged["silence"].update(s.get("silence", {}))+ merged["merge"].update(s.get("merge", {}))+ merged["summary"].update(s.get("summary", {}))+ return merged+++def mark_day_dirty(con, day: str | None) -> None:+ if not day:+ return+ con.execute("""insert into days(day, dirty, dirty_since) values(?,1,?)+ on conflict(day) do update set+ dirty_since=case when days.dirty=1 then coalesce(days.dirty_since, excluded.dirty_since)+ else excluded.dirty_since end,+ dirty=1""", (day, now_iso()))diff --git a/docs/conversation.png b/docs/conversation.pngnew file mode 100644index 0000000..6cf9646Binary files /dev/null and b/docs/conversation.png differdiff --git a/docs/settings-providers.png b/docs/settings-providers.pngnew file mode 100644index 0000000..b73fd7bBinary files /dev/null and b/docs/settings-providers.png differdiff --git a/launch.py b/launch.pynew file mode 100644index 0000000..e679263--- /dev/null+++ b/launch.py@@ -0,0 +1,124 @@+"""Start / stop / restart / status for Voice Capture (server + worker). Windows only.++ python launch.py start+ python launch.py stop+ python launch.py restart+ python launch.py status+ python launch.py token # print the watch's INGEST_TOKEN (creates one if missing)++Any Python can run this file; server and worker always run on the app's .venv.+"""+import json+import os+import secrets+import subprocess+import sys+import time+import urllib.request+from pathlib import Path++APP = Path(__file__).resolve().parent+ENV = APP / ".env"+++def env_value(key: str, default: str) -> str:+ if ENV.exists():+ for ln in ENV.read_text(encoding="utf-8").splitlines():+ if ln.split("=", 1)[0].strip() == key and "=" in ln and ln.split("=", 1)[1].strip():+ return ln.split("=", 1)[1].strip()+ return default+++PORT = int(env_value("PORT", "8808"))+HEALTH = f"http://127.0.0.1:{PORT}/api/health"+VENV_PY = APP / ".venv" / "Scripts" / "python.exe"+DATA = APP / "data"+PROCS = {"server": "server.py", "worker": "worker.py"}+++def pid_file(name): return DATA / f"{name}.pid"+def log_file(name): return DATA / f"{name}.log"+++def alive(pid: int) -> bool:+ out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout+ return str(pid) in out+++def read_pid(name):+ try:+ pid = int(pid_file(name).read_text().strip())+ return pid if alive(pid) else None+ except Exception:+ return None+++def health(timeout=2.0):+ try:+ with urllib.request.urlopen(HEALTH, timeout=timeout) as r:+ return json.loads(r.read().decode("utf-8"))+ except Exception:+ return None+++def ensure_token() -> str:+ lines = ENV.read_text(encoding="utf-8").splitlines() if ENV.exists() else []+ for ln in lines:+ if ln.startswith("INGEST_TOKEN=") and ln.split("=", 1)[1].strip():+ return ln.split("=", 1)[1].strip()+ tok = secrets.token_urlsafe(32)+ lines.append(f"INGEST_TOKEN={tok}")+ ENV.write_text("\n".join(lines) + "\n", encoding="utf-8")+ return tok+++def start():+ DATA.mkdir(exist_ok=True)+ if not VENV_PY.exists():+ sys.exit(f"no venv at {VENV_PY}; see SETUP.md")+ ensure_token()+ flags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP+ env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}+ for name, script in PROCS.items():+ if read_pid(name):+ continue+ log = open(log_file(name), "a", encoding="utf-8")+ p = subprocess.Popen([str(VENV_PY), "-u", str(APP / script)], cwd=APP, stdout=log, stderr=subprocess.STDOUT,+ creationflags=flags, env=env)+ pid_file(name).write_text(str(p.pid))+ for _ in range(60):+ h = health()+ if h and h["worker"]["alive"]:+ break+ time.sleep(1)+ status()+++def stop():+ for name in PROCS:+ pid = read_pid(name)+ if pid:+ subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True)+ pid_file(name).unlink(missing_ok=True)+ print(json.dumps({"ok": True, "state": "stopped"}))+++def status():+ h = health()+ print(json.dumps({"ok": bool(h and h.get("ok")), "url": f"http://127.0.0.1:{PORT}",+ "server_pid": read_pid("server"), "worker_pid": read_pid("worker"),+ "health": h, "logs": [str(log_file(n)) for n in PROCS]}, indent=2))+++if __name__ == "__main__":+ cmd = sys.argv[1] if len(sys.argv) > 1 else "status"+ if cmd == "start":+ start()+ elif cmd == "stop":+ stop()+ elif cmd == "restart":+ stop(); time.sleep(1); start()+ elif cmd == "token":+ print(ensure_token())+ else:+ status()diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..65fb079--- /dev/null+++ b/requirements.txt@@ -0,0 +1,12 @@+# Install torch from the CUDA index FIRST (WhisperX 3.8.6 pins torch 2.8):+# .venv\Scripts\python.exe -m pip install torch==2.8.0 torchaudio==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cu128+whisperx==3.8.6+fastapi>=0.115+uvicorn>=0.30+python-multipart+python-dotenv+httpx+icalendar>=6+recurring-ical-events>=3+# Only needed for the "Claude subscription" summary provider:+claude-agent-sdk>=0.2.152diff --git a/server.py b/server.pynew file mode 100644index 0000000..2b52e03--- /dev/null+++ b/server.py@@ -0,0 +1,607 @@+"""Voice Capture server (default 127.0.0.1:8808).++Two audiences on one port:+ /api/v1/* the watch. Always needs the bearer INGEST_TOKEN.+ everything else: the dashboard.++Two ways to run it (see SETUP.md):+ Wi-Fi mode BIND_HOST=0.0.0.0. The watch uploads straight to this PC on the home network.+ Other devices can only reach /api/v1/*; the dashboard answers only on this PC+ unless DASHBOARD_ON_LAN=1.+ Tunnel mode BIND_HOST=127.0.0.1 behind a tunnel (Cloudflare Tunnel + Access, Tailscale...).+ Set INGEST_HOST to the hostname the watch uploads to: requests on that hostname+ can never reach a dashboard route. Protecting the dashboard hostname is the+ tunnel's job (e.g. a Cloudflare Access policy).++Heavy work (transcription, diarization, summaries) happens in worker.py, never here.+"""++from __future__ import annotations++import hashlib+import hmac+import json+import re+import shutil+import subprocess+import sys+import time+import uuid+from datetime import datetime, timedelta, timezone+from pathlib import Path++from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile+from fastapi.responses import FileResponse, JSONResponse+from fastapi.staticfiles import StaticFiles++import calendar_feed+import config+import db+import stitch+import store+import summarize++config.ensure_dirs()+db.init()+app = FastAPI(title="Voice Capture")++SAFE_ID = re.compile(r"^[A-Za-z0-9_-]{6,64}$")+AUDIO_EXT = {".ogg", ".opus", ".m4a", ".aac", ".wav", ".mp3", ".webm", ".flac", ".amr", ".3gp", ".mp4"}+++def con():+ return db.connect()+++# ---- host gate ---------------------------------------------------------------++LOOPBACK = {"127.0.0.1", "::1"} # a local tunnel client (cloudflared) also connects from here+[email protected]("http")+async def no_stale_ui(request: Request, call_next):+ """Dashboard files: always revalidate, so a redesign shows up on the next load (ETag keeps it cheap)."""+ resp = await call_next(request)+ if not request.url.path.startswith("/api/"):+ resp.headers["Cache-Control"] = "no-cache"+ return resp++[email protected]("http")+async def host_gate(request: Request, call_next):+ host = (request.headers.get("host") or "").split(":")[0].lower()+ path = request.url.path+ if not path.startswith("/api/v1/"):+ if config.INGEST_HOST and host == config.INGEST_HOST:+ return JSONResponse({"detail": "not found"}, status_code=404)+ client = request.client.host if request.client else ""+ if client not in LOOPBACK and not config.DASHBOARD_ON_LAN:+ return JSONResponse({"detail": "the dashboard only answers on the PC itself"}, status_code=403)+ if path.startswith("/api/v1/"):+ token = config.ingest_token()+ got = (request.headers.get("authorization") or "").removeprefix("Bearer ").strip()+ if not token or not hmac.compare_digest(got, token):+ return JSONResponse({"detail": "bad token"}, status_code=401)+ return await call_next(request)+++# ---- watch API ---------------------------------------------------------------+[email protected]("/api/v1/ping")+def ping():+ return {"ok": True, "server_time": db.now_iso()}+++def _store_chunk(c, *, recording_id: str, idx: int, is_last: bool, started_at: str, chunk_started_at: str | None,+ duration_s: float | None, trigger: str, device_id: str | None, sha: str, src: Path, ext: str) -> dict:+ existing = c.execute("select sha256 from chunks where recording_id=? and idx=?", (recording_id, idx)).fetchone()+ if existing:+ src.unlink(missing_ok=True)+ if existing["sha256"] == sha:+ return {"ok": True, "duplicate": True, "sha256": sha}+ raise HTTPException(409, "chunk already stored with a different checksum")+ rec = c.execute("select status from recordings where id=?", (recording_id,)).fetchone()+ if rec and rec["status"] not in ("receiving", "waiting"):+ # Late chunk for a recording already processed (it went stale first): start a continuation.+ recording_id = f"{recording_id}-c{idx}"+ rec = c.execute("select status from recordings where id=?", (recording_id,)).fetchone()+ dest_dir = config.AUDIO_DIR / recording_id+ dest_dir.mkdir(parents=True, exist_ok=True)+ dest = dest_dir / f"{idx:05d}{ext}"+ shutil.move(str(src), dest)+ now = db.now_iso()+ with db.tx(c):+ if not rec:+ c.execute("""insert into recordings(id, device_id, trigger, started_at, day, status, updated_at)+ values(?,?,?,?,?, 'receiving', ?)""",+ (recording_id, device_id, trigger, started_at, db.local_day(started_at), now))+ c.execute("""insert into chunks(recording_id, idx, started_at, duration_s, path, sha256, bytes, received_at)+ values(?,?,?,?,?,?,?,?)""",+ (recording_id, idx, chunk_started_at, duration_s, str(dest), sha, dest.stat().st_size, now))+ if is_last:+ end = None+ if chunk_started_at and duration_s:+ end = (datetime.fromisoformat(chunk_started_at) + timedelta(seconds=duration_s)).isoformat(timespec="seconds")+ c.execute("update recordings set last_idx=?, ended_at=coalesce(?, ended_at) where id=?",+ (idx, end, recording_id))+ c.execute("update recordings set updated_at=? where id=?", (now, recording_id))+ return {"ok": True, "duplicate": False, "sha256": sha, "recording_id": recording_id}+++def _norm_iso(s: str) -> str:+ try:+ dt = datetime.fromisoformat(s.replace("Z", "+00:00"))+ except ValueError:+ raise HTTPException(422, f"bad timestamp {s!r}")+ if dt.tzinfo is None:+ dt = dt.astimezone()+ return dt.astimezone(timezone.utc).isoformat(timespec="seconds")+++async def _save_upload(file: UploadFile) -> tuple[Path, str, str]:+ ext = Path(file.filename or "").suffix.lower() or ".ogg"+ if ext not in AUDIO_EXT:+ raise HTTPException(415, f"unsupported audio type {ext}")+ tmp = config.DATA_DIR / f"incoming-{uuid.uuid4().hex}{ext}"+ h = hashlib.sha256()+ with tmp.open("wb") as f:+ while blk := await file.read(1 << 20):+ h.update(blk)+ f.write(blk)+ return tmp, h.hexdigest(), ext++[email protected]("/api/v1/chunks")+async def ingest_chunk(+ file: UploadFile = File(...),+ recording_id: str = Form(...),+ idx: int = Form(...),+ is_last: bool = Form(False),+ started_at: str = Form(...),+ chunk_started_at: str | None = Form(None),+ duration_s: float | None = Form(None),+ trigger: str = Form("manual"),+ device_id: str | None = Form(None),+ sha256: str = Form(...),+):+ if not SAFE_ID.match(recording_id) or idx < 0:+ raise HTTPException(422, "bad recording_id/idx")+ if trigger not in ("manual", "auto", "calendar"):+ raise HTTPException(422, "bad trigger")+ tmp, sha, ext = await _save_upload(file)+ if sha != sha256.lower():+ tmp.unlink(missing_ok=True)+ raise HTTPException(400, "checksum mismatch, resend")+ c = con()+ try:+ return _store_chunk(c, recording_id=recording_id, idx=idx, is_last=is_last, started_at=_norm_iso(started_at),+ chunk_started_at=_norm_iso(chunk_started_at) if chunk_started_at else None,+ duration_s=duration_s, trigger=trigger, device_id=device_id, sha=sha, src=tmp, ext=ext)+ finally:+ c.close()++[email protected]("/api/v1/schedule")+def schedule():+ c = con()+ try:+ s = db.settings(c)+ finally:+ c.close()+ meetings, cal_error = [], None+ if s["auto"]["calendar"]["enabled"]:+ try:+ meetings = calendar_feed.meetings()+ except Exception as e: # calendar trouble must never block the watch+ cal_error = str(e)[:200]+ return {"server_time": db.now_iso(), "tz_offset_min": int(datetime.now().astimezone().utcoffset().total_seconds() // 60),+ "auto": s["auto"], "upload": s["upload"], "silence": s["silence"], "meetings": meetings, "calendar_error": cal_error}+++# ---- dashboard API -----------------------------------------------------------+[email protected]("/api/health")+def health():+ c = con()+ try:+ hb = db.get_kv(c, "worker_heartbeat") or {}+ counts = {r["status"]: r["n"] for r in c.execute("select status, count(*) n from recordings group by status")}+ summary_cfg = db.settings(c)["summary"]+ finally:+ c.close()+ alive = bool(hb.get("at")) and (datetime.now(timezone.utc) - datetime.fromisoformat(hb["at"])).total_seconds() < 90+ summary_label, summary_problem = summarize.status(summary_cfg)+ problems = []+ if not alive:+ problems.append("worker is not running")+ if not config.hf_token():+ problems.append("no Hugging Face token: speaker labels are off")+ if summary_problem:+ problems.append(summary_problem)+ if not config.ingest_token():+ problems.append("no INGEST_TOKEN: the watch can't upload")+ if counts.get("failed"):+ problems.append(f"{counts['failed']} recording(s) failed")+ venv = Path(sys.prefix).resolve() == (config.APP_DIR / ".venv").resolve()+ if not venv:+ problems.append("server is running on the wrong Python")+ return {"ok": not problems, "problems": problems, "venv": venv,+ "worker": {"alive": alive, "last_tick": hb.get("at"), "state": hb.get("state") or "unknown"},+ "hf_token": bool(config.hf_token()), "summary": summary_label, "calendar": bool(config.calendar_ics_url()),+ "queue": {k: counts.get(k, 0) for k in ("receiving", "waiting", "transcribing", "summarizing", "failed")}}++[email protected]("/api/days")+def days(limit: int = 60):+ c = con()+ try:+ rows = c.execute("""select r.day, count(*) n, coalesce(sum(r.speech_s),0) speech, d.summary_json+ from recordings r left join days d on d.day=r.day+ where r.status != 'empty' group by r.day order by r.day desc limit ?""", (limit,)).fetchall()+ return [{"day": r["day"], "conversations": r["n"], "speech_minutes": round(r["speech"] / 60, 1),+ "headline": (json.loads(r["summary_json"]) or {}).get("headline") if r["summary_json"] else None}+ for r in rows]+ finally:+ c.close()++[email protected]("/api/days/{day}")+def day_view(day: str):+ if not re.match(r"^\d{4}-\d{2}-\d{2}$", day):+ raise HTTPException(422, "bad day")+ c = con()+ try:+ d = c.execute("select summary_json from days where day=?", (day,)).fetchone()+ convs = []+ for r in c.execute("select * from recordings where day=? order by started_at", (day,)):+ s = json.loads(r["summary_json"]) if r["summary_json"] else None+ convs.append({"id": r["id"], "started_at": r["started_at"], "ended_at": r["ended_at"],+ "duration_s": r["duration_s"], "trigger": r["trigger"], "status": r["status"],+ "title": r["title"], "summary_short": (s or {}).get("summary"),+ "speakers": [v["display"] for v in store.speaker_names(c, r["id"]).values()]})+ return {"day": day, "summary": json.loads(d["summary_json"]) if d and d["summary_json"] else None,+ "conversations": convs}+ finally:+ c.close()++[email protected]("/api/conversations/{rec_id}")+def get_conversation(rec_id: str):+ c = con()+ try:+ conv = store.conversation(c, rec_id)+ finally:+ c.close()+ if not conv:+ raise HTTPException(404, "no such conversation")+ return conv++[email protected]("/api/conversations/{rec_id}/speakers/{label}")+async def name_speaker(rec_id: str, label: str, request: Request):+ body = await request.json()+ c = con()+ try:+ rs = c.execute("select * from recording_speakers where recording_id=? and label=?", (rec_id, label)).fetchone()+ if not rs:+ raise HTTPException(404, "no such speaker in this conversation")+ with db.tx(c):+ if body.get("speaker_id"):+ sid = int(body["speaker_id"])+ if not c.execute("select 1 from speakers where id=?", (sid,)).fetchone():+ raise HTTPException(404, "no such speaker")+ else:+ name = (body.get("name") or "").strip()[:60]+ if not name:+ raise HTTPException(422, "name required")+ row = c.execute("select id from speakers where lower(name)=lower(?)", (name,)).fetchone()+ sid = row["id"] if row else c.execute(+ "insert into speakers(name, created_at) values(?,?)", (name, db.now_iso())).lastrowid+ first_time = rs["speaker_id"] != sid+ c.execute("update recording_speakers set speaker_id=? where recording_id=? and label=?", (sid, rec_id, label))+ if first_time:+ store.fold_into_speaker(c, sid, rs["embedding"])+ store.refresh_transcript(c, rec_id)+ # Re-summarize with real names; the worker waits ~60 s so naming several speakers costs one call.+ c.execute("""update recordings set status='transcribed', updated_at=? where id=? and status in ('done','failed')""",+ (db.now_iso(), rec_id))+ return store.conversation(c, rec_id)+ finally:+ c.close()++[email protected]("/api/conversations/{rec_id}/resummarize")+def resummarize(rec_id: str):+ c = con()+ try:+ n = c.execute("""update recordings set status='transcribed', error=null, updated_at=?+ where id=? and transcript_text is not null""", (db.now_iso(), rec_id)).rowcount+ finally:+ c.close()+ if not n:+ raise HTTPException(409, "nothing to summarize yet")+ return {"ok": True}++[email protected]("/api/conversations/{rec_id}/merge-previous")+def merge_previous(rec_id: str):+ """Manual stitch: fold this conversation into the one right before it (same watch)."""+ c = con()+ try:+ r = c.execute("select * from recordings where id=?", (rec_id,)).fetchone()+ if not r:+ raise HTTPException(404, "no such conversation")+ busy = ("receiving", "waiting", "transcribing")+ if r["status"] in busy:+ raise HTTPException(409, "still being transcribed, try again in a minute")+ prev = c.execute("""select * from recordings where id != ? and started_at < ? and status not in+ ('receiving','waiting','transcribing') order by started_at desc limit 1""",+ (rec_id, r["started_at"])).fetchone()+ if not prev:+ raise HTTPException(409, "there is no earlier conversation to merge into")+ stitch.merge(c, prev["id"], rec_id)+ return {"ok": True, "into": prev["id"]}+ finally:+ c.close()++[email protected]("/api/conversations/{rec_id}")+def delete_conversation(rec_id: str):+ c = con()+ try:+ r = c.execute("select day from recordings where id=?", (rec_id,)).fetchone()+ if not r:+ raise HTTPException(404, "no such conversation")+ with db.tx(c):+ c.execute("delete from recordings where id=?", (rec_id,))+ db.mark_day_dirty(c, r["day"])+ shutil.rmtree(config.AUDIO_DIR / rec_id, ignore_errors=True)+ return {"ok": True}+ finally:+ c.close()+++SEARCH_TERM_RE = re.compile(r'"([^"]+)"|(\S+)')+++def _terms(q: str) -> list[str]:+ """Keyword terms: words, or "quoted phrases". Every term must appear (any order)."""+ return [(a or b).strip().lower() for a, b in SEARCH_TERM_RE.findall(q or "") if (a or b).strip()][:8]++[email protected]("/api/search")+def search(q: str = "", date_from: str | None = None, date_to: str | None = None, speaker: int | None = None):+ """Keyword search over every conversation (title, summary, transcript). No AI.+ Returns each matching conversation with every matching transcript line (time + speaker)."""+ terms = [t for t in _terms(q) if len(t) >= 2]+ if not terms:+ return {"results": [], "terms": []}+ where = ["r.status not in ('receiving','waiting','transcribing','empty')"]+ args: list = []+ for t in terms:+ where.append("lower(coalesce(r.title,'') || ' ' || coalesce(r.summary_text,'') || ' ' || coalesce(r.transcript_text,'')) like ?")+ args.append(f"%{t}%")+ if date_from and re.match(r"^\d{4}-\d{2}-\d{2}$", date_from):+ where.append("r.day >= ?"); args.append(date_from)+ if date_to and re.match(r"^\d{4}-\d{2}-\d{2}$", date_to):+ where.append("r.day <= ?"); args.append(date_to)+ if speaker:+ where.append("exists (select 1 from recording_speakers rs where rs.recording_id = r.id and rs.speaker_id = ?)")+ args.append(int(speaker))+ c = con()+ try:+ rows = c.execute(f"""select r.id, r.day, r.started_at, r.duration_s, r.trigger, r.title, r.summary_text+ from recordings r where {' and '.join(where)}+ order by r.started_at desc limit 100""", args).fetchall()+ out = []+ for r in rows:+ names = store.speaker_names(c, r["id"])+ t0 = datetime.fromisoformat(r["started_at"])+ hits = []+ for sg in c.execute("select start_s, label, text from segments where recording_id=? order by start_s", (r["id"],)):+ low = sg["text"].lower()+ if any(t in low for t in terms):+ hits.append({"at": (t0 + timedelta(seconds=sg["start_s"])).isoformat(timespec="seconds"),+ "speaker": names.get(sg["label"], {}).get("display") or "Speaker", "text": sg["text"]})+ summ = (r["summary_text"] or "")+ sl = summ.lower()+ i = min([sl.find(t) for t in terms if t in sl] or [-1])+ summary_snip = None+ if i >= 0:+ a0, a1 = max(0, i - 60), i + 160+ summary_snip = (("... " if a0 > 0 else "") + summ[a0:a1].replace(chr(10), " ").strip()+ + (" ..." if a1 < len(summ) else ""))+ out.append({"id": r["id"], "day": r["day"], "started_at": r["started_at"], "duration_s": r["duration_s"],+ "trigger": r["trigger"], "title": r["title"], "speakers": [v["display"] for v in names.values()],+ "summary_hit": summary_snip, "hit_count": len(hits), "hits": hits[:12]})+ return {"results": out, "terms": terms}+ finally:+ c.close()++[email protected]("/api/speakers")+def speakers():+ c = con()+ try:+ return [{"id": r["id"], "name": r["name"], "is_self": bool(r["is_self"]), "samples": r["samples"],+ "last_heard": r["last_heard"]} for r in c.execute("select * from speakers order by is_self desc, name")]+ finally:+ c.close()++[email protected]("/api/speakers/{sid}")+async def rename_speaker(sid: int, request: Request):+ name = ((await request.json()).get("name") or "").strip()[:60]+ if not name:+ raise HTTPException(422, "name required")+ c = con()+ try:+ try:+ n = c.execute("update speakers set name=? where id=?", (name, sid)).rowcount+ except Exception:+ raise HTTPException(409, "that name is taken")+ if not n:+ raise HTTPException(404, "no such speaker")+ for (rid,) in c.execute("select recording_id from recording_speakers where speaker_id=?", (sid,)).fetchall():+ store.refresh_transcript(c, rid)+ return {"ok": True}+ finally:+ c.close()++[email protected]("/api/speakers/{sid}")+def delete_speaker(sid: int):+ c = con()+ try:+ with db.tx(c):+ rids = [r[0] for r in c.execute("select recording_id from recording_speakers where speaker_id=?", (sid,))]+ c.execute("update recording_speakers set speaker_id=null where speaker_id=?", (sid,))+ c.execute("delete from speakers where id=?", (sid,))+ for rid in rids:+ store.refresh_transcript(c, rid)+ return {"ok": True}+ finally:+ c.close()++[email protected]("/api/speakers/enroll")+async def enroll(file: UploadFile = File(...), name: str = Form("Me"), is_self: str = Form("1")):+ name = name.strip()[:60] or "Me"+ tmp, _, ext = await _save_upload(file)+ dest = config.ENROLL_DIR / f"{uuid.uuid4().hex}{ext}"+ shutil.move(str(tmp), dest)+ c = con()+ try:+ jid = c.execute("insert into jobs(kind, payload, created_at) values('enroll', ?, ?)",+ (json.dumps({"path": str(dest), "name": name, "is_self": is_self in ("1", "true", "on")}),+ db.now_iso())).lastrowid+ finally:+ c.close()+ return {"ok": True, "job_id": jid}+++def _settings_out(s: dict) -> dict:+ """Settings for the dashboard. The API key itself never leaves the PC, only whether one is saved."""+ s["summary"]["api_key_set"] = bool(config.summary_api_key())+ return s++[email protected]("/api/settings")+def get_settings():+ c = con()+ try:+ return _settings_out(db.settings(c))+ finally:+ c.close()+++TIME_RE = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")++[email protected]("/api/settings")+async def put_settings(request: Request):+ body = await request.json()+ c = con()+ try:+ s = db.settings(c)+ auto = body.get("auto") or {}+ if "always_while_worn" in auto:+ s["auto"]["always_while_worn"] = bool(auto["always_while_worn"])+ for d, wins in (auto.get("windows") or {}).items():+ if d not in s["auto"]["windows"]:+ raise HTTPException(422, f"bad weekday {d}")+ clean = []+ for w in wins or []:+ if len(w) != 2 or not all(TIME_RE.match(x or "") for x in w) or w[0] >= w[1]:+ raise HTTPException(422, f"bad window {w} on {d} (start must be before end)")+ clean.append([w[0], w[1]])+ s["auto"]["windows"][d] = sorted(clean)+ cal = auto.get("calendar") or {}+ if "enabled" in cal:+ s["auto"]["calendar"]["enabled"] = bool(cal["enabled"])+ if "lead_min" in cal:+ s["auto"]["calendar"]["lead_min"] = max(0, min(30, int(cal["lead_min"])))+ sil = body.get("silence") or {}+ if "auto_end_min" in sil:+ s["silence"]["auto_end_min"] = max(1, min(30, int(sil["auto_end_min"])))+ if "manual_stop_min" in sil:+ s["silence"]["manual_stop_min"] = max(0, min(120, int(sil["manual_stop_min"])))+ if "gap_min" in (body.get("merge") or {}):+ s["merge"]["gap_min"] = max(0, min(60, int(body["merge"]["gap_min"])))+ if "battery_saver" in (body.get("upload") or {}):+ s["upload"]["battery_saver"] = bool(body["upload"]["battery_saver"])+ summ = body.get("summary") or {}+ changed = False+ if "provider" in summ:+ if summ["provider"] not in summarize.PROVIDERS:+ raise HTTPException(422, f"unknown summary provider {summ['provider']!r}")+ changed |= s["summary"]["provider"] != summ["provider"]+ s["summary"]["provider"] = summ["provider"]+ for k in ("model", "base_url"):+ if k in summ:+ v = str(summ[k] or "").strip()[:300]+ if k == "base_url" and v and not re.match(r"^https?://", v):+ raise HTTPException(422, "base URL must start with http:// or https://")+ changed |= s["summary"][k] != v+ s["summary"][k] = v+ if "api_key" in summ: # "" keeps the saved key; clear_api_key removes it+ key = str(summ["api_key"] or "").strip()+ if key:+ config.set_env_value("SUMMARY_API_KEY", key)+ changed = True+ if summ.get("clear_api_key"):+ config.set_env_value("SUMMARY_API_KEY", "")+ changed = True+ db.set_kv(c, "settings", s)+ if changed:+ db.set_kv(c, "summary_changed_at", db.now_iso()) # the worker retries paused summaries+ return _settings_out(s)+ finally:+ c.close()++[email protected]("/api/summary/test")+def summary_test():+ """Run one tiny summary through the saved provider so the user can see it work (or why not)."""+ c = con()+ try:+ cfg = db.settings(c)["summary"]+ finally:+ c.close()+ try:+ return summarize.test(cfg)+ except Exception as e:+ return {"ok": False, "error": str(e)[:500]}++[email protected]("/api/upload")+async def upload(file: UploadFile = File(...)):+ tmp, sha, ext = await _save_upload(file)+ dur = None+ try:+ out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(tmp)],+ capture_output=True, text=True, timeout=30).stdout.strip()+ dur = float(out) if out else None+ except Exception:+ pass+ started = (datetime.now(timezone.utc) - timedelta(seconds=dur or 0)).isoformat(timespec="seconds")+ rid = "up-" + uuid.uuid4().hex[:16]+ c = con()+ try:+ _store_chunk(c, recording_id=rid, idx=0, is_last=True, started_at=started, chunk_started_at=started,+ duration_s=dur, trigger="manual", device_id="dashboard", sha=sha, src=tmp, ext=ext)+ c.execute("update recordings set trigger='upload' where id=?", (rid,))+ finally:+ c.close()+ return {"ok": True, "recording_id": rid}+++# ---- static ------------------------------------------------------------------++config.STATIC_DIR.mkdir(exist_ok=True)+# Mounted last so every /api route above wins; index.html is served at "/".+app.mount("/", StaticFiles(directory=config.STATIC_DIR, html=True), name="static")+++if __name__ == "__main__":+ import uvicorn+ uvicorn.run(app, host=config.BIND_HOST, port=config.PORT, log_level="info")diff --git a/static/app.js b/static/app.jsnew file mode 100644index 0000000..28f36ee--- /dev/null+++ b/static/app.js@@ -0,0 +1,1215 @@+'use strict';+/* Voice Capture dashboard. Vanilla JS, hash routes, relative API paths. */++/* ================= helpers ================= */+const $ = (sel, root) => (root || document).querySelector(sel);+const view = $('#view');++function esc(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, c => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}++const state = {+ nav: 0, // increments each navigation; stale async renders bail out+ timers: [], // timeouts/intervals cleared on navigation+ cleanups: [], // functions run on navigation+ health: null,+ speakerNames: [],+};++function later(fn, ms) { const t = setTimeout(fn, ms); state.timers.push(t); return t; }+function clearRouteState() {+ state.timers.forEach(t => { clearTimeout(t); clearInterval(t); });+ state.timers = [];+ const c = state.cleanups; state.cleanups = [];+ c.forEach(fn => { try { fn(); } catch (e) { /* ignore */ } });+}++/* ---- storage (optional, always guarded) ---- */+function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }+function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } }++/* ---- toast ---- */+let toastTimer = null;+function toast(msg) {+ const el = $('#toast');+ el.textContent = msg;+ el.hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => { el.hidden = true; }, 3000);+}++/* ---- api ---- */+async function api(path, opts) {+ opts = opts || {};+ const init = { method: opts.method || 'GET', headers: { 'Accept': 'application/json' } };+ if (opts.json !== undefined) {+ init.headers['Content-Type'] = 'application/json';+ init.body = JSON.stringify(opts.json);+ } else if (opts.form) {+ init.body = opts.form; // browser sets multipart boundary+ }+ let res;+ try {+ res = await fetch(path, init);+ } catch (e) {+ throw new Error('Network error: ' + (e && e.message ? e.message : e));+ }+ let data = null;+ const text = await res.text();+ if (text) { try { data = JSON.parse(text); } catch (e) { data = null; } }+ if (!res.ok) {+ let detail = data && data.detail;+ if (detail && typeof detail !== 'string') detail = JSON.stringify(detail);+ throw new Error(detail || ('Request failed (' + res.status + ')'));+ }+ return data;+}++function fail(e) { toast((e && e.message) ? e.message : String(e)); }++/* ---- formatting ---- */+function fmtTime(iso) {+ if (!iso) return '';+ const d = new Date(iso);+ if (isNaN(d)) return '';+ return d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });+}+function fmtDateTime(iso) {+ if (!iso) return '';+ const d = new Date(iso);+ if (isNaN(d)) return '';+ return d.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }) + ', ' + fmtTime(iso);+}+function fmtDay(day) {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day || '');+ if (!m) return day || '';+ const d = new Date(+m[1], +m[2] - 1, +m[3]);+ return d.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });+}+function dayOf(iso) {+ const d = new Date(iso);+ if (isNaN(d)) return null;+ const p = n => String(n).padStart(2, '0');+ return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());+}+function fmtDur(s) {+ if (s == null || isNaN(s)) return '';+ if (s < 60) return Math.round(s) + ' sec';+ const m = Math.round(s / 60);+ if (m < 60) return m + ' min';+ return Math.floor(m / 60) + ' hr ' + (m % 60) + ' min';+}+function fmtClock(s) { // mm:ss countdown+ s = Math.max(0, s);+ return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');+}+function fmtAgo(iso) {+ if (!iso) return 'never';+ const d = new Date(iso);+ if (isNaN(d)) return 'unknown';+ const s = Math.round((Date.now() - d.getTime()) / 1000);+ if (s < 60) return s + ' sec ago';+ if (s < 3600) return Math.round(s / 60) + ' min ago';+ if (s < 86400) return Math.round(s / 3600) + ' hr ago';+ return fmtDateTime(iso);+}++function hashStr(s) {+ let h = 0;+ s = String(s || '');+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;+ return h;+}+function spClassByName(name) { return 'sp-' + (hashStr(name) % 6); }++const TERMINAL = ['done', 'empty', 'failed'];++function statusPill(status) {+ if (!status || status === 'done') return '';+ const cls = status === 'failed' ? 'pill bad' : (status === 'empty' ? 'pill' : 'pill warn');+ const label = { waiting: 'queued', empty: 'no speech' }[status] || status;+ return '<span class="' + cls + '">' + esc(label) + '</span>';+}+function triggerBadge(t) { return t ? '<span class="badge">' + esc(t) + '</span>' : ''; }++function listHtml(items) {+ if (!items || !items.length) return '';+ return '<ul>' + items.map(i => '<li>' + esc(i) + '</li>').join('') + '</ul>';+}+function chipsHtml(items) {+ if (!items || !items.length) return '';+ return '<div class="chips">' + items.map(i => '<span class="chip">' + esc(i) + '</span>').join('') + '</div>';+}+function actionItemsHtml(items) {+ if (!items || !items.length) return '';+ return '<ul>' + items.map(a => {+ if (typeof a === 'string') return '<li>' + esc(a) + '</li>';+ let extra = [];+ if (a.owner) extra.push(esc(a.owner));+ if (a.due) extra.push('due ' + esc(a.due));+ return '<li>' + esc(a.item) + (extra.length ? ' <span class="faint">(' + extra.join(', ') + ')</span>' : '') + '</li>';+ }).join('') + '</ul>';+}++function subBlock(title, inner) {+ return inner ? '<div class="sub-list"><b>' + esc(title) + '</b>' + inner + '</div>' : '';+}++/* two-tap confirm; never window.confirm */+function armConfirm(btn, armedText, action) {+ const orig = btn.textContent;+ btn.addEventListener('click', () => {+ if (btn.dataset.armed === '1') {+ clearTimeout(btn._armTimer);+ btn.dataset.armed = '';+ btn.classList.remove('armed');+ btn.textContent = orig;+ action();+ return;+ }+ btn.dataset.armed = '1';+ btn.classList.add('armed');+ btn.textContent = armedText;+ btn._armTimer = setTimeout(() => {+ btn.dataset.armed = '';+ btn.classList.remove('armed');+ btn.textContent = orig;+ }, 4000);+ });+}++async function copyText(text) {+ try {+ if (navigator.clipboard && navigator.clipboard.writeText) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch (e) { /* fall through */ }+ try {+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ const ok = document.execCommand('copy');+ ta.remove();+ return ok;+ } catch (e) { return false; }+}++function setView(html) { view.innerHTML = html; }++/* ================= health ================= */+function healthSummaryHtml(h) {+ if (!h) return '<span class="muted">Status unavailable.</span>';+ if (h.ok) return '<b>All systems OK.</b>';+ const probs = (h.problems || []);+ return '<b>Problems</b>' + (probs.length ? '<ul>' + probs.map(p => '<li>' + esc(p) + '</li>').join('') + '</ul>' : '<div class="muted">Unknown problem.</div>');+}++async function refreshHealth() {+ const dot = $('#health-dot');+ try {+ const h = await api('api/health');+ state.health = h;+ dot.className = 'status-btn ' + (h && h.ok ? 'ok' : 'warn');+ $('#health-label').textContent = h && h.ok ? 'Pipeline healthy' : 'Needs attention';+ const probs = (h && h.problems) || [];+ dot.title = h && h.ok ? 'All systems OK' : (probs.length ? probs.join('; ') : 'Needs attention');+ } catch (e) {+ state.health = null;+ dot.className = 'status-btn warn';+ $('#health-label').textContent = 'Server unreachable';+ dot.title = 'Cannot reach server: ' + e.message;+ }+ const pop = $('#health-pop');+ if (!pop.hidden) pop.innerHTML = healthSummaryHtml(state.health);+ return state.health;+}++function initTopbar() {+ $('#health-dot').addEventListener('click', e => {+ e.stopPropagation();+ const pop = $('#health-pop');+ if (pop.hidden) {+ pop.innerHTML = healthSummaryHtml(state.health) + '<div style="margin-top:6px"><a href="#/settings">Pipeline details</a></div>';+ pop.hidden = false;+ } else {+ pop.hidden = true;+ }+ });+ document.addEventListener('click', e => {+ const pop = $('#health-pop');+ if (!pop.hidden && !pop.contains(e.target)) pop.hidden = true;+ });+ $('#search-form').addEventListener('submit', e => {+ e.preventDefault();+ const q = $('#search-input').value.trim();+ if (!q) return;+ lsSet('vc_last_q', q);+ location.hash = '#/search?q=' + encodeURIComponent(q);+ $('#search-input').blur();+ });+ document.addEventListener('keydown', e => {+ if (e.key === '/' && !/^(INPUT|TEXTAREA|SELECT)$/.test((e.target && e.target.tagName) || '')) {+ e.preventDefault();+ $('#search-input').focus();+ }+ });+ const last = lsGet('vc_last_q');+ if (last) $('#search-input').value = last;+ refreshHealth();+ setInterval(refreshHealth, 30000);+}++/* ================= router ================= */+function parseHash() {+ const raw = (location.hash || '#/').replace(/^#/, '') || '/';+ const qi = raw.indexOf('?');+ const path = qi >= 0 ? raw.slice(0, qi) : raw;+ const params = new URLSearchParams(qi >= 0 ? raw.slice(qi + 1) : '');+ return { path, params };+}++function route() {+ clearRouteState();+ const token = ++state.nav;+ const { path, params } = parseHash();+ const parts = path.split('/').filter(Boolean);+ window.scrollTo(0, 0);+ let p;+ if (parts.length === 0) p = renderDays(token);+ else if (parts[0] === 'today') p = renderDay(token, todayStr(), 'today');+ else if (parts[0] === 'day' && parts[1]) p = renderDay(token, decodeURIComponent(parts[1]), decodeURIComponent(parts[1]) === todayStr() ? 'today' : 'days');+ else if (parts[0] === 'c' && parts[1]) p = renderConversation(token, decodeURIComponent(parts[1]));+ else if (parts[0] === 'search') p = renderSearch(token, params);+ else if (parts[0] === 'settings') p = renderSettings(token);+ else p = renderDays(token);+ if (p && p.catch) p.catch(e => {+ if (token !== state.nav) return;+ setView('<div class="notice">' + esc(e.message || e) + '</div>');+ fail(e);+ });+}++/* ================= shared UI bits ================= */+const ICON_CHEV = '<svg class="chev" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M7.3 4.3 8.4 3.2 15.2 10l-6.8 6.8-1.1-1.1L12.9 10z"/></svg>';+const ICON_COPY = '<svg viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M7 2h8.5A2.5 2.5 0 0 1 18 4.5V13a2.5 2.5 0 0 1-2.5 2.5H15V14h.5c.5 0 .9-.4.9-.9V4.5c0-.5-.4-.9-.9-.9H7c-.5 0-.9.4-.9.9V5H4.5v-.5A2.5 2.5 0 0 1 7 2zM4.5 6H13a2.5 2.5 0 0 1 2.5 2.5V16A2.5 2.5 0 0 1 13 18.5H4.5A2.5 2.5 0 0 1 2 16V8.5A2.5 2.5 0 0 1 4.5 6zm0 1.6c-.5 0-.9.4-.9.9V16c0 .5.4.9.9.9H13c.5 0 .9-.4.9-.9V8.5c0-.5-.4-.9-.9-.9H4.5z"/></svg>';++function initials(name) {+ name = String(name || '?').trim();+ const m = /^speaker\s+([a-z0-9]+)$/i.exec(name);+ if (m) return m[1].slice(0, 2).toUpperCase();+ const parts = name.split(/\s+/).filter(Boolean);+ return ((parts[0] || '?')[0] + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase();+}+function avatarHtml(name, cls, small) {+ return '<span class="avatar ' + (small ? 'sm ' : '') + (cls || spClassByName(name)) + '" title="' + esc(name) + '">' + esc(initials(name)) + '</span>';+}+function triggerBadgeHtml(t) {+ if (!t) return '';+ const label = { manual: 'Button', auto: 'Auto', calendar: 'Meeting', upload: 'Upload' }[t] || t;+ return '<span class="badge ' + esc(t) + '">' + esc(label) + '</span>';+}+function pageHead(title, subParts, actions, crumb) {+ const sub = (subParts || []).filter(Boolean);+ return '<header class="page-head"><div style="min-width:0">' + (crumb || '') ++ '<h1>' + title + '</h1>' ++ (sub.length ? '<div class="sub">' + sub.join('<span class="sep">/</span>') + '</div>' : '') ++ '</div>' + (actions ? '<div class="actions">' + actions + '</div>' : '') + '</header>';+}+function fmtDayLong(day) {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day || '');+ if (!m) return day || '';+ return new Date(+m[1], +m[2] - 1, +m[3]).toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric' });+}+function todayStr() { return dayOf(new Date().toISOString()); }+function setActiveNav(name) {+ document.querySelectorAll('.side-nav a').forEach(a => a.classList.toggle('active', a.dataset.nav === name));+}++/* ================= views: all days ================= */+async function renderDays(token) {+ setActiveNav('days');+ setView('<p class="loading">Loading...</p>');+ const days = await api('api/days?limit=60');+ if (token !== state.nav) return;+ const head = pageHead('Conversations', ['Everything your watch has captured, newest first']);+ if (!days || !days.length) {+ setView(head + '<div class="empty">No recordings yet. Start one on the watch, or upload a test file in Settings.</div>');+ return;+ }+ const weekAgo = dayOf(new Date(Date.now() - 6 * 86400000).toISOString());+ const week = days.filter(d => d.day >= weekAgo);+ const sum = (arr, k) => arr.reduce((a, d) => a + (+d[k] || 0), 0);+ const today = days.find(d => d.day === todayStr());+ const stats =+ '<div class="stats">' ++ '<div class="stat"><div class="label">Today</div><div class="value">' + (today ? today.conversations : 0) + '<small>conversations</small></div></div>' ++ '<div class="stat"><div class="label">Last 7 days</div><div class="value">' + sum(week, 'conversations') + '<small>conversations</small></div></div>' ++ '<div class="stat"><div class="label">Speech, last 7 days</div><div class="value">' + Math.round(sum(week, 'speech_minutes')) + '<small>min</small></div></div>' ++ '<div class="stat"><div class="label">Days recorded</div><div class="value">' + days.length + '</div></div>' ++ '</div>';+ const rows = days.map(d => {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(d.day);+ const dt = m ? new Date(+m[1], +m[2] - 1, +m[3]) : null;+ return '<a class="row" href="#/day/' + esc(d.day) + '">' ++ '<div class="date-tile"><div class="dow">' + (dt ? esc(dt.toLocaleDateString([], { weekday: 'short' })) : '') + '</div><div class="num">' + (dt ? dt.getDate() : '') + '</div></div>' ++ '<div class="grow"><div class="card-title clamp2">' + (d.headline ? esc(d.headline) : '<span class="muted">Daily summary pending</span>') + '</div>' ++ '<div class="row-meta"><span>' + esc(fmtDayLong(d.day)) + '</span><span>' + esc(d.conversations) + ' conversation' + (d.conversations === 1 ? '' : 's') + '</span><span>' + esc(Math.round(d.speech_minutes || 0)) + ' min of speech</span></div></div>' ++ ICON_CHEV + '</a>';+ }).join('');+ setView(head + stats + '<div class="list">' + rows + '</div>');+}++/* ================= views: day ================= */+function convItemHtml(c) {+ const spk = (c.speakers || []);+ return '<div class="tl-item"><div class="tl-time">' + esc(fmtTime(c.started_at)) + (c.duration_s != null ? '<small>' + esc(fmtDur(c.duration_s)) + '</small>' : '') + '</div>' ++ '<a class="card tl-card" href="#/c/' + encodeURIComponent(c.id) + '">' ++ '<div class="top"><div class="card-title">' + (c.title ? esc(c.title) : '<span class="muted">Untitled conversation</span>') + '</div>' ++ '<div style="display:flex;gap:6px;flex:none">' + triggerBadgeHtml(c.trigger) + statusPill(c.status) + '</div></div>' ++ (c.summary_short ? '<div class="card-text clamp2">' + esc(c.summary_short) + '</div>' : '') ++ (spk.length ? '<div class="foot"><div class="avatars">' + spk.slice(0, 5).map(n => avatarHtml(n, null, true)).join('') + '</div>' ++ '<div class="card-meta" style="margin:0">' + esc(spk.join(', ')) + '</div></div>' : '') ++ '</a></div>';+}++async function renderDay(token, day, navName) {+ setActiveNav(navName || 'days');+ setView('<p class="loading">Loading...</p>');+ const d = await api('api/days/' + encodeURIComponent(day));+ if (token !== state.nav) return;+ const s = d.summary;+ // newest first on screen (copy-day text keeps its own oldest-first order)+ const convs = (d.conversations || []).slice().sort((a, b) => String(b.started_at).localeCompare(String(a.started_at)));+ const shown = convs.filter(c => c.status !== 'empty');+ const empties = convs.filter(c => c.status === 'empty');+ const mins = Math.round(shown.reduce((a, c) => a + (+c.duration_s || 0), 0) / 60);+ const people = [...new Set(shown.flatMap(c => c.speakers || []))];++ const summary = s+ ? '<div class="card"><h3>Day summary</h3>' ++ (s.headline ? '<div class="card-title" style="margin-bottom:8px">' + esc(s.headline) + '</div>' : '') ++ (s.summary ? '<p class="card-text" style="margin:0 0 6px">' + esc(s.summary) + '</p>' : '') ++ subBlock('Key points', listHtml(s.key_points)) ++ subBlock('Action items', actionItemsHtml(s.action_items)) ++ '</div>'+ : '<div class="card"><h3>Day summary</h3><p class="muted" style="margin:0">Builds automatically after the conversations finish.</p></div>';+ const peopleCard = people.length+ ? '<div class="card"><h3>People</h3><div class="spk-list">' + people.map(n => '<div class="spk-item" style="cursor:default">' + avatarHtml(n) + '<div class="grow">' + esc(n) + '</div></div>').join('') + '</div></div>'+ : '';++ const isToday = day === todayStr();+ setView(+ pageHead(esc(isToday ? 'Today' : fmtDayLong(d.day || day)),+ [isToday ? esc(fmtDayLong(day)) : '', shown.length + ' conversation' + (shown.length === 1 ? '' : 's'), mins + ' min recorded'],+ '<button class="btn" id="btn-copy-day" type="button">' + ICON_COPY + 'Copy whole day</button>',+ navName === 'today' ? '' : '<a class="crumb" href="#/">← All conversations</a>') ++ '<div class="split"><div>' ++ (shown.length ? '<div class="timeline">' + shown.map(convItemHtml).join('') + '</div>' : '<div class="empty">No conversations with speech yet.</div>') ++ (empties.length ? '<button class="toggle-link" id="empty-toggle" type="button">Show ' + empties.length + ' empty recording' + (empties.length === 1 ? '' : 's') + '</button><div id="empty-list" class="timeline" hidden>' + empties.map(convItemHtml).join('') + '</div>' : '') ++ '</div><aside>' + summary + peopleCard + '</aside></div>'+ );+ $('#btn-copy-day').addEventListener('click', async () => {+ try {+ const full = await Promise.all(shown.map(c => api('api/conversations/' + encodeURIComponent(c.id))));+ const ok = await copyText(dayText(d.day || day, d, full));+ toast(ok ? 'Copied the whole day' : 'Could not copy');+ } catch (e) { fail(e); }+ });+ const tg = $('#empty-toggle');+ if (tg) tg.addEventListener('click', () => {+ const list = $('#empty-list');+ list.hidden = !list.hidden;+ tg.textContent = list.hidden ? 'Show ' + empties.length + ' empty recording' + (empties.length === 1 ? '' : 's') : 'Hide empty recordings';+ });+ if (convs.some(c => !TERMINAL.includes(c.status))) {+ later(() => { if (token === state.nav) renderDay(token, day, navName).catch(() => {}); }, 15000);+ }+}++/* ================= views: conversation ================= */+const convUI = { editLabel: null };++function groupSegments(segments) {+ const blocks = [];+ (segments || []).forEach(seg => {+ const key = seg.label == null ? '' : seg.label;+ const last = blocks[blocks.length - 1];+ // Same speaker continues the paragraph, but start a new one (with its own time) every ~60 s.+ if (last && last.key === key && last.display === seg.display && (seg.start_s - last.start_s) < 60) {+ last.text += ' ' + (seg.text || '').trim();+ } else {+ blocks.push({ key, label: seg.label, display: seg.display, at: seg.at, start_s: seg.start_s, text: (seg.text || '').trim() });+ }+ });+ return blocks;+}++function speakerClassFor(conv, label, display) {+ const spk = conv.speakers || [];+ const idx = spk.findIndex(s => s.label === label);+ if (idx >= 0 && spk[idx].is_self) return 'sp-self';+ if (idx >= 0) return 'sp-' + (idx % 6);+ return spClassByName(label || display);+}++function transcriptPlain(conv) {+ return groupSegments(conv.segments).map(b => (b.display || 'Unknown') + ': ' + b.text).join('\n');+}++/* ---- copy text builders (shared by conversation + whole-day copy) ---- */+function plainTime(iso) {+ const d = new Date(iso);+ if (isNaN(d)) return '';+ return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });+}+function plainDateTime(iso) {+ const d = new Date(iso);+ if (isNaN(d)) return '';+ return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }).replace(/,\s*(\d{4})$/, ' $1') + ', ' + plainTime(iso);+}+function plainList(arr) { return (arr || []).filter(Boolean).map(x => '- ' + x); }+function plainActions(arr) {+ return (arr || []).filter(a => a && a.item).map(a => {+ const bits = [];+ if (a.owner) bits.push('owner: ' + a.owner);+ if (a.due) bits.push('due: ' + a.due);+ return '- ' + a.item + (bits.length ? ' (' + bits.join(', ') + ')' : '');+ });+}+function conversationText(conv) {+ const out = [];+ out.push(conv.title || (conv.summary && conv.summary.title) || 'Untitled conversation');+ const meta = [];+ const when = plainDateTime(conv.started_at);+ if (when) meta.push(when);+ if (conv.duration_s != null && !isNaN(conv.duration_s)) meta.push(Math.max(1, Math.round(conv.duration_s / 60)) + ' min');+ const names = (conv.speakers || []).map(s => s.display || s.label).filter(Boolean);+ if (names.length) meta.push(names.join(', '));+ if (meta.length) out.push(meta.join(' · '));+ const s = conv.summary;+ if (s) {+ const sec = [];+ if (s.summary) sec.push(s.summary);+ const kp = plainList(s.key_points);+ if (kp.length) sec.push('', 'Key points', ...kp);+ const dc = plainList(s.decisions);+ if (dc.length) sec.push('', 'Decisions', ...dc);+ const ai = plainActions(s.action_items);+ if (ai.length) sec.push('', 'Action items', ...ai);+ if (s.people && s.people.length) sec.push('', 'People: ' + s.people.join(', '));+ if (s.topics && s.topics.length) sec.push('Topics: ' + s.topics.join(', '));+ if (sec.length) out.push('', 'SUMMARY', ...sec);+ }+ const blocks = groupSegments(conv.segments);+ if (blocks.length) {+ out.push('', 'TRANSCRIPT');+ blocks.forEach(b => out.push('[' + plainTime(b.at) + '] ' + (b.display || 'Unknown') + ': ' + b.text));+ }+ return out.join('\n');+}+function dayText(day, d, convs) {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day || '');+ const label = m+ ? new Date(+m[1], +m[2] - 1, +m[3]).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' }).replace(/,\s*(\d{4})$/, ' $1')+ : (day || '');+ const out = [label];+ const s = d && d.summary;+ if (s) {+ out.push('', 'DAY SUMMARY');+ if (s.headline) out.push(s.headline);+ if (s.summary) out.push(s.summary);+ out.push(...plainList(s.key_points));+ const ai = plainActions(s.action_items);+ if (ai.length) out.push('Action items', ...ai);+ }+ const sorted = convs.slice().sort((a, b) => String(a.started_at).localeCompare(String(b.started_at)));+ sorted.forEach(c => out.push('', '==============================', conversationText(c)));+ return out.join('\n');+}++const convTab = { name: 'summary' };++function renderConvView(conv, token) {+ setActiveNav('days');+ const s = conv.summary;+ const speakers = conv.speakers || [];+ const blocks = groupSegments(conv.segments);+ const spCls = sp => sp.is_self ? 'sp-self' : 'sp-' + (speakers.indexOf(sp) % 6);++ let summaryPanel;+ if (s) {+ const todos = (s.action_items || []).filter(a => a && (a.item || typeof a === 'string')).map(a => {+ const item = typeof a === 'string' ? a : a.item;+ const tags = typeof a === 'string' ? '' : (a.owner ? '<span class="pill">' + esc(a.owner) + '</span>' : '') + (a.due ? '<span class="pill">Due ' + esc(a.due) + '</span>' : '');+ return '<div class="todo"><span class="box"></span><div><div class="what">' + esc(item) + '</div>' + (tags ? '<div class="tags">' + tags + '</div>' : '') + '</div></div>';+ }).join('');+ const list = (arr, cls) => (arr && arr.length) ? '<ul class="block-list ' + (cls || '') + '">' + arr.map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>' : '';+ summaryPanel =+ (s.summary ? '<div class="card"><h3>Overview</h3><p class="overview">' + esc(s.summary) + '</p></div>' : '') ++ (todos ? '<div class="card"><h3>Action items</h3>' + todos + '</div>' : '') ++ ((s.key_points || []).length ? '<div class="card"><h3>Key points</h3>' + list(s.key_points) + '</div>' : '') ++ ((s.decisions || []).length ? '<div class="card"><h3>Decisions</h3>' + list(s.decisions, 'decisions') + '</div>' : '');+ } else {+ const msg = TERMINAL.includes(conv.status) ? 'No summary for this conversation (too short to summarize).' : 'The summary appears when processing finishes.';+ summaryPanel = '<div class="card"><p class="muted" style="margin:0">' + esc(msg) + '</p></div>';+ }++ const transcriptPanel = '<div class="card" style="padding:0"><div class="transcript" id="transcript">' + (blocks.length ? blocks.map(b => {+ const cls = speakerClassFor(conv, b.label, b.display);+ return '<div class="utt">' + avatarHtml(b.display || 'Unknown', cls) + '<div><div class="utt-head"><span class="sp-name ' + cls + '">' + esc(b.display || 'Unknown') + '</span>' ++ '<span class="t">' + esc(fmtTime(b.at)) + '</span></div><div class="utt-text">' + esc(b.text) + '</div></div></div>';+ }).join('') : '<p class="muted" style="margin:0;padding:16px 20px">' + (conv.status === 'empty' ? 'No speech was found in this recording.' : 'No transcript yet.') + '</p>') + '</div></div>';++ const range = fmtTime(conv.started_at) + (conv.ended_at ? ' - ' + fmtTime(conv.ended_at) : '');+ const details = '<div class="card"><h3>Details</h3><dl class="details">' ++ '<dt>Date</dt><dd>' + esc(fmtDayLong(dayOf(conv.started_at))) + '</dd>' ++ '<dt>Time</dt><dd>' + esc(range) + '</dd>' ++ (conv.duration_s != null ? '<dt>Length</dt><dd>' + esc(fmtDur(conv.duration_s)) + '</dd>' : '') ++ '<dt>Started by</dt><dd>' + triggerBadgeHtml(conv.trigger) + '</dd>' ++ '<dt>Words</dt><dd>' + esc(blocks.reduce((a, b) => a + b.text.split(/\s+/).filter(Boolean).length, 0)) + '</dd>' ++ '</dl></div>';+ const spkCard = speakers.length ? '<div class="card"><h3>Speakers</h3><div class="spk-list" id="spk-chips">' + speakers.map(sp =>+ '<button type="button" class="spk-item" data-label="' + esc(sp.label) + '">' + avatarHtml(sp.display || sp.label, spCls(sp)) ++ '<span class="grow">' + esc(sp.display || sp.label) + (sp.is_self ? ' <span class="you">You</span>' : '') + '</span>' ++ '<span class="hint">' + (sp.speaker_id != null ? 'Rename' : 'Name') + '</span></button>').join('') ++ '</div><div id="spk-form"></div></div>' : '';+ const tagCard = (title, arr) => (arr && arr.length) ? '<div class="card"><h3>' + title + '</h3>' + chipsHtml(arr) + '</div>' : '';++ const tab = convTab.name;+ setView(+ pageHead(conv.title ? esc(conv.title) : 'Untitled conversation',+ [esc(fmtDateTime(conv.started_at)), conv.duration_s != null ? esc(fmtDur(conv.duration_s)) : '', triggerBadgeHtml(conv.trigger) + statusPill(conv.status)],+ '<button class="btn primary" id="btn-copy" type="button">' + ICON_COPY + 'Copy summary + transcript</button>' ++ '<button class="btn" id="btn-resum" type="button">Re-summarize</button>' ++ '<button class="btn" id="btn-merge" type="button">Merge with previous</button>' ++ '<button class="btn danger" id="btn-del" type="button">Delete</button>',+ '<a class="crumb" href="#/day/' + esc(dayOf(conv.started_at) || '') + '">← ' + esc(fmtDayLong(dayOf(conv.started_at))) + '</a>') ++ (conv.error ? '<div class="notice">' + esc(conv.error) + '</div>' : '') ++ '<div class="split"><div>' ++ '<div class="tabs" role="tablist">' ++ '<button class="tab' + (tab === 'summary' ? ' active' : '') + '" data-tab="summary" type="button" role="tab">Summary</button>' ++ '<button class="tab' + (tab === 'transcript' ? ' active' : '') + '" data-tab="transcript" type="button" role="tab">Transcript<span class="count">' + blocks.length + '</span></button>' ++ '</div>' ++ '<div id="pane-summary"' + (tab === 'summary' ? '' : ' hidden') + '>' + summaryPanel + '</div>' ++ '<div id="pane-transcript"' + (tab === 'transcript' ? '' : ' hidden') + '>' + transcriptPanel + '</div>' ++ '</div><aside>' + details + spkCard + tagCard('Topics', s && s.topics) + tagCard('People mentioned', s && s.people) + '</aside></div>'+ );++ document.querySelectorAll('.tab').forEach(b => b.addEventListener('click', () => {+ convTab.name = b.dataset.tab;+ document.querySelectorAll('.tab').forEach(x => x.classList.toggle('active', x === b));+ $('#pane-summary').hidden = convTab.name !== 'summary';+ $('#pane-transcript').hidden = convTab.name !== 'transcript';+ }));+ $('#btn-copy').addEventListener('click', async () => {+ const ok = await copyText(conversationText(conv));+ toast(ok ? 'Copied summary and transcript' : 'Could not copy');+ });+ $('#btn-resum').addEventListener('click', async () => {+ try {+ await api('api/conversations/' + encodeURIComponent(conv.id) + '/resummarize', { method: 'POST' });+ toast('Re-summarizing...');+ } catch (e) { fail(e); }+ });+ $('#btn-merge').addEventListener('click', async () => {+ if (!confirm('Join this conversation onto the one right before it?')) return;+ try {+ const res = await api('api/conversations/' + encodeURIComponent(conv.id) + '/merge-previous', { method: 'POST' });+ location.hash = '#/c/' + encodeURIComponent(res.into);+ } catch (e) { fail(e); }+ });+ armConfirm($('#btn-del'), 'Tap again to delete', async () => {+ try {+ await api('api/conversations/' + encodeURIComponent(conv.id), { method: 'DELETE' });+ toast('Deleted');+ const dd = dayOf(conv.started_at);+ location.hash = dd ? '#/day/' + dd : '#/';+ } catch (e) { fail(e); }+ });++ const chipsEl = $('#spk-chips');+ if (chipsEl) chipsEl.addEventListener('click', e => {+ const b = e.target.closest('button[data-label]');+ if (!b) return;+ openSpeakerForm(conv, b.dataset.label, token);+ });+ if (convUI.editLabel && speakers.some(sp => sp.label === convUI.editLabel)) {+ openSpeakerForm(conv, convUI.editLabel, token, true);+ } else {+ convUI.editLabel = null;+ }+}++function openSpeakerForm(conv, label, token, keepValue) {+ convUI.editLabel = label;+ const sp = (conv.speakers || []).find(s => s.label === label) || {};+ const host = $('#spk-form');+ if (!host) return;+ const names = state.speakerNames.map(n => '<option value="' + esc(n) + '"></option>').join('');+ host.innerHTML =+ '<form class="spk-form" id="spk-form-el" autocomplete="off">' ++ '<input type="text" id="spk-name" list="spk-names" placeholder="Who is this?" aria-label="Who is this?" value="' + esc(sp.speaker_id != null ? (sp.display || '') : '') + '">' ++ '<datalist id="spk-names">' + names + '</datalist>' ++ '<button class="btn primary" type="submit">Save</button>' ++ '<button class="btn ghost" type="button" id="spk-cancel">Cancel</button>' ++ '</form>';+ const input = $('#spk-name');+ if (!keepValue) input.focus();+ $('#spk-cancel').addEventListener('click', () => { convUI.editLabel = null; host.innerHTML = ''; });+ $('#spk-form-el').addEventListener('submit', async e => {+ e.preventDefault();+ const name = input.value.trim();+ if (!name) { toast('Type a name first'); return; }+ try {+ const updated = await api('api/conversations/' + encodeURIComponent(conv.id) + '/speakers/' + encodeURIComponent(label), { method: 'POST', json: { name } });+ if (token !== state.nav) return;+ convUI.editLabel = null;+ if (!state.speakerNames.includes(name)) state.speakerNames.push(name);+ toast('Saved');+ renderConvView(updated, token);+ scheduleConvRefresh(updated.id, updated.status, token);+ } catch (err) { fail(err); }+ });+}++function scheduleConvRefresh(id, status, token) {+ if (TERMINAL.includes(status)) return;+ later(async () => {+ if (token !== state.nav) return;+ if (convUI.editLabel) { scheduleConvRefresh(id, status, token); return; }+ try {+ const c = await api('api/conversations/' + encodeURIComponent(id));+ if (token !== state.nav) return;+ if (!convUI.editLabel) renderConvView(c, token);+ scheduleConvRefresh(id, c.status, token);+ } catch (e) { scheduleConvRefresh(id, status, token); }+ }, 10000);+}++async function renderConversation(token, id) {+ setView('<p class="loading">Loading...</p>');+ convUI.editLabel = null;+ const [conv, names] = await Promise.all([+ api('api/conversations/' + encodeURIComponent(id)),+ api('api/speakers').catch(() => []),+ ]);+ if (token !== state.nav) return;+ state.speakerNames = (names || []).map(n => n.name).filter(Boolean);+ renderConvView(conv, token);+ scheduleConvRefresh(conv.id, conv.status, token);+}++/* ================= views: search ================= */+function searchTerms(q) {+ const out = [];+ String(q || '').replace(/"([^"]+)"|(\S+)/g, (m, a, b) => { const t = (a || b || '').trim(); if (t.length >= 2) out.push(t); return m; });+ return out;+}+function highlight(text, q) {+ const safe = esc(text);+ const terms = (Array.isArray(q) ? q : searchTerms(q)).map(t => esc(t).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));+ if (!terms.length) return safe;+ return safe.replace(new RegExp('(' + terms.join('|') + ')', 'gi'), '<mark>$1</mark>');+}++async function renderSearch(token, params) {+ setActiveNav('search');+ const q = params.get('q') || '';+ const from = params.get('from') || '';+ const to = params.get('to') || '';+ const sp = params.get('sp') || '';+ $('#search-input').value = q;+ const speakers = await api('api/speakers').catch(() => []);+ if (token !== state.nav) return;++ const filters =+ '<form class="card filters" id="search-page-form" autocomplete="off">' ++ '<label class="q">Keywords<input type="search" name="q" value="' + esc(q) + '" placeholder="e.g. priya security, or "exact phrase"" enterkeyhint="search"></label>' ++ '<label>From<input type="date" name="from" value="' + esc(from) + '"></label>' ++ '<label>To<input type="date" name="to" value="' + esc(to) + '"></label>' ++ '<label>Person<select name="sp"><option value="">Anyone</option>' ++ (speakers || []).map(s => '<option value="' + esc(s.id) + '"' + (String(s.id) === sp ? ' selected' : '') + '>' + esc(s.name) + '</option>').join('') ++ '</select></label>' ++ '<button class="btn primary" type="submit">Search</button>' ++ '</form>';++ const head = pageHead('Search', ['Keyword search across every conversation. All words must appear, in any order. Use quotes for an exact phrase.']);+ const bind = () => {+ $('#search-page-form').addEventListener('submit', e => {+ e.preventDefault();+ const f = new FormData(e.target);+ const p = new URLSearchParams();+ ['q', 'from', 'to', 'sp'].forEach(k => { const v = String(f.get(k) || '').trim(); if (v) p.set(k, v); });+ if (p.get('q')) lsSet('vc_last_q', p.get('q'));+ location.hash = '#/search?' + p.toString();+ });+ };+ if (!searchTerms(q).length) {+ setView(head + filters + '<div class="empty">Type a word or two to search all your conversations.</div>');+ bind();+ return;+ }+ setView(head + filters + '<p class="loading">Searching...</p>');+ bind();+ const qs = new URLSearchParams({ q });+ if (from) qs.set('date_from', from);+ if (to) qs.set('date_to', to);+ if (sp) qs.set('speaker', sp);+ const res = await api('api/search?' + qs.toString());+ if (token !== state.nav) return;+ const results = (res && res.results) || [];+ const terms = (res && res.terms) || searchTerms(q);+ let body;+ if (!results.length) {+ body = '<div class="empty">No conversations match “' + esc(q) + '”' + (from || to || sp ? ' with these filters' : '') + '.</div>';+ } else {+ const totalHits = results.reduce((a, r) => a + (r.hit_count || 0), 0);+ body = '<div class="section-title"><h2>' + results.length + ' conversation' + (results.length === 1 ? '' : 's') + '</h2><span class="card-meta">' + totalHits + ' matching line' + (totalHits === 1 ? '' : 's') + '</span></div>' ++ results.map(r => {+ const hits = (r.hits || []).map(h =>+ '<a class="hit" href="#/c/' + encodeURIComponent(r.id) + '"><span class="t">' + esc(fmtTime(h.at)) + '</span><div><b>' + esc(h.speaker) + '</b>' + highlight(h.text, terms) + '</div></a>').join('');+ const more = (r.hit_count || 0) - (r.hits || []).length;+ return '<div class="card result">' ++ '<a class="result-head" href="#/c/' + encodeURIComponent(r.id) + '">' ++ '<div style="display:flex;justify-content:space-between;gap:10px;align-items:center"><div class="card-title">' + (r.title ? highlight(r.title, terms) : '<span class="muted">Untitled conversation</span>') + '</div>' + triggerBadgeHtml(r.trigger) + '</div>' ++ '<div class="row-meta"><span>' + esc(fmtDateTime(r.started_at)) + '</span>' + (r.duration_s != null ? '<span>' + esc(fmtDur(r.duration_s)) + '</span>' : '') ++ ((r.speakers || []).length ? '<span>' + esc(r.speakers.join(', ')) + '</span>' : '') + '</div>' ++ (r.summary_hit ? '<div class="card-text">' + highlight(r.summary_hit, terms) + '</div>' : '') ++ '</a>' ++ (hits ? '<div class="hits">' + hits + '</div>' : '') ++ (more > 0 ? '<div class="more">+' + more + ' more matching line' + (more === 1 ? '' : 's') + ' in this conversation</div>' : '') ++ '</div>';+ }).join('');+ }+ const loading = view.querySelector('.loading');+ if (loading) loading.outerHTML = body;+}++/* ================= views: settings ================= */+const DAYS = [['mon', 'Monday'], ['tue', 'Tuesday'], ['wed', 'Wednesday'], ['thu', 'Thursday'], ['fri', 'Friday'], ['sat', 'Saturday'], ['sun', 'Sunday']];++function normalizeSettings(s) {+ s = s || {};+ s.auto = s.auto || {};+ s.auto.always_while_worn = !!s.auto.always_while_worn;+ s.auto.windows = s.auto.windows || {};+ DAYS.forEach(([k]) => { if (!Array.isArray(s.auto.windows[k])) s.auto.windows[k] = []; });+ s.auto.calendar = s.auto.calendar || {};+ s.auto.calendar.enabled = !!s.auto.calendar.enabled;+ s.auto.calendar.lead_min = Number.isFinite(+s.auto.calendar.lead_min) ? +s.auto.calendar.lead_min : 5;+ s.silence = s.silence || {};+ s.silence.auto_end_min = Number.isFinite(+s.silence.auto_end_min) ? +s.silence.auto_end_min : 2;+ s.silence.manual_stop_min = Number.isFinite(+s.silence.manual_stop_min) ? +s.silence.manual_stop_min : 10;+ s.merge = s.merge || {};+ s.merge.gap_min = Number.isFinite(+s.merge.gap_min) ? +s.merge.gap_min : 10;+ s.upload = s.upload || {};+ s.upload.battery_saver = !!s.upload.battery_saver;+ s.summary = s.summary || {};+ s.summary.provider = s.summary.provider || 'claude_subscription';+ s.summary.model = s.summary.model || '';+ s.summary.base_url = s.summary.base_url || '';+ s.summary.api_key_set = !!s.summary.api_key_set;+ return s;+}++function healthBlockHtml(h) {+ if (!h) return '<p class="muted" style="margin:0">Could not load status.</p>';+ const w = h.worker || {};+ const q = h.queue || {};+ const rows = [+ ['Overall', h.ok ? '<span class="pill ok">OK</span>' : '<span class="pill warn">Needs attention</span>'],+ ['Worker', (w.alive ? '<span class="pill ok">running</span>' : '<span class="pill bad">stopped</span>') + ' <span class="muted">' + esc(w.state || '') + (w.last_tick ? ' · last tick ' + esc(fmtAgo(w.last_tick)) : '') + '</span>'],+ ['Queue', esc(q.receiving || 0) + ' receiving, ' + esc(q.waiting || 0) + ' waiting, ' + esc(q.transcribing || 0) + ' transcribing, ' + esc(q.summarizing || 0) + ' summarizing, ' + esc(q.failed || 0) + ' failed'],+ ['Hugging Face token', h.hf_token ? 'Yes' : 'No'],+ ['Summaries', esc(h.summary || 'not set')],+ ['Calendar', h.calendar ? 'Connected' : 'Not set up'],+ ];+ let html = '<dl class="kv">' + rows.map(r => '<dt>' + esc(r[0]) + '</dt><dd>' + r[1] + '</dd>').join('') + '</dl>';+ if (!h.hf_token) html += '<div class="notice" style="margin-top:10px;margin-bottom:0">Speaker labels are off until a Hugging Face token is added.</div>';+ if (h.problems && h.problems.length) html += '<div style="margin-top:10px"><b>Problems</b>' + listHtml(h.problems) + '</div>';+ return html;+}++function windowsHtml(st) {+ return DAYS.map(([k, label]) => {+ const wins = st.auto.windows[k];+ return '<div class="day-row"><div class="day-name">' + esc(label) + '</div>' ++ (wins.length ? wins.map((w, i) =>+ '<div class="win"><input type="time" data-day="' + k + '" data-i="' + i + '" data-k="0" value="' + esc(w[0] || '') + '" aria-label="' + esc(label) + ' start">' ++ '<span class="dash">to</span>' ++ '<input type="time" data-day="' + k + '" data-i="' + i + '" data-k="1" value="' + esc(w[1] || '') + '" aria-label="' + esc(label) + ' end">' ++ '<button type="button" class="btn small ghost" data-act="rm" data-day="' + k + '" data-i="' + i + '">Remove</button></div>'+ ).join('') : '<div class="faint" style="font-size:13px;margin-bottom:6px">No windows</div>') ++ '<button type="button" class="btn small" data-act="add" data-day="' + k + '">Add window</button>' ++ '</div>';+ }).join('');+}++function speakersListHtml(list, editingId) {+ if (!list || !list.length) return '<p class="muted" style="margin:0">No voices enrolled yet.</p>';+ return list.map(sp => {+ const meta = esc(sp.samples || 0) + ' sample' + (sp.samples === 1 ? '' : 's') + ' · last heard ' + (sp.last_heard ? esc(fmtDateTime(sp.last_heard)) : 'never');+ const name = editingId === sp.id+ ? '<input type="text" data-rename-input="' + sp.id + '" value="' + esc(sp.name) + '" aria-label="Speaker name">'+ : '<div class="card-title">' + esc(sp.name) + (sp.is_self ? ' <span class="badge">you</span>' : '') + '</div><div class="card-meta">' + meta + '</div>';+ const actions = editingId === sp.id+ ? '<button class="btn small primary" type="button" data-act="rename-save" data-id="' + sp.id + '">Save</button><button class="btn small ghost" type="button" data-act="rename-cancel">Cancel</button>'+ : '<button class="btn small" type="button" data-act="rename" data-id="' + sp.id + '">Rename</button><button class="btn small danger" type="button" data-act="delete" data-id="' + sp.id + '">Delete</button>';+ return '<div class="spk-row"><div class="grow">' + name + '</div><div class="spk-actions">' + actions + '</div></div>';+ }).join('');+}++const PROVIDERS = [+ ['claude_subscription', 'Claude subscription (Claude Code login)'],+ ['codex_subscription', 'ChatGPT subscription (Codex CLI login)'],+ ['openai_compatible', 'API key or local model (OpenAI-compatible)'],+];+const ENDPOINTS = [+ ['', 'Pick a service...'],+ ['https://api.openai.com/v1', 'OpenAI'],+ ['http://localhost:11434/v1', 'Ollama (local, free)'],+ ['http://localhost:1234/v1', 'LM Studio (local, free)'],+ ['https://openrouter.ai/api/v1', 'OpenRouter'],+ ['https://generativelanguage.googleapis.com/v1beta/openai', 'Google Gemini'],+ ['https://api.anthropic.com/v1', 'Anthropic API'],+];+const PROVIDER_HELP = {+ claude_subscription: 'Uses the Claude Code sign-in on this PC. No API charges. Leave the model empty for Sonnet, or type opus or haiku.',+ codex_subscription: 'Uses the Codex CLI signed in with your ChatGPT account (run "codex login" once). No API charges. Leave the model empty for the Codex default.',+ openai_compatible: 'Any service with an OpenAI-style API. Cloud services need a key and bill per use. Ollama and LM Studio run on this PC for free and need no key.',+};++function summaryFieldsHtml(st) {+ const sm = st.summary;+ const compat = sm.provider === 'openai_compatible';+ return '<div class="field-row"><label for="sm-provider">Provider</label><select id="sm-provider">' ++ PROVIDERS.map(([v, l]) => '<option value="' + v + '"' + (sm.provider === v ? ' selected' : '') + '>' + esc(l) + '</option>').join('') + '</select></div>' ++ '<p class="card-meta" style="margin:0 0 10px">' + esc(PROVIDER_HELP[sm.provider] || '') + '</p>' ++ (compat+ ? '<div class="field-row"><label for="sm-preset">Service</label><select id="sm-preset">' ++ ENDPOINTS.map(([v, l]) => '<option value="' + esc(v) + '"' + (v && sm.base_url === v ? ' selected' : '') + '>' + esc(l) + '</option>').join('') + '</select></div>' ++ '<div class="field-row"><label for="sm-url">Base URL</label><input type="text" id="sm-url" class="wide" value="' + esc(sm.base_url) + '" placeholder="https://api.openai.com/v1" spellcheck="false"></div>'+ : '') ++ '<div class="field-row"><label for="sm-model">Model</label><input type="text" id="sm-model" class="wide" value="' + esc(sm.model) + '" placeholder="' + (compat ? 'the model name your service uses' : 'default') + '" spellcheck="false"></div>' ++ (compat+ ? '<div class="field-row"><label for="sm-key">API key</label><input type="password" id="sm-key" class="wide" value="" autocomplete="off" placeholder="' + (sm.api_key_set ? 'saved (type to replace)' : 'not needed for local models') + '"></div>'+ : '') ++ '<div class="btn-row" style="margin-top:6px"><button class="btn" type="button" id="sm-test">Save and test</button></div>' ++ '<div class="card-meta" id="sm-status"></div>';+}++const ENROLL_PROMPT = 'Today started like most days. I woke up a little before seven, made a cup of coffee, and checked the weather while the toast was in the toaster. After breakfast I walked to the corner store for milk and bread, said hello to a few neighbors, and then sat down at my desk to answer some messages. Around noon I stepped outside for lunch, and in the evening I cooked dinner and read a few pages of a book before bed.';++function sRow(title, help, body) {+ return '<section class="s-row"><div class="s-info"><h2>' + esc(title) + '</h2><p>' + esc(help) + '</p></div>' ++ '<div class="card s-body">' + body + '</div></section>';+}++async function renderSettings(token) {+ setActiveNav('settings');+ setView('<p class="loading">Loading...</p>');+ const [health, settingsRaw, speakers] = await Promise.all([+ refreshHealth(),+ api('api/settings'),+ api('api/speakers').catch(() => []),+ ]);+ if (token !== state.nav) return;+ const st = normalizeSettings(settingsRaw);+ let spkList = speakers || [];+ let editingId = null;++ setView(+ pageHead('Settings', ['Changes reach the watch within about 2 minutes'],+ '<button class="btn primary" type="button" id="st-save">Save changes</button>') ++ '<div class="settings">' +++ '<div class="s-group">Auto mode</div>' ++ sRow('When to listen', 'Auto mode listens whenever the watch is on your wrist, unless you set weekly windows below. Calendar meetings also count once a calendar link is added (see SETUP.md).',+ '<label class="row-check"><input type="checkbox" id="st-always"' + (st.auto.always_while_worn ? ' checked' : '') + '> Listen whenever I\'m wearing it, even outside my windows</label>' ++ '<label class="row-check"><input type="checkbox" id="st-cal"' + (st.auto.calendar.enabled ? ' checked' : '') + '> Record calendar meetings</label>' ++ '<div class="field-row indent"><label for="st-lead">Start</label><input type="number" id="st-lead" min="0" max="120" value="' + esc(st.auto.calendar.lead_min) + '"><label for="st-lead">minutes before the meeting</label></div>') ++ sRow('Weekly time windows', 'Optional. Leave every day empty to listen all day. Add windows to limit auto mode to those hours.',+ '<div class="btn-row" style="margin:0 0 6px"><button type="button" class="btn small" id="st-copy-mon">Copy Monday to weekdays</button></div>' ++ '<div id="st-windows">' + windowsHtml(st) + '</div>') ++ sRow('Silence and stitching', 'How long a quiet stretch ends a recording, and when two recordings close together are joined into one conversation.',+ '<div class="field-row"><label for="st-auto-end">End an auto recording after</label><input type="number" id="st-auto-end" min="1" max="30" value="' + esc(st.silence.auto_end_min) + '"><label for="st-auto-end">min of silence</label></div>' ++ '<div class="field-row"><label for="st-manual-stop">Stop a button recording after</label><input type="number" id="st-manual-stop" min="0" max="120" value="' + esc(st.silence.manual_stop_min) + '"><label for="st-manual-stop">min of silence (0 = never)</label></div>' ++ '<div class="field-row"><label for="st-gap">Join recordings less than</label><input type="number" id="st-gap" min="0" max="60" value="' + esc(st.merge.gap_min) + '"><label for="st-gap">min apart (0 = off)</label></div>') ++ sRow('Uploads', 'The watch uploads over Wi-Fi or through your phone. Battery saver waits for Wi-Fi.',+ '<label class="row-check"><input type="checkbox" id="st-batt"' + (st.upload.battery_saver ? ' checked' : '') + '> Battery saver: upload only on Wi-Fi or while charging</label>') +++ '<div class="s-group">Voices</div>' ++ sRow('Enroll a voice', 'Read the paragraph out loud for about 30 seconds, or upload a clip. New recordings then label that person by name.',+ '<div class="field-row"><label for="en-name">Name</label><input type="text" id="en-name" value="" placeholder="Your name" style="max-width:240px"></div>' ++ '<label class="row-check"><input type="checkbox" id="en-self" checked> This is me</label>' ++ '<p class="prompt-text">' + esc(ENROLL_PROMPT) + '</p>' ++ '<div class="btn-row" style="margin-top:0">' ++ '<button class="btn primary" type="button" id="en-rec">Record</button>' ++ '<button class="btn" type="button" id="en-stop" disabled hidden>Stop</button>' ++ '<span class="timer" id="en-timer" aria-live="off"></span>' ++ '<span class="or">or</span>' ++ '<label class="btn file-btn">Upload a clip<input type="file" id="en-file" accept="audio/*"></label>' ++ '<button class="btn" type="button" id="en-upload" hidden>Enroll this clip</button>' ++ '</div>' ++ '<div class="card-meta" id="en-status"></div>') ++ sRow('Known speakers', 'Everyone the pipeline recognizes. Rename or delete a voiceprint here.',+ '<div id="spk-list">' + speakersListHtml(spkList, editingId) + '</div>') +++ '<div class="s-group">Summaries</div>' ++ sRow('AI provider', 'Which AI writes the conversation summaries and the daily digest. Transcription always runs on this PC.',+ '<div id="sm-fields">' + summaryFieldsHtml(st) + '</div>') +++ '<div class="s-group">System</div>' ++ sRow('Pipeline status', 'Transcription runs on this PC. Summaries use the provider chosen above.',+ '<div id="health-block">' + healthBlockHtml(health) + '</div>') ++ sRow('Test upload', 'Send any audio file through the full pipeline, as if the watch had recorded it.',+ '<div class="btn-row" style="margin-top:0"><label class="btn file-btn">Choose audio file<input type="file" id="up-file" accept="audio/*"></label>' ++ '<button class="btn primary" type="button" id="up-btn" hidden>Upload</button></div>' ++ '<div class="card-meta" id="up-status"></div>') ++ '</div>'+ );++ const fileName = (input, btn, label) => input.addEventListener('change', () => {+ const f = input.files && input.files[0];+ btn.hidden = !f;+ if (f) btn.textContent = label + ' (' + (f.name.length > 28 ? f.name.slice(0, 25) + '...' : f.name) + ')';+ });+ fileName($('#en-file'), $('#en-upload'), 'Enroll');+ fileName($('#up-file'), $('#up-btn'), 'Upload');++ /* ---- summaries ---- */+ const smHost = $('#sm-fields');+ const readSummary = () => {+ st.summary.model = ($('#sm-model') || {}).value ? $('#sm-model').value.trim() : '';+ if ($('#sm-url')) st.summary.base_url = $('#sm-url').value.trim();+ };+ smHost.addEventListener('change', e => {+ if (e.target.id === 'sm-provider') {+ st.summary.provider = e.target.value;+ st.summary.model = '';+ smHost.innerHTML = summaryFieldsHtml(st);+ } else if (e.target.id === 'sm-preset' && e.target.value) {+ st.summary.base_url = e.target.value;+ $('#sm-url').value = e.target.value;+ }+ });+ const saveSettings = async () => {+ readSummary();+ const out = JSON.parse(JSON.stringify(st));+ DAYS.forEach(([k]) => { out.auto.windows[k] = out.auto.windows[k].filter(w => w[0] && w[1]); });+ delete out.summary.api_key_set;+ const key = $('#sm-key') ? $('#sm-key').value.trim() : '';+ if (key) out.summary.api_key = key;+ const res = await api('api/settings', { method: 'PUT', json: out });+ if (res && typeof res === 'object' && res.auto) Object.assign(st, normalizeSettings(res));+ redrawWindows();+ const status = $('#sm-status') ? $('#sm-status').textContent : '';+ smHost.innerHTML = summaryFieldsHtml(st);+ $('#sm-status').textContent = status;+ };+ smHost.addEventListener('click', async e => {+ if (!e.target.closest('#sm-test')) return;+ try {+ await saveSettings();+ $('#sm-status').textContent = 'Saved. Asking the model for a test summary...';+ const r = await api('api/summary/test', { method: 'POST' });+ if (token !== state.nav) return;+ $('#sm-status').textContent = r && r.ok+ ? 'Works. Answered in ' + r.seconds + ' s: "' + r.title + '"'+ : 'Did not work: ' + ((r && r.error) || 'unknown error');+ refreshHealth().then(h => { if (token === state.nav && $('#health-block')) $('#health-block').innerHTML = healthBlockHtml(h); });+ } catch (err) { fail(err); }+ });++ /* ---- auto mode ---- */+ $('#st-always').addEventListener('change', e => { st.auto.always_while_worn = e.target.checked; });+ $('#st-cal').addEventListener('change', e => { st.auto.calendar.enabled = e.target.checked; });+ $('#st-batt').addEventListener('change', e => { st.upload.battery_saver = e.target.checked; });+ $('#st-lead').addEventListener('input', e => { const n = parseInt(e.target.value, 10); st.auto.calendar.lead_min = Number.isFinite(n) ? n : 0; });++ $('#st-auto-end').addEventListener('input', e => { const n = parseInt(e.target.value, 10); st.silence.auto_end_min = Number.isFinite(n) ? n : 0; });+ $('#st-manual-stop').addEventListener('input', e => { const n = parseInt(e.target.value, 10); st.silence.manual_stop_min = Number.isFinite(n) ? n : 0; });+ $('#st-gap').addEventListener('input', e => { const n = parseInt(e.target.value, 10); st.merge.gap_min = Number.isFinite(n) ? n : 0; });++ const winHost = $('#st-windows');+ const redrawWindows = () => { winHost.innerHTML = windowsHtml(st); };+ winHost.addEventListener('change', e => {+ const t = e.target;+ if (t.matches('input[type="time"]')) st.auto.windows[t.dataset.day][+t.dataset.i][+t.dataset.k] = t.value;+ });+ winHost.addEventListener('click', e => {+ const b = e.target.closest('button[data-act]');+ if (!b) return;+ const day = b.dataset.day;+ if (b.dataset.act === 'add') {+ st.auto.windows[day].push(['09:00', '17:00']);+ redrawWindows();+ } else if (b.dataset.act === 'rm') {+ st.auto.windows[day].splice(+b.dataset.i, 1);+ redrawWindows();+ }+ });+ $('#st-copy-mon').addEventListener('click', () => {+ const mon = JSON.parse(JSON.stringify(st.auto.windows.mon));+ ['tue', 'wed', 'thu', 'fri'].forEach(k => { st.auto.windows[k] = JSON.parse(JSON.stringify(mon)); });+ redrawWindows();+ toast('Copied Monday to Tue-Fri (not saved yet)');+ });+ $('#st-save').addEventListener('click', async () => {+ try {+ await saveSettings();+ toast('Saved');+ } catch (e) { fail(e); }+ });++ /* ---- speakers list ---- */+ const listHost = $('#spk-list');+ const redrawSpk = () => { listHost.innerHTML = speakersListHtml(spkList, editingId); wireSpkConfirm(); };+ const reloadSpk = async () => {+ try {+ spkList = await api('api/speakers');+ if (token !== state.nav) return;+ redrawSpk();+ } catch (e) { fail(e); }+ };+ function wireSpkConfirm() {+ listHost.querySelectorAll('button[data-act="delete"]').forEach(btn => {+ armConfirm(btn, 'Tap again to delete', async () => {+ try {+ await api('api/speakers/' + encodeURIComponent(btn.dataset.id), { method: 'DELETE' });+ toast('Deleted');+ reloadSpk();+ } catch (e) { fail(e); }+ });+ });+ }+ wireSpkConfirm();+ listHost.addEventListener('click', async e => {+ const b = e.target.closest('button[data-act]');+ if (!b) return;+ const act = b.dataset.act;+ if (act === 'rename') {+ editingId = +b.dataset.id;+ redrawSpk();+ const inp = listHost.querySelector('input[data-rename-input]');+ if (inp) inp.focus();+ } else if (act === 'rename-cancel') {+ editingId = null;+ redrawSpk();+ } else if (act === 'rename-save') {+ const inp = listHost.querySelector('input[data-rename-input]');+ const name = inp ? inp.value.trim() : '';+ if (!name) { toast('Name cannot be empty'); return; }+ try {+ await api('api/speakers/' + encodeURIComponent(b.dataset.id), { method: 'PATCH', json: { name } });+ editingId = null;+ toast('Saved');+ reloadSpk();+ } catch (err) { fail(err); }+ }+ });++ /* ---- enroll ---- */+ const enStatus = $('#en-status');+ async function uploadEnroll(blob, filename) {+ const name = $('#en-name').value.trim();+ if (!name) { toast('Enter a name first'); return; }+ const fd = new FormData();+ fd.append('file', blob, filename);+ fd.append('name', name);+ fd.append('is_self', $('#en-self').checked ? '1' : '0');+ enStatus.textContent = 'Uploading…';+ try {+ await api('api/speakers/enroll', { method: 'POST', form: fd });+ enStatus.textContent = 'Processing voiceprint…';+ later(() => { if (token === state.nav) { reloadSpk(); enStatus.textContent = 'Speakers list refreshed.'; } }, 15000);+ } catch (e) { enStatus.textContent = ''; fail(e); }+ }++ const recBtn = $('#en-rec'), stopBtn = $('#en-stop'), timerEl = $('#en-timer');+ let recorder = null, stream = null, tick = null, discard = false;+ const releaseMic = () => {+ if (tick) { clearInterval(tick); tick = null; }+ if (stream) { stream.getTracks().forEach(t => t.stop()); stream = null; }+ };+ state.cleanups.push(() => {+ discard = true;+ try { if (recorder && recorder.state !== 'inactive') recorder.stop(); } catch (e) { /* ignore */ }+ releaseMic();+ });++ recBtn.addEventListener('click', async () => {+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia || typeof MediaRecorder === 'undefined') {+ toast('Recording is not supported in this browser. Use the file upload.');+ return;+ }+ try {+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ } catch (e) { toast('Microphone unavailable: ' + (e && e.message ? e.message : e)); return; }+ discard = false;+ const chunks = [];+ recorder = new MediaRecorder(stream);+ recorder.addEventListener('dataavailable', ev => { if (ev.data && ev.data.size) chunks.push(ev.data); });+ recorder.addEventListener('stop', () => {+ const type = recorder.mimeType || 'audio/webm';+ releaseMic();+ recBtn.disabled = false;+ stopBtn.hidden = true;+ timerEl.textContent = '';+ if (discard) return;+ const blob = new Blob(chunks, { type });+ const ext = /ogg/.test(type) ? 'ogg' : /mp4|aac/.test(type) ? 'm4a' : /wav/.test(type) ? 'wav' : 'webm';+ uploadEnroll(blob, 'voice.' + ext);+ });+ recorder.start();+ recBtn.disabled = true;+ stopBtn.hidden = false;+ stopBtn.disabled = true;+ enStatus.textContent = 'Recording. Read the paragraph above out loud.';+ let elapsed = 0;+ timerEl.textContent = fmtClock(30);+ tick = setInterval(() => {+ elapsed += 1;+ timerEl.textContent = fmtClock(30 - elapsed);+ if (elapsed >= 10) stopBtn.disabled = false;+ if (elapsed >= 30) { try { recorder.stop(); } catch (e) { /* ignore */ } }+ }, 1000);+ state.timers.push(tick);+ });+ stopBtn.addEventListener('click', () => { try { if (recorder && recorder.state !== 'inactive') recorder.stop(); } catch (e) { /* ignore */ } });++ $('#en-upload').addEventListener('click', () => {+ const f = $('#en-file').files[0];+ if (!f) { toast('Choose an audio file first'); return; }+ uploadEnroll(f, f.name);+ });++ /* ---- test upload ---- */+ $('#up-btn').addEventListener('click', async () => {+ const f = $('#up-file').files[0];+ const out = $('#up-status');+ if (!f) { toast('Choose an audio file first'); return; }+ const fd = new FormData();+ fd.append('file', f, f.name);+ out.textContent = 'Uploading…';+ try {+ const res = await api('api/upload', { method: 'POST', form: fd });+ const id = res && res.recording_id;+ out.innerHTML = 'Uploaded, processing… recording id ' + esc(id) ++ (id != null ? ' · <a href="#/c/' + encodeURIComponent(id) + '">Open conversation</a>' : '');+ toast('Uploaded');+ } catch (e) { out.textContent = ''; fail(e); }+ });+}++/* ================= boot ================= */+window.addEventListener('hashchange', route);+initTopbar();+route();diff --git a/static/index.html b/static/index.htmlnew file mode 100644index 0000000..3867c32--- /dev/null+++ b/static/index.html@@ -0,0 +1,70 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">+ <meta name="color-scheme" content="light dark">+ <title>Voice Capture</title>+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 48 48'%3E%3Crect width='48' height='48' rx='12' fill='%232563EB'/%3E%3Cpath fill='%23fff' d='M13 14h12a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H13a4 4 0 0 1-4-4v-8a4 4 0 0 1 4-4z'/%3E%3Ccircle cx='15' cy='21' r='2.2' fill='%231E3A8A'/%3E%3Ccircle cx='23' cy='21' r='2.2' fill='%231E3A8A'/%3E%3Cpath fill='%23fff' d='M37 15a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0v-6a3 3 0 0 1 3-3z'/%3E%3C/svg%3E">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">+ <link rel="stylesheet" href="style.css?v=2">+</head>+<body>+ <div class="shell">+ <aside class="side">+ <a class="logo" href="#/">+ <svg class="logo-mark" viewBox="0 0 48 48" aria-hidden="true">+ <rect width="48" height="48" rx="12" fill="#2563EB"/>+ <circle cx="19" cy="8.5" r="2" fill="#fff"/><rect x="18.2" y="9" width="1.6" height="5" fill="#fff"/>+ <path fill="#fff" d="M13 14h12a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H13a4 4 0 0 1-4-4v-8a4 4 0 0 1 4-4z"/>+ <circle cx="15" cy="21" r="2.2" fill="#1E3A8A"/><circle cx="23" cy="21" r="2.2" fill="#1E3A8A"/>+ <rect x="15" y="25.5" width="8" height="1.6" rx=".8" fill="#1E3A8A"/>+ <path fill="#fff" d="M12 33h14a3 3 0 0 1 3 3v4H9v-4a3 3 0 0 1 3-3z"/>+ <path fill="#fff" d="M37 15a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0v-6a3 3 0 0 1 3-3z"/>+ <path d="M32.5 23.5a4.5 4.5 0 0 0 9 0" fill="none" stroke="#fff" stroke-width="1.6"/>+ <rect x="36.2" y="28" width="1.6" height="4" fill="#fff"/>+ </svg>+ <span class="logo-text">Voice Capture</span>+ </a>++ <form id="search-form" class="side-search" role="search" autocomplete="off">+ <svg viewBox="0 0 20 20" aria-hidden="true"><path d="M8.5 3a5.5 5.5 0 1 0 3.4 9.8l3.6 3.7 1.1-1.1-3.7-3.6A5.5 5.5 0 0 0 8.5 3zm0 1.6a3.9 3.9 0 1 1 0 7.8 3.9 3.9 0 0 1 0-7.8z" fill="currentColor"/></svg>+ <input id="search-input" type="search" name="q" placeholder="Search conversations" aria-label="Search conversations" enterkeyhint="search">+ <kbd>/</kbd>+ </form>++ <nav class="side-nav" aria-label="Main">+ <a href="#/today" data-nav="today">+ <svg viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M6 2h1.6v1.5h4.8V2H14v1.5h1.5A2.5 2.5 0 0 1 18 6v9.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 2 15.5V6a2.5 2.5 0 0 1 2.5-2.5H6V2zM3.6 8v7.5c0 .5.4.9.9.9h11c.5 0 .9-.4.9-.9V8H3.6z"/></svg>+ <span>Today</span></a>+ <a href="#/" data-nav="days">+ <svg viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M3 4h14v1.6H3V4zm0 5.2h14v1.6H3V9.2zm0 5.2h9v1.6H3v-1.6z"/></svg>+ <span>All conversations</span></a>+ <a href="#/search" data-nav="search">+ <svg viewBox="0 0 20 20" aria-hidden="true"><path d="M8.5 3a5.5 5.5 0 1 0 3.4 9.8l3.6 3.7 1.1-1.1-3.7-3.6A5.5 5.5 0 0 0 8.5 3zm0 1.6a3.9 3.9 0 1 1 0 7.8 3.9 3.9 0 0 1 0-7.8z" fill="currentColor"/></svg>+ <span>Search</span></a>+ <a href="#/settings" data-nav="settings">+ <svg viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M8.6 2h2.8l.4 2.1c.5.2 1 .5 1.4.8l2-.7 1.4 2.4-1.6 1.4a5.6 5.6 0 0 1 0 1.6l1.6 1.4-1.4 2.4-2-.7c-.4.3-.9.6-1.4.8l-.4 2.1H8.6l-.4-2.1c-.5-.2-1-.5-1.4-.8l-2 .7-1.4-2.4L5 10.8a5.6 5.6 0 0 1 0-1.6L3.4 7.8l1.4-2.4 2 .7c.4-.3.9-.6 1.4-.8L8.6 2zM10 7.4a2.6 2.6 0 1 0 0 5.2 2.6 2.6 0 0 0 0-5.2z"/></svg>+ <span>Settings</span></a>+ </nav>++ <div class="side-foot">+ <button id="health-dot" class="status-btn" type="button" aria-label="Pipeline status">+ <span class="dot"></span><span id="health-label">Checking...</span>+ </button>+ <div id="health-pop" class="health-pop" hidden></div>+ </div>+ </aside>++ <main id="view" class="main" aria-live="polite">+ <p class="loading">Loading...</p>+ </main>+ </div>++ <div id="toast" class="toast" role="status" aria-live="polite" hidden></div>++ <script src="app.js?v=1"></script>+</body>+</html>diff --git a/static/style.css b/static/style.cssnew file mode 100644index 0000000..788e1fa--- /dev/null+++ b/static/style.css@@ -0,0 +1,455 @@+[hidden] { display: none !important; }+/* Voice Capture dashboard. SaaS app shell: sidebar + content, light and dark. */+:root {+ --bg: #f6f7f9;+ --panel: #ffffff;+ --panel-2: #f9fafb;+ --hover: #f2f4f7;+ --border: #e5e7eb;+ --border-2: #d6d9df;+ --text: #0f1115;+ --text-2: #3f4451;+ --muted: #6b7280;+ --faint: #9ca3af;+ --accent: #2563eb;+ --accent-2: #1d4ed8;+ --accent-soft: #eef3ff;+ --accent-ring: rgba(37, 99, 235, .22);+ --green: #16a34a;+ --green-soft: #e9f8ee;+ --amber: #b45309;+ --amber-soft: #fdf3e2;+ --red: #dc2626;+ --red-soft: #fdecec;+ --mark: #fde68a;+ --shadow-1: 0 1px 2px rgba(16, 24, 40, .05);+ --shadow-2: 0 1px 3px rgba(16, 24, 40, .06), 0 8px 24px -8px rgba(16, 24, 40, .12);+ --radius: 12px;+ --radius-sm: 8px;+ --side-w: 248px;+ --sp0: #7c3aed; --sp1: #0d9488; --sp2: #ea580c; --sp3: #db2777; --sp4: #65a30d; --sp5: #4f46e5;+}++@media (prefers-color-scheme: dark) {+ :root {+ --bg: #0b0c0f;+ --panel: #121318;+ --panel-2: #16181e;+ --hover: #1b1d24;+ --border: #23252d;+ --border-2: #2e313a;+ --text: #ededf0;+ --text-2: #c9cad1;+ --muted: #9a9ba6;+ --faint: #676874;+ --accent: #4f8bff;+ --accent-2: #6b9dff;+ --accent-soft: #16213a;+ --accent-ring: rgba(79, 139, 255, .3);+ --green: #34d399;+ --green-soft: #10261d;+ --amber: #fbbf24;+ --amber-soft: #2a2110;+ --red: #f87171;+ --red-soft: #2c1416;+ --mark: rgba(251, 191, 36, .32);+ --shadow-1: 0 1px 2px rgba(0, 0, 0, .4);+ --shadow-2: 0 1px 2px rgba(0, 0, 0, .4), 0 12px 32px -12px rgba(0, 0, 0, .7);+ --sp0: #a78bfa; --sp1: #2dd4bf; --sp2: #fb923c; --sp3: #f472b6; --sp4: #a3e635; --sp5: #818cf8;+ }+}++* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }+html, body { margin: 0; padding: 0; }+body {+ background: var(--bg);+ color: var(--text);+ font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;+ font-size: 14px;+ line-height: 1.5;+ -webkit-font-smoothing: antialiased;+ font-feature-settings: 'cv11', 'ss01';+ overflow-x: hidden;+}+a { color: var(--accent); text-decoration: none; }+p { margin: 0 0 10px; }+ul { margin: 0; padding-left: 18px; }+li { margin: 4px 0; }+h1, h2, h3, h4 { margin: 0; letter-spacing: -.015em; }++/* ================= shell ================= */+.shell { display: grid; grid-template-columns: var(--side-w) minmax(0, 1fr); min-height: 100dvh; }++.side {+ position: sticky; top: 0; height: 100dvh;+ display: flex; flex-direction: column; gap: 14px;+ padding: 18px 14px;+ background: var(--panel);+ border-right: 1px solid var(--border);+}+.logo { display: flex; align-items: center; gap: 10px; padding: 4px 6px; color: var(--text); }+.logo-mark { width: 30px; height: 30px; flex: none; border-radius: 8px; }+.logo-text { font-weight: 650; font-size: 15px; letter-spacing: -.02em; }++.side-search {+ position: relative; display: flex; align-items: center;+}+.side-search svg { position: absolute; left: 10px; width: 16px; height: 16px; color: var(--faint); pointer-events: none; }+.side-search input[type="search"] {+ width: 100%; height: 36px; padding: 0 30px 0 32px;+ font: inherit; font-size: 13.5px; color: var(--text);+ background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius-sm);+ outline: none; transition: border-color .15s, box-shadow .15s;+}+.side-search input[type="search"]:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-ring); background: var(--panel); }+.side-search kbd {+ position: absolute; right: 8px; font: 11px/1 'Inter', sans-serif; color: var(--faint);+ padding: 3px 6px; border: 1px solid var(--border); border-radius: 5px; background: var(--panel);+}++.side-nav { display: flex; flex-direction: column; gap: 2px; }+.side-nav a {+ display: flex; align-items: center; gap: 10px;+ height: 36px; padding: 0 10px; border-radius: var(--radius-sm);+ color: var(--text-2); font-weight: 500; font-size: 13.5px;+ transition: background .12s, color .12s;+}+.side-nav a svg { width: 17px; height: 17px; flex: none; color: var(--faint); }+.side-nav a:hover { background: var(--hover); color: var(--text); }+.side-nav a.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }+.side-nav a.active svg { color: var(--accent); }++.side-foot { margin-top: auto; position: relative; }+.status-btn {+ display: flex; align-items: center; gap: 8px; width: 100%;+ padding: 9px 10px; font: inherit; font-size: 12.5px; color: var(--muted);+ background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: pointer;+}+.status-btn:hover { color: var(--text); }+.status-btn .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; }+.status-btn.ok .dot { background: var(--green); box-shadow: 0 0 0 3px var(--green-soft); }+.status-btn.warn .dot { background: var(--amber); box-shadow: 0 0 0 3px var(--amber-soft); }+.health-pop {+ position: absolute; left: 0; right: 0; bottom: calc(100% + 8px); z-index: 30;+ padding: 12px; font-size: 13px;+ background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-2);+}+.health-pop[hidden] { display: none; }++.main { min-width: 0; padding: 28px clamp(16px, 3.2vw, 44px) 64px; }+.main > * { max-width: 1160px; margin-left: auto; margin-right: auto; }++/* phones + small tablets: sidebar becomes a top bar */+@media (max-width: 900px) {+ .shell { grid-template-columns: 1fr; }+ .side {+ position: sticky; z-index: 20; height: auto; flex-direction: row; flex-wrap: wrap; align-items: center;+ gap: 10px; padding: 10px 14px; border-right: 0; border-bottom: 1px solid var(--border);+ padding-top: calc(env(safe-area-inset-top) + 10px);+ }+ .logo-text { font-size: 14px; }+ .side-nav { flex-direction: row; margin-left: auto; gap: 0; }+ .side-nav a { padding: 0 9px; }+ .side-nav a span { display: none; }+ .side-search { order: 5; flex: 1 0 100%; }+ .side-search kbd { display: none; }+ .side-foot { margin: 0; }+ .status-btn { width: auto; padding: 8px; background: transparent; border: 0; }+ .status-btn #health-label { display: none; }+ .health-pop { left: auto; right: 0; bottom: auto; top: calc(100% + 8px); width: min(320px, 90vw); }+ .main { padding-top: 18px; }+}++/* ================= page header ================= */+.page-head {+ display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap;+ margin-bottom: 22px;+}+.page-head h1 { font-size: 24px; font-weight: 650; line-height: 1.2; letter-spacing: -.025em; overflow-wrap: anywhere; }+.page-head .sub { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin-top: 6px; color: var(--muted); font-size: 13px; }+.page-head .sub .sep { color: var(--border-2); }+.page-head .actions { display: flex; flex-wrap: wrap; gap: 8px; }+.crumb { display: inline-flex; align-items: center; gap: 6px; margin-bottom: 10px; font-size: 13px; color: var(--muted); font-weight: 500; }+.crumb:hover { color: var(--text); }+.eyebrow { font-size: 11.5px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--faint); }++/* ================= buttons + inputs ================= */+.btn {+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;+ height: 36px; padding: 0 14px;+ font: inherit; font-size: 13.5px; font-weight: 550; color: var(--text);+ background: var(--panel); border: 1px solid var(--border-2); border-radius: var(--radius-sm);+ box-shadow: var(--shadow-1); cursor: pointer; white-space: nowrap;+ transition: background .12s, border-color .12s, color .12s;+}+.btn svg { width: 15px; height: 15px; }+.btn:hover { background: var(--hover); }+.btn:active { transform: translateY(1px); }+.btn[disabled] { opacity: .5; cursor: default; }+.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }+.btn.primary:hover { background: var(--accent-2); border-color: var(--accent-2); }+.btn.danger { color: var(--red); }+.btn.danger:hover { background: var(--red-soft); }+.btn.danger.armed { background: var(--red); border-color: var(--red); color: #fff; }+.btn.small { height: 30px; padding: 0 10px; font-size: 12.5px; }+.btn.ghost { box-shadow: none; background: transparent; border-color: transparent; color: var(--muted); }+.btn.ghost:hover { background: var(--hover); color: var(--text); }+.btn-row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }++input[type="text"], input[type="password"], input[type="search"], input[type="number"], input[type="time"], input[type="date"], select, input:not([type]) {+ width: 100%; height: 36px; padding: 0 11px;+ font: inherit; font-size: 13.5px; color: var(--text);+ background: var(--panel); border: 1px solid var(--border-2); border-radius: var(--radius-sm);+ outline: none; transition: border-color .15s, box-shadow .15s;+}+select { padding-right: 28px; }+input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-ring); }+input[type="file"] { font: inherit; font-size: 13px; color: var(--muted); max-width: 100%; }+input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--accent); flex: none; }+input[type="time"], input[type="date"] { width: auto; }+input[type="number"] { width: 76px; }+@media (prefers-color-scheme: dark) { input[type="time"], input[type="date"] { color-scheme: dark; } }++/* ================= panels ================= */+.card, .panel {+ display: block; min-width: 0;+ background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius);+ box-shadow: var(--shadow-1); color: inherit;+}+.card { padding: 18px 20px; margin-bottom: 14px; }+.card > h3, .panel-head h3 {+ font-size: 12px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); margin-bottom: 12px;+}+.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 18px; border-bottom: 1px solid var(--border); }+.panel-head h3 { margin: 0; }+.panel-body { padding: 16px 18px; }+a.card, a.row { transition: border-color .15s, box-shadow .15s, background .15s; }+@media (hover: hover) { a.card:hover { border-color: var(--border-2); box-shadow: var(--shadow-2); } }++.split { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 20px; align-items: start; }+.split > aside { position: sticky; top: 20px; display: flex; flex-direction: column; gap: 14px; }+.split > aside .card { margin: 0; }+@media (max-width: 1100px) { .split { grid-template-columns: 1fr; } .split > aside { position: static; } }++.card-title { font-size: 15px; font-weight: 600; letter-spacing: -.01em; overflow-wrap: anywhere; color: var(--text); }+.card-meta { font-size: 12.5px; color: var(--muted); margin-top: 2px; }+.card-text { font-size: 13.5px; color: var(--text-2); margin-top: 6px; overflow-wrap: anywhere; }+.clamp2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }++.muted { color: var(--muted); }+.faint { color: var(--faint); }+.loading { color: var(--faint); font-size: 13px; padding: 24px 0; }+.empty {+ padding: 48px 20px; text-align: center; color: var(--muted);+ background: var(--panel); border: 1px dashed var(--border-2); border-radius: var(--radius);+}+.section { margin-top: 26px; }+.section-title { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }+.section-title h2 { font-size: 15px; font-weight: 600; }++/* ================= stats ================= */+.stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 22px; }+.stat { padding: 14px 16px; background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-1); }+.stat .label { font-size: 12px; color: var(--muted); font-weight: 500; }+.stat .value { font-size: 24px; font-weight: 650; letter-spacing: -.03em; margin-top: 2px; font-variant-numeric: tabular-nums; }+.stat .value small { font-size: 13px; font-weight: 500; color: var(--muted); margin-left: 6px; letter-spacing: 0; }+@media (max-width: 700px) { .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }++/* ================= lists (days, conversations) ================= */+.list { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-1); overflow: hidden; }+.row { display: flex; align-items: center; gap: 16px; padding: 14px 18px; color: inherit; border-top: 1px solid var(--border); }+.row:first-child { border-top: 0; }+a.row:hover { background: var(--panel-2); }+.row .grow { flex: 1; min-width: 0; }+.row .chev { color: var(--faint); flex: none; width: 16px; height: 16px; }+.date-tile {+ flex: none; width: 48px; text-align: center; padding: 6px 0;+ border: 1px solid var(--border); border-radius: 10px; background: var(--panel-2);+}+.date-tile .dow { font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); }+.date-tile .num { font-size: 19px; font-weight: 650; line-height: 1.15; letter-spacing: -.02em; }+.row-meta { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 12.5px; color: var(--muted); margin-top: 3px; }++/* timeline of conversations on a day */+.timeline { position: relative; display: flex; flex-direction: column; gap: 12px; }+.tl-item { display: grid; grid-template-columns: 74px minmax(0, 1fr); gap: 14px; }+.tl-time { text-align: right; padding-top: 16px; font-size: 12.5px; font-weight: 600; color: var(--text-2); font-variant-numeric: tabular-nums; }+.tl-time small { display: block; font-weight: 500; color: var(--faint); font-size: 11.5px; }+.tl-card { padding: 14px 16px; margin: 0; }+.tl-card .top { display: flex; align-items: center; gap: 8px; justify-content: space-between; }+.tl-card .foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 10px; }+@media (max-width: 560px) { .tl-item { grid-template-columns: 1fr; gap: 4px; } .tl-time { text-align: left; padding: 0; } .tl-time small { display: inline; margin-left: 6px; } }++/* ================= pills, badges, chips, avatars ================= */+.pill, .badge {+ display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 8px;+ border-radius: 999px; font-size: 11.5px; font-weight: 550;+ background: var(--panel-2); color: var(--muted); border: 1px solid var(--border); white-space: nowrap;+}+.badge { text-transform: capitalize; }+.badge.auto { color: var(--accent); background: var(--accent-soft); border-color: transparent; }+.badge.calendar { color: var(--sp0); border-color: transparent; background: color-mix(in srgb, var(--sp0) 14%, transparent); }+.pill.warn { background: var(--amber-soft); color: var(--amber); border-color: transparent; }+.pill.ok { background: var(--green-soft); color: var(--green); border-color: transparent; }+.pill.bad { background: var(--red-soft); color: var(--red); border-color: transparent; }++.chips { display: flex; flex-wrap: wrap; gap: 6px; }+.chip {+ display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 10px;+ border-radius: 999px; font: inherit; font-size: 12.5px; font-weight: 500;+ background: var(--panel-2); color: var(--text-2); border: 1px solid var(--border);+}+button.chip { cursor: pointer; }++.sp-0 { --sp: var(--sp0); } .sp-1 { --sp: var(--sp1); } .sp-2 { --sp: var(--sp2); }+.sp-3 { --sp: var(--sp3); } .sp-4 { --sp: var(--sp4); } .sp-5 { --sp: var(--sp5); }+.sp-self { --sp: var(--accent); }+.sp-name { color: var(--sp, var(--text)); font-weight: 600; }++.avatar {+ display: inline-grid; place-items: center; flex: none;+ width: 28px; height: 28px; border-radius: 50%;+ font-size: 11.5px; font-weight: 650; letter-spacing: 0;+ color: var(--sp, var(--muted)); background: color-mix(in srgb, var(--sp, var(--muted)) 15%, transparent);+ border: 1px solid color-mix(in srgb, var(--sp, var(--muted)) 30%, transparent);+}+.avatar.sm { width: 22px; height: 22px; font-size: 10px; }+.avatars { display: flex; }+.avatars .avatar { margin-left: -6px; box-shadow: 0 0 0 2px var(--panel); }+.avatars .avatar:first-child { margin-left: 0; }++mark { background: var(--mark); color: inherit; border-radius: 3px; padding: 0 2px; }++/* ================= conversation ================= */+.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); margin-bottom: 18px; }+.tab {+ position: relative; height: 38px; padding: 0 12px; font: inherit; font-size: 13.5px; font-weight: 550;+ color: var(--muted); background: none; border: 0; cursor: pointer;+}+.tab:hover { color: var(--text); }+.tab.active { color: var(--text); }+.tab.active::after { content: ''; position: absolute; left: 8px; right: 8px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--accent); }+.tab .count { margin-left: 6px; font-size: 11.5px; color: var(--faint); font-weight: 500; }++.overview { font-size: 15px; line-height: 1.65; color: var(--text); margin: 0; }+.block-list { list-style: none; padding: 0; margin: 0; }+.block-list li { position: relative; padding: 7px 0 7px 18px; margin: 0; color: var(--text-2); border-top: 1px solid var(--border); }+.block-list li:first-child { border-top: 0; }+.block-list li::before { content: ''; position: absolute; left: 2px; top: 15px; width: 6px; height: 6px; border-radius: 50%; background: var(--border-2); }+.block-list.decisions li::before { background: var(--green); }+.todo { display: flex; gap: 10px; align-items: flex-start; padding: 9px 0; border-top: 1px solid var(--border); }+.todo:first-child { border-top: 0; }+.todo .box { width: 16px; height: 16px; margin-top: 2px; flex: none; border: 1.5px solid var(--border-2); border-radius: 4px; }+.todo .what { color: var(--text); }+.todo .tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }++.details { display: grid; grid-template-columns: auto 1fr; gap: 8px 14px; font-size: 13px; margin: 0; }+.details dt { color: var(--muted); }+.details dd { margin: 0; text-align: right; overflow-wrap: anywhere; }++.spk-list { display: flex; flex-direction: column; gap: 2px; }+.spk-item {+ display: flex; align-items: center; gap: 10px; width: 100%; padding: 7px 8px; margin: 0 -8px; width: calc(100% + 16px);+ font: inherit; font-size: 13.5px; color: var(--text); text-align: left;+ background: none; border: 0; border-radius: var(--radius-sm); cursor: pointer;+}+.spk-item:hover { background: var(--hover); }+.spk-item .grow { flex: 1; min-width: 0; }+.spk-item .hint { font-size: 11.5px; color: var(--faint); }+.spk-item .you { font-size: 11px; color: var(--accent); font-weight: 600; }++.transcript { padding: 6px 0; }+.utt { display: grid; grid-template-columns: 28px minmax(0, 1fr); gap: 12px; padding: 12px 20px; }+.utt:hover { background: var(--panel-2); }+.utt-head { display: flex; align-items: baseline; gap: 8px; font-size: 13px; margin-bottom: 2px; }+.utt-head .t { color: var(--faint); font-size: 12px; font-variant-numeric: tabular-nums; }+.utt-text { font-size: 14.5px; line-height: 1.6; color: var(--text-2); overflow-wrap: anywhere; white-space: pre-wrap; }++.spk-form { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }+.spk-form input { flex: 1 1 160px; }++/* ================= search ================= */+.filters {+ display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto auto; gap: 10px; align-items: end;+ padding: 14px; margin-bottom: 18px;+}+.filters label { display: flex; flex-direction: column; gap: 5px; font-size: 12px; font-weight: 500; color: var(--muted); }+@media (max-width: 860px) { .filters { grid-template-columns: 1fr 1fr; } .filters .q { grid-column: 1 / -1; } }+.result { padding: 0; overflow: hidden; }+.result-head { display: block; padding: 14px 18px; color: inherit; }+.result-head:hover { background: var(--panel-2); }+.hits { border-top: 1px solid var(--border); }+.hit { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; padding: 9px 18px; font-size: 13.5px; color: var(--text-2); border-top: 1px solid var(--border); }+.hit:first-child { border-top: 0; }+.hit .t { color: var(--faint); font-size: 12px; font-variant-numeric: tabular-nums; padding-top: 1px; }+.hit b { font-weight: 600; margin-right: 6px; }+.more { padding: 9px 18px; font-size: 12.5px; color: var(--muted); border-top: 1px solid var(--border); background: var(--panel-2); }++/* ================= settings ================= */+.settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; }+.settings-grid .card { margin: 0; }+.settings-grid .wide { grid-column: 1 / -1; }+@media (max-width: 1000px) { .settings-grid { grid-template-columns: 1fr; } }+.kv { display: grid; grid-template-columns: auto 1fr; gap: 8px 16px; font-size: 13.5px; margin: 0; }+.kv dt { color: var(--muted); }+.kv dd { margin: 0; overflow-wrap: anywhere; }+.sub-list { font-size: 13.5px; margin-top: 10px; }+.sub-list b { font-weight: 600; display: block; margin-bottom: 4px; }+.notice { padding: 10px 12px; margin-bottom: 12px; border-radius: var(--radius-sm); font-size: 13.5px; background: var(--amber-soft); color: var(--amber); overflow-wrap: anywhere; }+.row-check { display: flex; align-items: center; gap: 10px; padding: 8px 0; font-size: 14px; cursor: pointer; }+.day-row { padding: 12px 0; border-top: 1px solid var(--border); }+.day-row:first-of-type { border-top: 0; }+.day-name { font-weight: 600; font-size: 13.5px; margin-bottom: 6px; }+.win { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; }+.win .dash { color: var(--faint); font-size: 13px; }+.field-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 6px 0; }+.field-row label { font-size: 13.5px; color: var(--text-2); }+.prompt-text { margin: 12px 0; padding: 12px 14px; font-size: 13.5px; line-height: 1.6; color: var(--text-2); background: var(--panel-2); border: 1px solid var(--border); border-left: 3px solid var(--accent); border-radius: var(--radius-sm); }+.timer { font-variant-numeric: tabular-nums; font-weight: 600; margin-left: 4px; align-self: center; }+.spk-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 10px 0; border-top: 1px solid var(--border); }+.spk-row:first-of-type { border-top: 0; }+.spk-row .grow { flex: 1 1 140px; min-width: 0; }+.spk-actions { display: flex; gap: 6px; }+.toggle-link { display: block; width: 100%; margin: 10px 0; padding: 9px; font: inherit; font-size: 13px; color: var(--muted); background: transparent; border: 1px dashed var(--border-2); border-radius: var(--radius-sm); cursor: pointer; }+.toggle-link:hover { color: var(--text); }++/* ================= toast ================= */+.toast {+ position: fixed; left: 50%; bottom: calc(env(safe-area-inset-bottom) + 24px); transform: translateX(-50%); z-index: 50;+ max-width: min(92vw, 520px); padding: 10px 16px;+ background: var(--text); color: var(--bg); border-radius: 10px; box-shadow: var(--shadow-2);+ font-size: 13.5px; font-weight: 500; text-align: center; overflow-wrap: anywhere;+}+.toast[hidden] { display: none; }++.sub-list ul { padding-left: 16px; }+.sub-list li { color: var(--text-2); font-weight: 400; font-size: 13px; line-height: 1.55; }+.sub-list b { font-size: 12px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); margin-top: 14px; }+a.hit { color: var(--text-2); }+a.hit:hover { background: var(--panel-2); }+#st-windows .day-row { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; padding: 9px 0; }+#st-windows .day-row > .day-name { width: 100px; margin: 0; }+#st-windows .day-row > .faint { margin: 0 !important; flex: 1; }+#st-windows .day-row > .win { margin: 0; }+#st-windows .day-row > .btn { margin-left: auto; }++/* ================= settings rows (one column, label left, controls right) ================= */+.settings { max-width: 1160px; }+.s-group { margin: 30px 0 4px; font-size: 12px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--accent); }+.s-group:first-child { margin-top: 0; }+.s-row { display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 28px; padding: 22px 0; border-top: 1px solid var(--border); }+.s-group + .s-row { border-top: 0; }+.s-info h2 { font-size: 14.5px; font-weight: 600; margin-bottom: 4px; }+.s-info p { margin: 0; font-size: 13px; line-height: 1.55; color: var(--muted); }+.s-body { margin: 0; }+.s-body > .row-check:first-child { padding-top: 0; }+.field-row.indent { padding-left: 26px; }+.or { align-self: center; font-size: 12.5px; color: var(--faint); }+.file-btn { position: relative; overflow: hidden; }+.file-btn input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; }+@media (max-width: 860px) { .s-row { grid-template-columns: 1fr; gap: 12px; } }++/* ================= summaries provider form ================= */+.field-row select { flex: 1 1 260px; min-width: 0; max-width: 460px; width: auto; }+.field-row label[for^="sm-"] { flex: 0 0 76px; }+.field-row input.wide { flex: 1 1 260px; min-width: 0; max-width: 460px; width: auto; }diff --git a/stitch.py b/stitch.pynew file mode 100644index 0000000..80132f8--- /dev/null+++ b/stitch.py@@ -0,0 +1,137 @@+"""Join recordings that are really one conversation.++The watch ends an auto recording after a couple of minutes of silence, so a conversation with a+5-minute pause arrives as two recordings. After a recording is transcribed the worker calls+`auto_merge`: if the previous recording from the same watch ended less than `merge.gap_min`+minutes earlier and the other voices are not clearly different people, the new one is folded+into it (segments shifted onto the earlier timeline, speakers matched by voiceprint) and the+combined conversation is re-summarized. The dashboard's "Merge with previous" button calls+`merge` directly for the cases the rule gets wrong.++Audio is already deleted at this point, so a merge works on segments, never on audio.+"""++from __future__ import annotations++from datetime import datetime++import numpy as np++import config+import db+import store++MERGEABLE = ("transcribed", "summarizing", "done")+++def _ts(iso: str) -> datetime:+ return datetime.fromisoformat(iso)+++def _speakers(c, rid: str) -> list[dict]:+ rows = c.execute("""select rs.label, rs.display, rs.speaker_id, rs.embedding, rs.speech_s, coalesce(s.is_self,0) is_self+ from recording_speakers rs left join speakers s on s.id = rs.speaker_id+ where rs.recording_id=?""", (rid,)).fetchall()+ return [{"label": r["label"], "display": r["display"], "speaker_id": r["speaker_id"],+ "emb": store.emb_load(r["embedding"]), "speech_s": r["speech_s"] or 0.0,+ "is_self": bool(r["is_self"])} for r in rows]+++def _same(a: dict, b: dict, thr: float) -> bool:+ if a["speaker_id"] and b["speaker_id"]:+ return a["speaker_id"] == b["speaker_id"]+ if a["emb"] is not None and b["emb"] is not None:+ return float(np.dot(a["emb"], b["emb"])) >= thr+ return False+++def previous(c, r) -> dict | None:+ """The recording just before r from the same device, if any."""+ return c.execute("""select * from recordings where id != ? and coalesce(device_id,'') = coalesce(?, '')+ and trigger != 'upload' and started_at < ? order by started_at desc limit 1""",+ (r["id"], r["device_id"], r["started_at"])).fetchone()+++def should_merge(c, prev, new) -> tuple[bool, str]:+ gap_min = db.settings(c)["merge"]["gap_min"]+ if not gap_min:+ return False, "auto-merge off"+ if prev is None or prev["status"] not in MERGEABLE or new["trigger"] == "upload":+ return False, "no mergeable previous recording"+ gap = (_ts(new["started_at"]) - _ts(prev["ended_at"] or prev["started_at"])).total_seconds() / 60+ if gap > gap_min:+ return False, f"gap {gap:.1f} min > {gap_min}"+ thr = config.tunables()["speaker_match_threshold"]+ p_others = [s for s in _speakers(c, prev["id"]) if not s["is_self"]]+ n_others = [s for s in _speakers(c, new["id"]) if not s["is_self"]]+ if p_others and n_others and not any(_same(a, b, thr) for a in n_others for b in p_others):+ return False, f"gap {gap:.1f} min but different people"+ return True, f"gap {gap:.1f} min"+++def merge(c, prev_id: str, new_id: str) -> None:+ """Fold recording new_id into prev_id (which must start earlier)."""+ prev = c.execute("select * from recordings where id=?", (prev_id,)).fetchone()+ new = c.execute("select * from recordings where id=?", (new_id,)).fetchone()+ if not prev or not new:+ raise ValueError("recording not found")+ if new["started_at"] < prev["started_at"]:+ prev, new = new, prev+ offset = (_ts(new["started_at"]) - _ts(prev["started_at"])).total_seconds()+ thr = config.tunables()["speaker_match_threshold"]+ p_spk, n_spk = _speakers(c, prev["id"]), _speakers(c, new["id"])+ used_labels = {s["label"] for s in p_spk}+ used_letters = {s["display"].removeprefix("Speaker ") for s in p_spk if s["display"].startswith("Speaker ")}+ free_letters = iter(ch for ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if ch not in used_letters)+ taken: set[str] = set()+ label_map: dict[str, str] = {}+ with db.tx(c):+ for s in sorted(n_spk, key=lambda x: -x["speech_s"]):+ match = next((p for p in p_spk if p["label"] not in taken and _same(s, p, thr)), None)+ if match:+ taken.add(match["label"])+ label_map[s["label"]] = match["label"]+ c.execute("update recording_speakers set speech_s = coalesce(speech_s,0) + ?, "+ "speaker_id = coalesce(speaker_id, ?) where recording_id=? and label=?",+ (s["speech_s"], s["speaker_id"], prev["id"], match["label"]))+ continue+ k, lab = 0, s["label"]+ while lab in used_labels:+ k += 1+ lab = f"{s['label']}_{k}"+ used_labels.add(lab)+ label_map[s["label"]] = lab+ c.execute("""insert into recording_speakers(recording_id, label, display, speaker_id, embedding, speech_s)+ values(?,?,?,?,?,?)""",+ (prev["id"], lab, f"Speaker {next(free_letters, 'X')}", s["speaker_id"],+ store.emb_dump(s["emb"]) if s["emb"] is not None else None, s["speech_s"]))+ for seg in c.execute("select id, label, start_s, end_s from segments where recording_id=?", (new["id"],)).fetchall():+ c.execute("update segments set recording_id=?, label=?, start_s=?, end_s=? where id=?",+ (prev["id"], label_map.get(seg["label"], seg["label"]), seg["start_s"] + offset,+ seg["end_s"] + offset, seg["id"]))+ ended = max(prev["ended_at"] or prev["started_at"], new["ended_at"] or new["started_at"])+ c.execute("""update recordings set ended_at=?, duration_s=?, speech_s=?, words=?, status='transcribed',+ error=null, attempts=0, updated_at=? where id=?""",+ (ended, (prev["duration_s"] or 0) + (new["duration_s"] or 0),+ (prev["speech_s"] or 0) + (new["speech_s"] or 0), (prev["words"] or 0) + (new["words"] or 0),+ db.now_iso(), prev["id"]))+ merged = db.get_kv(c, "merged_into") or {}+ merged[new["id"]] = prev["id"]+ db.set_kv(c, "merged_into", merged)+ c.execute("delete from recordings where id=?", (new["id"],))+ store.refresh_transcript(c, prev["id"])+ db.mark_day_dirty(c, prev["day"])+ db.mark_day_dirty(c, new["day"])+++def auto_merge(c, rid: str) -> str | None:+ """Called right after rid is transcribed. Returns the id it was merged into, or None."""+ new = c.execute("select * from recordings where id=?", (rid,)).fetchone()+ if not new or new["status"] != "transcribed":+ return None+ prev = previous(c, new)+ ok, why = should_merge(c, prev, new)+ if not ok:+ return None+ merge(c, prev["id"], rid)+ return f"{prev['id']} ({why})"diff --git a/store.py b/store.pynew file mode 100644index 0000000..65fd213--- /dev/null+++ b/store.py@@ -0,0 +1,90 @@+"""Read/shape helpers shared by the server and the worker."""++from __future__ import annotations++import json++import numpy as np++import db+++def speaker_names(con, rec_id: str) -> dict[str, dict]:+ rows = con.execute("""select rs.label, rs.display, rs.speaker_id, s.name, coalesce(s.is_self,0) is_self+ from recording_speakers rs left join speakers s on s.id = rs.speaker_id+ where rs.recording_id=? order by rs.display""", (rec_id,)).fetchall()+ return {r["label"]: {"label": r["label"], "display": r["name"] or r["display"],+ "speaker_id": r["speaker_id"], "is_self": bool(r["is_self"])} for r in rows}+++def render_transcript(con, rec_id: str) -> str:+ names = speaker_names(con, rec_id)+ lines, last, buf = [], None, []+ for s in con.execute("select label, text from segments where recording_id=? order by start_s", (rec_id,)):+ who = names.get(s["label"], {}).get("display") or "Speaker"+ if who != last and buf:+ lines.append(f"{last}: {' '.join(buf)}")+ buf = []+ last = who+ buf.append(s["text"].strip())+ if buf:+ lines.append(f"{last}: {' '.join(buf)}")+ return "\n".join(lines)+++def refresh_transcript(con, rec_id: str) -> None:+ con.execute("update recordings set transcript_text=? where id=?", (render_transcript(con, rec_id), rec_id))+++def summary_text(s: dict | None) -> str | None:+ if not s:+ return None+ parts = [s.get("title") or "", s.get("summary") or ""]+ for k in ("key_points", "decisions"):+ parts += [f"- {x}" for x in s.get(k) or []]+ parts += [f"- TODO {a.get('item')}" for a in s.get("action_items") or []]+ return "\n".join(p for p in parts if p)+++def conversation(con, rec_id: str) -> dict | None:+ r = con.execute("select * from recordings where id=?", (rec_id,)).fetchone()+ if not r:+ return None+ names = speaker_names(con, rec_id)+ segs = []+ from datetime import datetime, timedelta+ t0 = datetime.fromisoformat(r["started_at"])+ for s in con.execute("select start_s, end_s, label, text from segments where recording_id=? order by start_s", (rec_id,)):+ segs.append({"start_s": s["start_s"], "end_s": s["end_s"],+ "at": (t0 + timedelta(seconds=s["start_s"])).isoformat(timespec="seconds"),+ "label": s["label"], "display": names.get(s["label"], {}).get("display") or "Speaker",+ "text": s["text"]})+ return {"id": r["id"], "started_at": r["started_at"], "ended_at": r["ended_at"], "duration_s": r["duration_s"],+ "trigger": r["trigger"], "status": r["status"], "error": r["error"], "title": r["title"],+ "summary": json.loads(r["summary_json"]) if r["summary_json"] else None,+ "speakers": list(names.values()), "segments": segs}+++def emb_load(txt: str | None) -> np.ndarray | None:+ if not txt:+ return None+ v = np.asarray(json.loads(txt), dtype=np.float32)+ n = np.linalg.norm(v)+ return v / n if n else None+++def emb_dump(v: np.ndarray) -> str:+ return json.dumps([round(float(x), 6) for x in v])+++def fold_into_speaker(con, speaker_id: int, emb_txt: str | None) -> None:+ """Running mean of normalized embeddings = the speaker's voiceprint."""+ new = emb_load(emb_txt)+ row = con.execute("select embedding, samples from speakers where id=?", (speaker_id,)).fetchone()+ if new is None or row is None:+ return+ old = emb_load(row["embedding"])+ n = row["samples"] or 0+ mean = new if old is None else (old * n + new) / (n + 1)+ con.execute("update speakers set embedding=?, samples=?, last_heard=? where id=?",+ (emb_dump(mean / np.linalg.norm(mean)), n + 1, db.now_iso(), speaker_id))diff --git a/summarize.py b/summarize.pynew file mode 100644index 0000000..f1ee31e--- /dev/null+++ b/summarize.py@@ -0,0 +1,324 @@+"""Summaries, with a choice of AI provider (dashboard Settings > Summaries).++ claude_subscription Claude Agent SDK signed in with `claude login`. Never bills API credits:+ ANTHROPIC_API_KEY is removed before the CLI starts, and a call is refused+ if the CLI still reports an API key as its credential source.+ codex_subscription OpenAI Codex CLI signed in with a ChatGPT account (`codex login`), run headless.+ openai_compatible Any /chat/completions endpoint: OpenAI, Ollama, LM Studio, OpenRouter, Gemini,+ Anthropic's compatibility endpoint. Base URL + model + optional key.++Every provider gets the same prompt and must return the same JSON shape; `_normalize` repairs+small-model output (missing keys, strings where lists belong) so the dashboard never breaks.+"""++from __future__ import annotations++import asyncio+import json+import os+import re+import shutil+import subprocess+import tempfile+import time+from pathlib import Path++import httpx++import config++PROVIDERS = ("claude_subscription", "codex_subscription", "openai_compatible")+DEFAULT_MODEL = {"claude_subscription": "sonnet", "codex_subscription": "", "openai_compatible": ""}+++class SummaryError(RuntimeError):+ pass+++CONV_SCHEMA = {+ "type": "object",+ "additionalProperties": False,+ "required": ["title", "summary", "key_points", "decisions", "action_items", "people", "topics"],+ "properties": {+ "title": {"type": "string", "description": "3-8 word title naming what was discussed"},+ "summary": {"type": "string", "description": "2-4 plain sentences: what was discussed and where it landed"},+ "key_points": {"type": "array", "items": {"type": "string"}},+ "decisions": {"type": "array", "items": {"type": "string"}},+ "action_items": {"type": "array", "items": {+ "type": "object", "additionalProperties": False, "required": ["item", "owner", "due"],+ "properties": {"item": {"type": "string"}, "owner": {"type": ["string", "null"]},+ "due": {"type": ["string", "null"]}}}},+ "people": {"type": "array", "items": {"type": "string"}},+ "topics": {"type": "array", "items": {"type": "string"}},+ },+}++DAY_SCHEMA = {+ "type": "object",+ "additionalProperties": False,+ "required": ["headline", "summary", "key_points", "action_items", "people"],+ "properties": {+ "headline": {"type": "string", "description": "one line, under 90 chars, the day at a glance"},+ "summary": {"type": "string", "description": "a short paragraph covering the day's conversations"},+ "key_points": {"type": "array", "items": {"type": "string"}},+ "action_items": CONV_SCHEMA["properties"]["action_items"],+ "people": {"type": "array", "items": {"type": "string"}},+ },+}++CONV_SYSTEM = """You summarize one recorded conversation for {who}, who wore the recorder.+The transcript comes from automatic speech-to-text with automatic speaker labels, so expect+mis-heard words and occasional wrong speaker turns; infer sensibly, never invent facts.+Speaker names come from voiceprints: {self_rule} "Speaker A/B/..." are people not yet named.+Speaker labels can be missing entirely (one label for everyone): then describe it as a conversation+and attribute points to people only when the transcript itself makes it clear.+Write plainly and concretely: names, numbers, dates, what was agreed. No filler.+Only list decisions and action items that were actually stated. Empty lists are fine.+Return only the JSON object."""++DAY_SYSTEM = """You write the end-of-day digest for {who} from the summaries of the conversations they recorded today.+Pull out what matters: decisions, commitments, follow-ups, notable info, who they talked to.+Merge duplicates across conversations. Plain, concrete, no filler. Return only the JSON object."""+++def _conv_system(wearer: str | None) -> str:+ if wearer:+ rule = (f'"{wearer}" is the wearer. If no line is labeled {wearer}, do not guess which speaker '+ f"they are; describe the speakers as labeled.")+ return CONV_SYSTEM.format(who=wearer, self_rule=rule)+ return CONV_SYSTEM.format(who="the person", self_rule="the wearer has not enrolled a voice, so do not guess which speaker they are.")+++# ---- output repair --------------------------------------------------------------++def _extract_json(text: str) -> dict:+ text = re.sub(r"<think>.*?</think>", "", text or "", flags=re.DOTALL).strip()+ fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.DOTALL)+ if fenced:+ text = fenced.group(1).strip()+ try:+ out = json.loads(text)+ except (json.JSONDecodeError, TypeError):+ i, j = text.find("{"), text.rfind("}")+ if i < 0 or j <= i:+ raise SummaryError(f"expected JSON, got {text[:200]!r}")+ try:+ out = json.loads(text[i:j + 1])+ except json.JSONDecodeError as e:+ raise SummaryError(f"expected JSON, got {text[:200]!r}") from e+ if not isinstance(out, dict):+ raise SummaryError("expected a JSON object")+ return out+++def _str_list(v) -> list[str]:+ if isinstance(v, str):+ v = [v]+ if not isinstance(v, list):+ return []+ return [str(x).strip() for x in v if isinstance(x, (str, int, float)) and str(x).strip()]+++def _actions(v) -> list[dict]:+ out = []+ for a in v if isinstance(v, list) else []:+ if isinstance(a, str) and a.strip():+ out.append({"item": a.strip(), "owner": None, "due": None})+ elif isinstance(a, dict) and str(a.get("item") or a.get("task") or "").strip():+ out.append({"item": str(a.get("item") or a.get("task")).strip(),+ "owner": (str(a["owner"]).strip() or None) if a.get("owner") else None,+ "due": (str(a["due"]).strip() or None) if a.get("due") else None})+ return out+++def _normalize(out: dict, schema: dict) -> dict:+ clean = {}+ for key, spec in schema["properties"].items():+ v = out.get(key)+ if key == "action_items":+ clean[key] = _actions(v)+ elif spec["type"] == "array":+ clean[key] = _str_list(v)+ else:+ clean[key] = str(v).strip() if isinstance(v, (str, int, float)) else ""+ if not (clean.get("summary") or clean.get("title") or clean.get("headline")):+ raise SummaryError("the model returned an empty summary")+ return clean+++# ---- provider: Claude subscription ----------------------------------------------++async def _claude(prompt: str, system: str, schema: dict, model: str) -> dict:+ try:+ from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ResultMessage, SystemMessage, TextBlock, query+ except ImportError as e:+ raise SummaryError("claude-agent-sdk is not installed (pip install claude-agent-sdk)") from e+ os.environ.pop("ANTHROPIC_API_KEY", None)+ if not (os.environ.get("CLAUDE_CODE_OAUTH_TOKEN") or "").strip():+ os.environ.pop("CLAUDE_CODE_OAUTH_TOKEN", None)+ opts = ClaudeAgentOptions(+ model=model or DEFAULT_MODEL["claude_subscription"], system_prompt=system, tools=[], allowed_tools=[],+ setting_sources=[], permission_mode="dontAsk", max_turns=4,+ output_format={"type": "json_schema", "schema": schema}, cwd=tempfile.gettempdir())+ result, texts = None, []+ async for m in query(prompt=prompt, options=opts):+ if isinstance(m, SystemMessage) and m.subtype == "init":+ src = m.data.get("apiKeySource")+ if src not in (None, "none"):+ raise SummaryError(f"CLI reports API key source {src!r}; refusing to bill API credits")+ elif isinstance(m, AssistantMessage):+ texts += [b.text for b in m.content if isinstance(b, TextBlock)]+ elif isinstance(m, ResultMessage):+ result = m+ if result is None:+ raise SummaryError("no result from Claude")+ if result.is_error:+ raise SummaryError(f"{result.subtype}: {result.result}")+ out = getattr(result, "structured_output", None)+ return out if isinstance(out, dict) else _extract_json(result.result or "\n".join(texts))+++# ---- provider: Codex CLI on a ChatGPT subscription ------------------------------++def _codex(prompt: str, system: str, schema: dict, model: str) -> dict:+ exe = shutil.which("codex")+ if not exe:+ raise SummaryError("Codex CLI not found. Install it (npm i -g @openai/codex) and run `codex login`.")+ env = {k: v for k, v in os.environ.items() if k not in ("OPENAI_API_KEY", "CODEX_API_KEY")} # subscription only+ with tempfile.TemporaryDirectory() as tmp:+ schema_path, out_path = Path(tmp) / "schema.json", Path(tmp) / "out.json"+ schema_path.write_text(json.dumps(schema), encoding="utf-8")+ cmd = [exe, "exec", "--skip-git-repo-check", "--sandbox", "read-only",+ "--output-schema", str(schema_path), "--output-last-message", str(out_path)]+ if model:+ cmd += ["--model", model]+ cmd.append("-") # prompt on stdin+ try:+ p = subprocess.run(cmd, input=f"{system}\n\n{prompt}", capture_output=True, text=True, encoding="utf-8",+ errors="replace", cwd=tmp, env=env, timeout=600)+ except subprocess.TimeoutExpired as e:+ raise SummaryError("Codex CLI timed out after 10 minutes") from e+ text = out_path.read_text(encoding="utf-8") if out_path.exists() else ""+ if p.returncode != 0 or not text.strip():+ tail = (p.stderr or p.stdout or "").strip().splitlines()[-3:]+ raise SummaryError(f"Codex CLI failed (exit {p.returncode}): {' | '.join(tail)[:400]}")+ return _extract_json(text)+++# ---- provider: any OpenAI-compatible endpoint -----------------------------------++def _compatible(prompt: str, system: str, schema: dict, model: str, base_url: str) -> dict:+ if not base_url or not model:+ raise SummaryError("set a base URL and a model name in Settings > Summaries")+ url = base_url.rstrip("/") + "/chat/completions"+ headers = {"Content-Type": "application/json"}+ if config.summary_api_key():+ headers["Authorization"] = f"Bearer {config.summary_api_key()}"+ keys = ", ".join(schema["required"])+ messages = [{"role": "system", "content": f"{system}\n\nJSON keys: {keys}.\nJSON schema:\n{json.dumps(schema)}"},+ {"role": "user", "content": prompt}]+ # Strict schema first; endpoints that don't support it get plain JSON mode, then no hint at all.+ formats = [{"type": "json_schema", "json_schema": {"name": "summary", "strict": True, "schema": schema}},+ {"type": "json_object"}, None]+ last = ""+ for fmt in formats:+ body = {"model": model, "messages": messages}+ if fmt:+ body["response_format"] = fmt+ try:+ r = httpx.post(url, headers=headers, json=body, timeout=600)+ except httpx.HTTPError as e:+ raise SummaryError(f"can't reach {url}: {e}") from e+ if r.status_code in (400, 404, 415, 422, 501) and fmt is not None:+ last = r.text[:300]+ continue+ if r.status_code >= 400:+ raise SummaryError(f"{url} answered {r.status_code}: {r.text[:300]}")+ try:+ content = r.json()["choices"][0]["message"]["content"]+ except (ValueError, KeyError, IndexError, TypeError) as e:+ raise SummaryError(f"unexpected response from {url}: {r.text[:200]}") from e+ if isinstance(content, list): # some servers return content parts+ content = "".join(p.get("text", "") for p in content if isinstance(p, dict))+ return _extract_json(content or "")+ raise SummaryError(f"{url} rejected the request: {last}")+++# ---- entry points ---------------------------------------------------------------++def _run(prompt: str, system: str, schema: dict, cfg: dict) -> dict:+ provider = cfg.get("provider") or "claude_subscription"+ model = (cfg.get("model") or "").strip()+ if provider == "claude_subscription":+ out = asyncio.run(_claude(prompt, system, schema, model))+ elif provider == "codex_subscription":+ out = _codex(prompt, system, schema, model)+ elif provider == "openai_compatible":+ out = _compatible(prompt, system, schema, model, (cfg.get("base_url") or "").strip())+ else:+ raise SummaryError(f"unknown summary provider {provider!r}")+ return _normalize(out, schema)+++def conversation(transcript: str, when: str, duration_min: float, trigger: str, meeting: str | None,+ cfg: dict, wearer: str | None = None) -> dict:+ head = f"Recorded {when}, {duration_min:.0f} min, trigger: {trigger}."+ if meeting:+ head += f" Calendar meeting at that time: {meeting!r}."+ # ~150k chars is far beyond any realistic single conversation; trim the middle if it ever happens.+ if len(transcript) > 150_000:+ transcript = transcript[:75_000] + "\n[... middle trimmed ...]\n" + transcript[-75_000:]+ return _run(f"{head}\n\nTranscript:\n{transcript}", _conv_system(wearer), CONV_SCHEMA, cfg)+++def day(day_label: str, items: list[dict], cfg: dict, wearer: str | None = None) -> dict:+ body = "\n\n".join(+ f"[{i['time']}] {i['title']}\n{i['summary']}\nKey points: {'; '.join(i['key_points'])}\n"+ f"Action items: {'; '.join(a['item'] + (' (' + a['owner'] + ')' if a.get('owner') else '') for a in i['action_items'])}\n"+ f"People: {', '.join(i['people'])}" for i in items)+ return _run(f"Day: {day_label}\n\nConversations:\n\n{body}", DAY_SYSTEM.format(who=wearer or "the wearer"), DAY_SCHEMA, cfg)+++TEST_TRANSCRIPT = """Speaker A: Did the plumber call back about the kitchen sink?+Speaker B: Yes, he can come Thursday at nine. It's a hundred and eighty dollars for the new valve.+Speaker A: Fine, book it. I'll work from home that morning to let him in.+Speaker B: Okay, I'll confirm with him tonight and send you his number."""+++def test(cfg: dict) -> dict:+ """One tiny summary through the chosen provider, for the Settings "Test" button."""+ t0 = time.time()+ s = conversation(TEST_TRANSCRIPT, "today", 1, "manual", None, cfg)+ return {"ok": True, "seconds": round(time.time() - t0, 1), "title": s["title"], "summary": s["summary"],+ "action_items": len(s["action_items"])}+++_status_cache: dict[str, tuple[float, str | None]] = {}+++def status(cfg: dict) -> tuple[str, str | None]:+ """(label for the dashboard, problem or None). Cheap checks only, cached 10 minutes."""+ provider = cfg.get("provider") or "claude_subscription"+ if provider == "openai_compatible":+ if not (cfg.get("base_url") and cfg.get("model")):+ return "OpenAI-compatible (not set up)", "summaries need a base URL and model in Settings"+ return f"{cfg['model']} at {cfg['base_url']}", None+ hit = _status_cache.get(provider)+ if hit and time.time() - hit[0] < 600:+ problem = hit[1]+ else:+ problem = None+ if provider == "codex_subscription":+ if not shutil.which("codex"):+ problem = "Codex CLI is not installed: summaries are paused"+ else:+ exe = shutil.which("claude")+ try:+ st = json.loads(subprocess.run([exe, "auth", "status"], capture_output=True, text=True, timeout=20).stdout) if exe else {}+ except Exception:+ st = {}+ if not st.get("loggedIn"):+ problem = "Claude is not signed in (run `claude login`): summaries are paused"+ _status_cache[provider] = (time.time(), problem)+ label = "Codex CLI (ChatGPT subscription)" if provider == "codex_subscription" else "Claude subscription"+ return label, problemdiff --git a/tools/setup_watch.py b/tools/setup_watch.pynew file mode 100644index 0000000..f2e416e--- /dev/null+++ b/tools/setup_watch.py@@ -0,0 +1,130 @@+"""Install the watch app and point it at this PC. Run from the repo root, any Python 3.10+:++ python tools/setup_watch.py # Wi-Fi mode: http://<this PC's address>:8808+ python tools/setup_watch.py --url https://in.example.com # tunnel mode+ python tools/setup_watch.py --config-only # app already installed, just rewrite its config++Before running: on the watch turn on Developer options > Wireless debugging and connect it+(`adb pair <ip>:<port> <code>` once, then `adb connect <ip>:<port>`). See SETUP.md step 5.++What it does: installs the APK, grants the microphone and notification permissions, writes+files/config.json into the app's private storage (server address + upload token), opens the app.+Nothing is typed on the watch.+"""++from __future__ import annotations++import argparse+import json+import os+import shutil+import socket+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+PKG = "com.leveledai.voicecapture.open"+ACTIVITY = f"{PKG}/com.leveledai.voicecapture.MainActivity"+APK_PATHS = [ROOT / "dist" / "voice-capture-watch.apk",+ ROOT / "watch" / "app" / "build" / "outputs" / "apk" / "debug" / "app-debug.apk"]+++def env_file() -> dict:+ out = {}+ p = ROOT / ".env"+ if p.exists():+ for ln in p.read_text(encoding="utf-8").splitlines():+ if "=" in ln and not ln.lstrip().startswith("#"):+ k, v = ln.split("=", 1)+ out[k.strip()] = v.strip()+ return out+++def find_adb() -> str:+ exe = shutil.which("adb")+ if exe:+ return exe+ for base in (os.environ.get("ANDROID_HOME"), os.environ.get("ANDROID_SDK_ROOT"),+ os.path.join(os.environ.get("LOCALAPPDATA", ""), "Android", "Sdk")):+ if base:+ cand = Path(base) / "platform-tools" / ("adb.exe" if os.name == "nt" else "adb")+ if cand.exists():+ return str(cand)+ sys.exit("adb not found. Install Android platform-tools (winget install Google.PlatformTools) and try again.")+++def lan_ip() -> str:+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ s.connect(("10.255.255.255", 1)) # no packet is sent; this only picks the outgoing interface+ return s.getsockname()[0]+ except OSError:+ return "127.0.0.1"+ finally:+ s.close()+++def main() -> None:+ ap = argparse.ArgumentParser(description="Install and configure the Voice Capture watch app")+ ap.add_argument("--url", help="server address the watch uploads to (default: this PC on the home network)")+ ap.add_argument("--serial", help="adb device serial, when more than one device is connected")+ ap.add_argument("--apk", help="path to the APK (default: dist/ or the gradle build output)")+ ap.add_argument("--device-id", default="galaxy-watch", help="name stored with each recording")+ ap.add_argument("--config-only", action="store_true", help="skip the install, only rewrite the config")+ a = ap.parse_args()++ env = env_file()+ token = env.get("INGEST_TOKEN")+ if not token:+ sys.exit("No INGEST_TOKEN in .env yet. Run `python launch.py token` first.")+ url = (a.url or f"http://{lan_ip()}:{env.get('PORT') or 8808}").rstrip("/")+ if "127.0.0.1" in url and not a.url:+ sys.exit("Could not find this PC's network address. Pass it yourself: --url http://192.168.x.x:8808")++ adb = find_adb()+ serial = a.serial+ if not serial:+ rows = [ln.split() for ln in subprocess.run([adb, "devices"], capture_output=True, text=True).stdout.splitlines()[1:]]+ ready = [r[0] for r in rows if len(r) >= 2 and r[1] == "device"]+ # A wirelessly connected watch often shows twice (ip:port and an mDNS name). Prefer ip:port.+ ip_ports = [d for d in ready if d.count(".") == 3 and ":" in d]+ if len(ip_ports) == 1:+ ready = ip_ports+ if not ready:+ sys.exit("No watch connected. On the watch: Developer options > Wireless debugging, then "+ "`adb pair <ip>:<port> <code>` once and `adb connect <ip>:<port>`.")+ if len(ready) > 1:+ sys.exit(f"More than one device connected ({', '.join(ready)}). Pick one with --serial.")+ serial = ready[0]++ def run(*args: str, stdin: str | None = None, check: bool = True) -> str:+ p = subprocess.run([adb, "-s", serial, *args], input=stdin, capture_output=True, text=True)+ if check and p.returncode != 0:+ sys.exit(f"adb {' '.join(args)} failed: {(p.stderr or p.stdout).strip()}")+ return (p.stdout or "").strip()++ if not a.config_only:+ apk = Path(a.apk) if a.apk else next((p for p in APK_PATHS if p.exists()), None)+ if not apk or not apk.exists():+ sys.exit("No APK found. Download voice-capture-watch.apk from the Releases page into dist/, "+ "or build it: cd watch && gradlew.bat assembleDebug")+ print(f"Installing {apk.name} on {serial} ...")+ run("install", "-r", str(apk))+ for perm in ("RECORD_AUDIO", "POST_NOTIFICATIONS"):+ run("shell", "pm", "grant", PKG, f"android.permission.{perm}", check=False)++ cfg = {"server_url": url, "ingest_token": token, "device_id": a.device_id}+ if env.get("CF_ACCESS_CLIENT_ID") and env.get("CF_ACCESS_CLIENT_SECRET"): # Cloudflare Access service token+ cfg["cf_client_id"], cfg["cf_client_secret"] = env["CF_ACCESS_CLIENT_ID"], env["CF_ACCESS_CLIENT_SECRET"]+ run("shell", f"run-as {PKG} sh -c 'mkdir -p files && cat > files/config.json && chmod 600 files/config.json'",+ stdin=json.dumps(cfg))+ run("shell", "am", "force-stop", PKG, check=False)+ run("shell", "am", "start", "-n", ACTIVITY)+ print(json.dumps({"ok": True, "watch": serial, "server_url": url,+ "next": "Open Voice Capture on the watch, tap Record, say a few words, tap Stop. "+ "The conversation shows up in the dashboard within a minute or two."}, indent=2))+++if __name__ == "__main__":+ main()diff --git a/transcribe.py b/transcribe.pynew file mode 100644index 0000000..e78af80--- /dev/null+++ b/transcribe.py@@ -0,0 +1,161 @@+"""WhisperX on this PC: transcribe -> word alignment -> speaker diarization.++Models load lazily and are dropped after `model_idle_unload_minutes`, so the GPU's memory is free+whenever nothing is being transcribed. Diarization needs HF_TOKEN (pyannote is gated); without it+every segment is labeled with one speaker and the pipeline still works.++Built and tested on an NVIDIA GPU. With "device": "auto" it falls back to the CPU (int8) when+CUDA isn't available; that path is much slower and has not been tested.+"""++from __future__ import annotations++import gc+import subprocess+import time+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np++import config++SAMPLE_RATE = 16000+++@dataclass+class Result:+ duration_s: float+ language: str | None+ segments: list[dict] # {start_s, end_s, label, text}+ speakers: dict[str, dict] = field(default_factory=dict) # label -> {embedding: np.ndarray|None, speech_s}+++def to_wav(paths: list[Path], out: Path) -> Path:+ """Decode and join chunks (any format ffmpeg reads) into one 16 kHz mono WAV."""+ args = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"]+ for p in paths:+ args += ["-i", str(p)]+ n = len(paths)+ if n == 1:+ args += ["-ac", "1", "-ar", str(SAMPLE_RATE), str(out)]+ else:+ inputs = "".join(f"[{i}:a]" for i in range(n))+ args += ["-filter_complex", f"{inputs}concat=n={n}:v=0:a=1[a]", "-map", "[a]",+ "-ac", "1", "-ar", str(SAMPLE_RATE), str(out)]+ subprocess.run(args, check=True, capture_output=True, timeout=1800)+ return out+++class Engine:+ def __init__(self):+ want = config.tunables().get("device") or "auto"+ if want == "auto":+ try:+ import torch+ want = "cuda" if torch.cuda.is_available() else "cpu"+ except Exception:+ want = "cpu"+ self.device = want+ self._asr = None+ self._align: dict[str, tuple] = {}+ self._diar = None+ self.last_used = 0.0++ # -- model lifecycle --+ def _whisperx(self):+ import whisperx # heavy import, keep it lazy+ return whisperx++ def asr(self):+ if self._asr is None:+ cfg = config.tunables()+ self._asr = self._whisperx().load_model(cfg["whisper_model"], self.device,+ compute_type=cfg["compute_type"] if self.device == "cuda" else "int8",+ language=cfg["language"] or None)+ return self._asr++ def aligner(self, lang: str):+ if lang not in self._align:+ self._align[lang] = self._whisperx().load_align_model(language_code=lang, device=self.device)+ return self._align[lang]++ def diarizer(self):+ if self._diar is None and config.hf_token():+ from whisperx.diarize import DiarizationPipeline+ self._diar = DiarizationPipeline(model_name=config.tunables()["diarize_model"],+ token=config.hf_token(), device=self.device)+ return self._diar++ def loaded(self) -> bool:+ return bool(self._asr or self._align or self._diar)++ def unload(self) -> None:+ self._asr, self._align, self._diar = None, {}, None+ gc.collect()+ try:+ import torch+ torch.cuda.empty_cache()+ except Exception:+ pass++ def maybe_unload(self) -> None:+ if self.loaded() and time.time() - self.last_used > config.tunables()["model_idle_unload_minutes"] * 60:+ self.unload()++ # -- work --+ def _diarize(self, audio: np.ndarray):+ d = self.diarizer()+ if d is None:+ return None, {}+ df, embs = d(audio, return_embeddings=True)+ return df, (embs or {})++ def run(self, wav: Path) -> Result:+ self.last_used = time.time()+ wx = self._whisperx()+ cfg = config.tunables()+ audio = wx.load_audio(str(wav))+ duration = len(audio) / SAMPLE_RATE+ out = self.asr().transcribe(audio, batch_size=cfg["batch_size"], language=cfg["language"] or None)+ lang = out.get("language") or cfg["language"] or "en"+ if not out.get("segments"):+ return Result(duration, lang, [])+ try:+ model_a, meta = self.aligner(lang)+ out = wx.align(out["segments"], model_a, meta, audio, self.device, return_char_alignments=False)+ except Exception:+ pass # no aligner for this language: keep segment-level timing+ try:+ df, embs = self._diarize(audio)+ except Exception as e: # gated repo, bad token, OOM: never lose the transcript over speaker labels+ print(f"diarization skipped: {str(e).splitlines()[0][:200]}", flush=True)+ self._diar = None+ df, embs = None, {}+ if df is not None:+ out = wx.assign_word_speakers(df, out)+ segs, speech = [], {}+ for s in out["segments"]:+ text = (s.get("text") or "").strip()+ if not any(ch.isalnum() for ch in text):+ continue # Whisper turns noise into "." / "..." segments; drop them+ label = s.get("speaker") or "SPEAKER_00"+ segs.append({"start_s": float(s["start"]), "end_s": float(s["end"]), "label": label, "text": text})+ speech[label] = speech.get(label, 0.0) + float(s["end"]) - float(s["start"])+ speakers = {lab: {"embedding": np.asarray(embs[lab], dtype=np.float32) if lab in embs else None,+ "speech_s": sec} for lab, sec in speech.items()}+ self.last_used = time.time()+ return Result(duration, lang, segs, speakers)++ def voiceprint(self, wav: Path) -> np.ndarray:+ """Embedding of the dominant speaker in an enrollment clip."""+ self.last_used = time.time()+ if not config.hf_token():+ raise RuntimeError("voice enrollment needs HF_TOKEN (pyannote)")+ audio = self._whisperx().load_audio(str(wav))+ df, embs = self._diarize(audio)+ if df is None or not embs:+ raise RuntimeError("no speech found in the enrollment clip")+ df = df.assign(dur=df["end"] - df["start"])+ top = df.groupby("speaker")["dur"].sum().idxmax()+ return np.asarray(embs[top], dtype=np.float32)diff --git a/watch/app/build.gradle.kts b/watch/app/build.gradle.ktsnew file mode 100644index 0000000..3732637--- /dev/null+++ b/watch/app/build.gradle.kts@@ -0,0 +1,53 @@+plugins {+ id("com.android.application")+ id("org.jetbrains.kotlin.android")+ id("org.jetbrains.kotlin.plugin.compose")+}++android {+ namespace = "com.leveledai.voicecapture"+ compileSdk = 36++ defaultConfig {+ applicationId = "com.leveledai.voicecapture.open" // the id adb and run-as use+ minSdk = 30 // Wear OS 3++ targetSdk = 36+ versionCode = 1+ versionName = "1.0.0"+ ndk { abiFilters += listOf("armeabi-v7a", "arm64-v8a") } // the Watch7 userspace is 32-bit ARM+ }++ buildTypes {+ // Sideloaded over ADB only. Debug build on purpose: `run-as` lets the PC write the+ // config (server URL + tokens) into private storage without any exported component.+ debug { isMinifyEnabled = false }+ }+ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }+ kotlin {+ compilerOptions {+ jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)+ }+ }+ buildFeatures { compose = true }+ androidResources { noCompress += "onnx" } // lets assets.openFd() report the size+}++dependencies {+ implementation("androidx.core:core-ktx:1.18.0")+ implementation("androidx.activity:activity-compose:1.13.0")+ implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.10.0")+ implementation("androidx.lifecycle:lifecycle-service:2.10.0")+ implementation(platform("androidx.compose:compose-bom:2026.06.01"))+ implementation("androidx.compose.ui:ui")+ implementation("androidx.wear.compose:compose-material:1.5.0")+ implementation("androidx.wear.compose:compose-foundation:1.5.0")+ implementation("androidx.wear:wear-ongoing:1.0.0")+ implementation("androidx.wear.watchface:watchface-complications-data-source-ktx:1.2.1")+ implementation("androidx.work:work-runtime-ktx:2.10.0")+ implementation("com.squareup.okhttp3:okhttp:4.12.0")+ implementation("com.microsoft.onnxruntime:onnxruntime-android:1.20.0") // Silero VAD+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")+}diff --git a/watch/app/src/main/AndroidManifest.xml b/watch/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..003b38b--- /dev/null+++ b/watch/app/src/main/AndroidManifest.xml@@ -0,0 +1,86 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-feature android:name="android.hardware.type.watch" />+ <uses-feature android:name="android.hardware.microphone" android:required="true" />++ <uses-permission android:name="android.permission.RECORD_AUDIO" />+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-permission android:name="android.permission.WAKE_LOCK" />+ <uses-permission android:name="android.permission.VIBRATE" />+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />+ <uses-permission android:name="android.permission.USE_EXACT_ALARM" />+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />++ <application+ android:allowBackup="false"+ android:icon="@drawable/ic_launcher"+ android:label="@string/app_name"+ android:networkSecurityConfig="@xml/network_security_config"+ android:theme="@android:style/Theme.DeviceDefault">++ <meta-data android:name="com.google.android.wearable.standalone" android:value="true" />++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:taskAffinity="">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <!-- Second launcher entry: pick this one for the Home-key double press.+ It flips recording on/off, buzzes, and closes without showing UI. -->+ <activity+ android:name=".ToggleActivity"+ android:exported="true"+ android:excludeFromRecents="true"+ android:icon="@drawable/ic_toggle"+ android:label="@string/toggle_name"+ android:noHistory="true"+ android:taskAffinity="com.leveledai.voicecapture.toggle"+ android:theme="@android:style/Theme.Translucent.NoTitleBar">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <service+ android:name=".RecorderService"+ android:exported="false"+ android:foregroundServiceType="microphone" />++ <!-- After a reboot or app update Android won't let us reopen the mic from the background:+ post a "tap to resume auto mode" notification instead. -->+ <receiver android:name=".BootReceiver" android:exported="false">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+ </intent-filter>+ </receiver>++ <service+ android:name=".RecComplicationService"+ android:exported="true"+ android:icon="@drawable/ic_mic"+ android:label="@string/complication_name"+ android:permission="com.google.android.wearable.permission.BIND_COMPLICATION_PROVIDER">+ <intent-filter>+ <action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" />+ </intent-filter>+ <meta-data+ android:name="android.support.wearable.complications.SUPPORTED_TYPES"+ android:value="SHORT_TEXT,MONOCHROMATIC_IMAGE,SMALL_IMAGE" />+ <meta-data+ android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS"+ android:value="0" />+ </service>+ </application>+</manifest>diff --git a/watch/app/src/main/assets/silero_vad.onnx b/watch/app/src/main/assets/silero_vad.onnxnew file mode 100644index 0000000..80c5592Binary files /dev/null and b/watch/app/src/main/assets/silero_vad.onnx differdiff --git a/watch/app/src/main/java/com/leveledai/voicecapture/AppState.kt b/watch/app/src/main/java/com/leveledai/voicecapture/AppState.ktnew file mode 100644index 0000000..d11dd11--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/AppState.kt@@ -0,0 +1,75 @@+package com.leveledai.voicecapture++import android.content.Context+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import org.json.JSONObject+import java.io.File++/**+ * Server config is written by the PC over ADB (tools/setup_watch.py, `run-as ... files/config.json`), never typed on the+ * watch and never exposed through an exported component:+ * {"server_url": "http://192.168.1.50:8808", "ingest_token": "...",+ * "cf_client_id": "...", "cf_client_secret": "...", "device_id": "galaxy-watch"}+ */+data class ServerConfig(+ val serverUrl: String,+ val ingestToken: String,+ val cfClientId: String?,+ val cfClientSecret: String?,+ val deviceId: String,+) {+ companion object {+ fun load(ctx: Context): ServerConfig? {+ val f = File(ctx.filesDir, "config.json")+ if (!f.exists()) return null+ return try {+ val j = JSONObject(f.readText())+ ServerConfig(+ serverUrl = j.getString("server_url").trimEnd('/'),+ ingestToken = j.getString("ingest_token"),+ cfClientId = j.optString("cf_client_id").ifBlank { null },+ cfClientSecret = j.optString("cf_client_secret").ifBlank { null },+ deviceId = j.optString("device_id").ifBlank { "galaxy-watch" },+ )+ } catch (e: Exception) {+ null+ }+ }+ }+}++enum class Mode { MANUAL, AUTO }++/** Process-wide UI state. The service and the upload worker push into it; the UI and complication read it. */+object AppState {+ val recording = MutableStateFlow(false)+ /** Mic open in auto mode (listening for speech or recording). */+ val listening = MutableStateFlow(false)+ /** One-line auto-mode status for the UI, null when auto mode is off. */+ val autoStatus = MutableStateFlow<String?>(null)+ val recordingSince = MutableStateFlow<Long?>(null)+ val pendingChunks = MutableStateFlow(0)+ val lastUpload = MutableStateFlow<String?>(null)++ private const val PREFS = "voice_capture"++ fun prefs(ctx: Context) = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++ fun mode(ctx: Context): Mode =+ if (prefs(ctx).getString("mode", "MANUAL") == "AUTO") Mode.AUTO else Mode.MANUAL++ fun setMode(ctx: Context, m: Mode) = prefs(ctx).edit().putString("mode", m.name).apply()++ fun setLastUpload(ctx: Context, msg: String) {+ lastUpload.value = msg+ prefs(ctx).edit().putString("last_upload", msg).apply()+ }++ fun restore(ctx: Context) {+ if (lastUpload.value == null) lastUpload.value = prefs(ctx).getString("last_upload", null)+ pendingChunks.value = Outbox.count(ctx)+ }++ val recordingFlow: StateFlow<Boolean> get() = recording+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/ChunkWriter.kt b/watch/app/src/main/java/com/leveledai/voicecapture/ChunkWriter.ktnew file mode 100644index 0000000..d7092d9--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/ChunkWriter.kt@@ -0,0 +1,128 @@+package com.leveledai.voicecapture++import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.media.MediaMuxer+import java.io.File++/**+ * One audio chunk: 16 kHz mono PCM in -> Opus in an Ogg file out (MediaCodec + MediaMuxer, API 29+).+ * Falls back to AAC in .m4a if the device has no Opus encoder. The Galaxy Watch7 has+ * c2.android.opus.encoder, so Opus is the normal path (~24 kbps, about 11 MB per hour).+ */+class ChunkWriter private constructor(val file: File, private val mime: String, muxFormat: Int,+ private val sampleRate: Int, bitrate: Int) {++ companion object {+ const val SAMPLE_RATE = 16000++ fun create(base: File, sampleRate: Int = SAMPLE_RATE): ChunkWriter {+ return try {+ ChunkWriter(File(base.path + ".ogg"), MediaFormat.MIMETYPE_AUDIO_OPUS,+ MediaMuxer.OutputFormat.MUXER_OUTPUT_OGG, sampleRate, 24_000)+ } catch (e: Exception) {+ ChunkWriter(File(base.path + ".m4a"), MediaFormat.MIMETYPE_AUDIO_AAC,+ MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4, sampleRate, 32_000)+ }+ }+ }++ private val codec: MediaCodec = MediaCodec.createEncoderByType(mime)+ private val muxer: MediaMuxer+ private val info = MediaCodec.BufferInfo()+ private var track = -1+ private var muxing = false+ private var samplesIn = 0L+ var samplesWritten = 0L+ private set++ init {+ val fmt = MediaFormat.createAudioFormat(mime, sampleRate, 1).apply {+ setInteger(MediaFormat.KEY_BIT_RATE, bitrate)+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 16 * 1024)+ if (mime == MediaFormat.MIMETYPE_AUDIO_AAC)+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)+ }+ try {+ codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+ codec.start()+ muxer = MediaMuxer(file.path, muxFormat)+ } catch (e: Exception) {+ runCatching { codec.release() }+ file.delete()+ throw e+ }+ }++ val ext: String get() = file.extension+ val durationS: Double get() = samplesWritten.toDouble() / sampleRate++ /** pcm: little-endian 16-bit mono samples, `len` bytes. */+ fun write(pcm: ByteArray, len: Int) {+ var off = 0+ while (off < len) {+ val inIdx = codec.dequeueInputBuffer(10_000)+ if (inIdx >= 0) {+ val buf = codec.getInputBuffer(inIdx)!!+ buf.clear()+ val n = minOf(buf.remaining(), len - off)+ buf.put(pcm, off, n)+ val ptsUs = samplesIn * 1_000_000L / sampleRate+ codec.queueInputBuffer(inIdx, 0, n, ptsUs, 0)+ samplesIn += n / 2+ off += n+ }+ drain(false)+ }+ samplesWritten = samplesIn+ }++ private fun drain(eos: Boolean) {+ while (true) {+ val outIdx = codec.dequeueOutputBuffer(info, if (eos) 10_000 else 0)+ when {+ outIdx == MediaCodec.INFO_TRY_AGAIN_LATER -> if (!eos) return+ outIdx == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {+ track = muxer.addTrack(codec.outputFormat)+ muxer.start()+ muxing = true+ }+ outIdx >= 0 -> {+ val buf = codec.getOutputBuffer(outIdx)!!+ val config = info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0+ if (!config && info.size > 0 && muxing) {+ buf.position(info.offset)+ buf.limit(info.offset + info.size)+ muxer.writeSampleData(track, buf, info)+ }+ codec.releaseOutputBuffer(outIdx, false)+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return+ }+ }+ }+ }++ /** Flush and close. Returns false (and deletes the file) if nothing was recorded. */+ fun finish(): Boolean {+ var ok = samplesIn > 0+ try {+ if (ok) {+ var inIdx: Int+ do { inIdx = codec.dequeueInputBuffer(10_000); if (inIdx < 0) drain(false) } while (inIdx < 0)+ codec.queueInputBuffer(inIdx, 0, 0, samplesIn * 1_000_000L / sampleRate,+ MediaCodec.BUFFER_FLAG_END_OF_STREAM)+ drain(true)+ }+ } catch (e: Exception) {+ ok = false+ } finally {+ runCatching { codec.stop() }+ runCatching { codec.release() }+ if (muxing) runCatching { muxer.stop() }.onFailure { ok = false }+ runCatching { muxer.release() }+ }+ if (!ok || !muxing) file.delete()+ return ok && muxing+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/MainActivity.kt b/watch/app/src/main/java/com/leveledai/voicecapture/MainActivity.ktnew file mode 100644index 0000000..2c41057--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/MainActivity.kt@@ -0,0 +1,157 @@+package com.leveledai.voicecapture++import android.Manifest+import android.content.pm.PackageManager+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.ButtonDefaults+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Scaffold+import androidx.wear.compose.material.Text+import androidx.wear.compose.material.TimeText+import androidx.wear.compose.material.ToggleChip+import androidx.wear.compose.material.ToggleChipDefaults+import kotlinx.coroutines.delay++class MainActivity : ComponentActivity() {++ private val askPerms = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ AppState.restore(this)+ Uploader.schedulePeriodic(this)+ val need = listOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS)+ .filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }+ if (need.isNotEmpty()) askPerms.launch(need.toTypedArray())+ // Opening the app (a visible activity) is the one moment Android lets us (re)start the+ // microphone service, so resume auto mode here after a reboot or update.+ if (AppState.mode(this) == Mode.AUTO && need.isEmpty()) {+ Notifications.clear(this)+ startForegroundService(RecorderService.intent(this, RecorderService.ACTION_AUTO_ON))+ }+ setContent { MaterialTheme { Screen() } }+ }++ override fun onResume() {+ super.onResume()+ AppState.restore(this)+ }++ @Composable+ private fun Screen() {+ val recording by AppState.recording.collectAsState()+ val since by AppState.recordingSince.collectAsState()+ val pending by AppState.pendingChunks.collectAsState()+ val autoStatus by AppState.autoStatus.collectAsState()+ val last by AppState.lastUpload.collectAsState()+ var now by remember { mutableLongStateOf(System.currentTimeMillis()) }+ var mode by remember { mutableLongStateOf(if (AppState.mode(this) == Mode.AUTO) 1L else 0L) }+ var saver by remember { mutableLongStateOf(if (AppState.prefs(this).getBoolean("battery_saver", false)) 1L else 0L) }+ val configured = remember { ServerConfig.load(this) != null }+ LaunchedEffect(recording) { while (recording) { now = System.currentTimeMillis(); delay(1000) } }+ val listState = rememberScalingLazyListState()++ Scaffold(timeText = { TimeText() }) {+ ScalingLazyColumn(state = listState, modifier = Modifier.fillMaxSize(),+ horizontalAlignment = Alignment.CenterHorizontally) {+ item {+ Box(Modifier.padding(top = 16.dp), contentAlignment = Alignment.Center) {+ Button(+ onClick = {+ startForegroundService(RecorderService.intent(this@MainActivity, RecorderService.ACTION_TOGGLE))+ },+ modifier = Modifier.size(84.dp),+ colors = ButtonDefaults.buttonColors(+ backgroundColor = if (recording) Color(0xFF1E3A8A) else Color(0xFF2563EB)),+ ) {+ Box(Modifier.size(if (recording) 26.dp else 30.dp)+ .clip(if (recording) androidx.compose.foundation.shape.RoundedCornerShape(4.dp) else CircleShape)+ .background(Color.White))+ }+ }+ }+ item {+ val secs = since?.let { (now - it) / 1000 } ?: 0+ Text(if (recording) "Recording %d:%02d".format(secs / 60, secs % 60) else "Tap to record",+ fontWeight = FontWeight.SemiBold, fontSize = 15.sp, modifier = Modifier.padding(top = 6.dp))+ }+ item {+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(2.dp),+ modifier = Modifier.padding(vertical = 6.dp)) {+ if (!configured) Text("Not set up yet", color = Color(0xFFFBBF24), fontSize = 12.sp)+ Text(if (pending == 0) "All uploaded" else "$pending waiting to upload",+ fontSize = 12.sp, color = Color.LightGray)+ last?.let { Text(it, fontSize = 11.sp, color = Color.Gray, textAlign = TextAlign.Center) }+ }+ }+ item {+ ToggleChip(+ checked = mode == 1L,+ onCheckedChange = {+ mode = if (it) 1L else 0L+ AppState.setMode(this@MainActivity, if (it) Mode.AUTO else Mode.MANUAL)+ startForegroundService(RecorderService.intent(this@MainActivity,+ if (it) RecorderService.ACTION_AUTO_ON else RecorderService.ACTION_AUTO_OFF))+ },+ label = { Text("Auto mode") },+ secondaryLabel = { Text(if (mode == 1L) (autoStatus ?: "Auto: starting") else "Manual: button only",+ maxLines = 2, fontSize = 11.sp) },+ toggleControl = { androidx.wear.compose.material.Switch(checked = mode == 1L) },+ modifier = Modifier.fillMaxWidth(),+ colors = ToggleChipDefaults.toggleChipColors(),+ )+ }+ item {+ ToggleChip(+ checked = saver == 1L,+ onCheckedChange = {+ saver = if (it) 1L else 0L+ AppState.prefs(this@MainActivity).edit().putBoolean("battery_saver", it).apply()+ Uploader.schedulePeriodic(this@MainActivity)+ },+ label = { Text("Battery saver") },+ secondaryLabel = { Text("Upload on Wi-Fi only") },+ toggleControl = { androidx.wear.compose.material.Switch(checked = saver == 1L) },+ modifier = Modifier.fillMaxWidth(),+ )+ }+ item {+ Chip(onClick = { Uploader.kick(this@MainActivity) }, label = { Text("Upload now") },+ colors = ChipDefaults.secondaryChipColors(), modifier = Modifier.fillMaxWidth())+ }+ }+ }+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/Notifications.kt b/watch/app/src/main/java/com/leveledai/voicecapture/Notifications.ktnew file mode 100644index 0000000..128fe70--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/Notifications.kt@@ -0,0 +1,37 @@+package com.leveledai.voicecapture++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat++object Notifications {+ private const val CHANNEL = "auto_resume"+ private const val ID = 2++ /** Tapping opens the app, and the app (a visible activity) is allowed to restart the mic service. */+ fun resumeAuto(ctx: Context) {+ val nm = ctx.getSystemService(NotificationManager::class.java)+ nm.createNotificationChannel(NotificationChannel(CHANNEL, "Auto mode", NotificationManager.IMPORTANCE_DEFAULT))+ val open = PendingIntent.getActivity(ctx, 3, Intent(ctx, MainActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ nm.notify(ID, NotificationCompat.Builder(ctx, CHANNEL)+ .setSmallIcon(R.drawable.ic_mic)+ .setContentTitle("Auto mode is paused")+ .setContentText("Tap to turn auto recording back on")+ .setAutoCancel(true)+ .setContentIntent(open)+ .build())+ }++ fun clear(ctx: Context) = ctx.getSystemService(NotificationManager::class.java).cancel(ID)+}++class BootReceiver : BroadcastReceiver() {+ override fun onReceive(ctx: Context, intent: Intent) {+ if (AppState.mode(ctx) == Mode.AUTO) Notifications.resumeAuto(ctx)+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/Outbox.kt b/watch/app/src/main/java/com/leveledai/voicecapture/Outbox.ktnew file mode 100644index 0000000..fe07e80--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/Outbox.kt@@ -0,0 +1,57 @@+package com.leveledai.voicecapture++import android.content.Context+import org.json.JSONObject+import java.io.File+import java.security.MessageDigest++/**+ * Finished chunks waiting for upload: filesDir/outbox/<recordingId>__<idx>.ogg + a .json sidecar.+ * A chunk is deleted only after the server confirms it stored the same SHA-256.+ */+object Outbox {+ fun dir(ctx: Context): File = File(ctx.filesDir, "outbox").apply { mkdirs() }++ data class Item(val audio: File, val meta: JSONObject)++ fun audioFile(ctx: Context, recordingId: String, idx: Int, ext: String) =+ File(dir(ctx), "${recordingId}__${"%05d".format(idx)}.$ext")++ /** Write the sidecar last: a chunk without a sidecar is still being written and is ignored. */+ fun commit(audio: File, meta: JSONObject) {+ meta.put("sha256", sha256(audio))+ val tmp = File(audio.path + ".json.tmp")+ tmp.writeText(meta.toString())+ tmp.renameTo(File(audio.path + ".json"))+ }++ fun pending(ctx: Context): List<Item> =+ dir(ctx).listFiles { f -> f.name.endsWith(".json") && !f.name.endsWith(".tmp") }+ .orEmpty()+ .sortedBy { it.name }+ .mapNotNull { side ->+ val audio = File(side.path.removeSuffix(".json"))+ if (!audio.exists()) { side.delete(); null }+ else runCatching { Item(audio, JSONObject(side.readText())) }.getOrNull()+ }++ fun count(ctx: Context) = pending(ctx).size++ fun remove(item: Item) {+ item.audio.delete()+ File(item.audio.path + ".json").delete()+ }++ fun sha256(f: File): String {+ val md = MessageDigest.getInstance("SHA-256")+ f.inputStream().use { s ->+ val buf = ByteArray(64 * 1024)+ while (true) {+ val n = s.read(buf)+ if (n <= 0) break+ md.update(buf, 0, n)+ }+ }+ return md.digest().joinToString("") { "%02x".format(it) }+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/RecComplicationService.kt b/watch/app/src/main/java/com/leveledai/voicecapture/RecComplicationService.ktnew file mode 100644index 0000000..1ac74f0--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/RecComplicationService.kt@@ -0,0 +1,59 @@+package com.leveledai.voicecapture++import android.app.PendingIntent+import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.graphics.drawable.Icon+import androidx.wear.watchface.complications.data.ComplicationData+import androidx.wear.watchface.complications.data.ComplicationType+import androidx.wear.watchface.complications.data.MonochromaticImage+import androidx.wear.watchface.complications.data.MonochromaticImageComplicationData+import androidx.wear.watchface.complications.data.PlainComplicationText+import androidx.wear.watchface.complications.data.ShortTextComplicationData+import androidx.wear.watchface.complications.data.SmallImage+import androidx.wear.watchface.complications.data.SmallImageComplicationData+import androidx.wear.watchface.complications.data.SmallImageType+import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester+import androidx.wear.watchface.complications.datasource.ComplicationRequest+import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService++/** Watch-face slot: tap to start/stop. Dark blue dot + "REC" while recording, mic + "AUTO" while auto mode listens, mic + "Rec" when idle. */+class RecComplicationService : SuspendingComplicationDataSourceService() {++ companion object {+ fun refresh(ctx: Context) {+ ComplicationDataSourceUpdateRequester.create(ctx, ComponentName(ctx, RecComplicationService::class.java))+ .requestUpdateAll()+ }+ }++ private fun tap(): PendingIntent = PendingIntent.getActivity(this, 0,+ Intent(this, ToggleActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)++ private fun build(type: ComplicationType, recording: Boolean, listening: Boolean = false): ComplicationData? {+ val iconRes = if (recording) R.drawable.ic_rec else R.drawable.ic_mic+ val icon = Icon.createWithResource(this, iconRes)+ val desc = PlainComplicationText.Builder(when {+ recording -> "Recording, tap to stop"+ listening -> "Auto mode listening, tap to record now"+ else -> "Tap to record" }).build()+ val mono = MonochromaticImage.Builder(icon).build()+ return when (type) {+ ComplicationType.SHORT_TEXT -> ShortTextComplicationData.Builder(+ PlainComplicationText.Builder(when { recording -> "REC"; listening -> "AUTO"; else -> "Rec" }).build(), desc)+ .setMonochromaticImage(mono).setTapAction(tap()).build()+ ComplicationType.MONOCHROMATIC_IMAGE -> MonochromaticImageComplicationData.Builder(mono, desc)+ .setTapAction(tap()).build()+ ComplicationType.SMALL_IMAGE -> SmallImageComplicationData.Builder(+ SmallImage.Builder(icon, SmallImageType.ICON).build(), desc).setTapAction(tap()).build()+ else -> null+ }+ }++ override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? =+ build(request.complicationType, AppState.recording.value, AppState.listening.value)++ override fun getPreviewData(type: ComplicationType): ComplicationData? = build(type, false)+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/RecorderService.kt b/watch/app/src/main/java/com/leveledai/voicecapture/RecorderService.ktnew file mode 100644index 0000000..60b179d--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/RecorderService.kt@@ -0,0 +1,487 @@+package com.leveledai.voicecapture++import android.Manifest+import android.annotation.SuppressLint+import android.app.AlarmManager+import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.content.pm.ServiceInfo+import android.hardware.Sensor+import android.hardware.SensorEvent+import android.hardware.SensorEventListener+import android.hardware.SensorManager+import android.media.AudioFormat+import android.media.AudioRecord+import android.media.MediaRecorder+import android.os.Handler+import android.os.IBinder+import android.os.Looper+import android.os.PowerManager+import android.os.SystemClock+import android.os.VibrationEffect+import android.os.Vibrator+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.content.ContextCompat+import androidx.wear.ongoing.OngoingActivity+import androidx.wear.ongoing.Status+import org.json.JSONObject+import java.io.File+import java.time.OffsetDateTime+import java.time.temporal.ChronoUnit+import java.util.UUID++/**+ * Foreground microphone service. Three states:+ * idle - service not running (manual mode, nothing recording)+ * listening - auto mode, gate open, watch worn: mic open, Silero VAD watching, nothing written+ * recording - writing 120 s Opus chunks to the outbox (started by speech, or by the button)+ *+ * Auto mode keeps the service in the foreground (type microphone) even while the gate is closed,+ * because Android 14+ won't let a background alarm start a microphone service from scratch. With+ * the gate closed the mic is released, no wake lock is held, and an exact alarm wakes us at the+ * next window / meeting boundary.+ *+ * One recording = one conversation. Silence ends it (auto: silence.auto_end_min, button-started:+ * silence.manual_stop_min, 0 = never). The PC stitches recordings that are minutes apart.+ */+class RecorderService : Service(), SensorEventListener {++ companion object {+ private const val TAG = "VoiceCapture"+ const val ACTION_START = "start"+ const val ACTION_STOP = "stop"+ const val ACTION_TOGGLE = "toggle"+ const val ACTION_AUTO_ON = "auto_on"+ const val ACTION_AUTO_OFF = "auto_off"+ const val ACTION_EVAL = "eval"+ const val EXTRA_TRIGGER = "trigger"+ private const val CHANNEL = "recording"+ private const val NOTIF_ID = 1+ const val CHUNK_SECONDS = 120+ private const val PREROLL_FRAMES = 63 // ~2 s of 32 ms frames+ private const val START_WINDOW = 47 // ~1.5 s+ private const val START_SPEECH_FRAMES = 12 // ~0.4 s of speech inside the window starts a recording+ private const val SPEECH_P = 0.5f+ private const val RMS_FLOOR = 0.0025f // below this the room is quiet: skip the model++ fun intent(ctx: Context, action: String, trigger: String = "manual") =+ Intent(ctx, RecorderService::class.java).setAction(action).putExtra(EXTRA_TRIGGER, trigger)++ /** Re-check the schedule if the service is up (e.g. after a schedule refresh). Never starts it. */+ fun poke(ctx: Context) {+ if (AppState.mode(ctx) == Mode.AUTO) runCatching { ctx.startService(intent(ctx, ACTION_EVAL)) }+ }+ }++ private val main = Handler(Looper.getMainLooper())+ private var inForeground = false+ private var wakeLock: PowerManager.WakeLock? = null+ private var thread: Thread? = null+ private var sensorManager: SensorManager? = null++ // Shared with the audio thread.+ @Volatile private var listenAllowed = false+ @Volatile private var gateTrigger = "auto"+ @Volatile private var manualStartRequested = false+ @Volatile private var stopRequested = false+ @Volatile private var shutdown = false+ @Volatile private var worn = true++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ val auto = AppState.mode(this) == Mode.AUTO+ when (intent?.action) {+ ACTION_TOGGLE -> if (AppState.recording.value) userStop() else userStart()+ ACTION_START -> if (!AppState.recording.value) userStart()+ ACTION_STOP -> if (AppState.recording.value) userStop() else if (!auto) quit()+ ACTION_AUTO_ON -> { AppState.prefs(this).edit().remove("auto_paused_until").apply(); refreshScheduleThenEval() }+ ACTION_AUTO_OFF -> { listenAllowed = false; cancelAlarm(); unregisterSensor(); if (!AppState.recording.value) quit() }+ ACTION_EVAL -> refreshScheduleThenEval()+ else -> if (auto) refreshScheduleThenEval() else if (!AppState.recording.value) quit()+ }+ return if (auto) START_STICKY else START_NOT_STICKY+ }++ // ---- user actions -----------------------------------------------------------++ private fun userStart() {+ if (!goForeground()) return+ AppState.prefs(this).edit().remove("auto_paused_until").apply()+ stopRequested = false+ manualStartRequested = true+ ensureThread()+ }++ private fun userStop() {+ if (AppState.mode(this) == Mode.AUTO) {+ // A manual stop in auto mode means "not now": stay quiet until this window/meeting ends.+ AppState.prefs(this).edit().putLong("auto_paused_until", Schedule.pauseUntil(this)).apply()+ }+ stopRequested = true+ evaluate()+ }++ // ---- gate ---------------------------------------------------------------------++ private fun refreshScheduleThenEval() {+ if (!goForeground()) return+ registerSensor()+ evaluate() // act on the cached schedule right away+ Thread({ if (Schedule.fetch(this)) main.post { evaluate() } }, "schedule").start()+ }++ private fun evaluate() {+ val auto = AppState.mode(this) == Mode.AUTO+ if (!auto) {+ listenAllowed = false+ AppState.autoStatus.value = null+ if (!AppState.recording.value && thread == null) quit()+ return+ }+ val g = Schedule.gate(this)+ gateTrigger = g.trigger+ listenAllowed = g.open && worn+ AppState.autoStatus.value = when {+ !worn -> "Auto: not on wrist"+ g.open -> "Auto: listening (${g.reason})"+ else -> "Auto: ${g.reason}"+ }+ // Mic closed: wake at the next boundary, and at least every 15 min to pick up setting /+ // calendar changes. (Mic open: the audio loop polls every 2 min.)+ setAlarm(minOf(g.nextChangeMs, System.currentTimeMillis() + 15 * 60_000L))+ if (listenAllowed) ensureThread()+ updateNotification()+ RecComplicationService.refresh(this)+ }++ // ---- foreground / notification -----------------------------------------------------++ private fun goForeground(): Boolean {+ if (inForeground) return true+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {+ Log.w(TAG, "no RECORD_AUDIO permission"); stopSelf(); return false+ }+ return try {+ startForeground(NOTIF_ID, notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)+ inForeground = true+ true+ } catch (e: Exception) {+ // Started from the background (boot, app update, killed service): Android refuses a+ // microphone service. Ask the wearer to tap, which opens the app and restarts it legally.+ Log.w(TAG, "cannot start microphone service from background: ${e.message}")+ Notifications.resumeAuto(this)+ stopSelf()+ false+ }+ }++ private fun quit() {+ listenAllowed = false+ shutdown = true+ cancelAlarm()+ unregisterSensor()+ AppState.autoStatus.value = null+ if (inForeground) stopForeground(STOP_FOREGROUND_REMOVE)+ inForeground = false+ stopSelf()+ }++ private fun updateNotification() {+ if (inForeground) getSystemService(NotificationManager::class.java).notify(NOTIF_ID, notification())+ }++ private fun notification(): Notification {+ val nm = getSystemService(NotificationManager::class.java)+ nm.createNotificationChannel(NotificationChannel(CHANNEL, "Recording", NotificationManager.IMPORTANCE_LOW))+ val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ val stop = PendingIntent.getService(this, 1, intent(this, ACTION_STOP),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ val rec = AppState.recording.value+ val title = if (rec) "Recording" else AppState.autoStatus.value ?: "Voice Capture"+ val b = NotificationCompat.Builder(this, CHANNEL)+ .setSmallIcon(if (rec) R.drawable.ic_rec else R.drawable.ic_mic)+ .setContentTitle(title)+ .setContentText("Tap to open")+ .setOngoing(true)+ .setOnlyAlertOnce(true)+ .setCategory(NotificationCompat.CATEGORY_STOPWATCH)+ .setContentIntent(open)+ if (rec) b.addAction(R.drawable.ic_mic, "Stop", stop)+ // Ongoing Activity: shows an icon on the watch face and in recents while we run.+ val status = if (rec) Status.Builder().addTemplate("Recording #time#")+ .addPart("time", Status.StopwatchPart(SystemClock.elapsedRealtime())).build()+ else Status.Builder().addTemplate(title).build()+ OngoingActivity.Builder(this, NOTIF_ID, b)+ .setStaticIcon(if (rec) R.drawable.ic_rec else R.drawable.ic_mic)+ .setTouchIntent(open)+ .setStatus(status)+ .build()+ .apply(this)+ return b.build()+ }++ // ---- alarms --------------------------------------------------------------------++ private fun alarmIntent() = PendingIntent.getForegroundService(this, 7, intent(this, ACTION_EVAL),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)++ private fun setAlarm(atMs: Long) {+ val am = getSystemService(AlarmManager::class.java)+ val at = maxOf(atMs + 1000, System.currentTimeMillis() + 15_000)+ if (am.canScheduleExactAlarms()) am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, alarmIntent())+ else am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, alarmIntent())+ }++ private fun cancelAlarm() = getSystemService(AlarmManager::class.java).cancel(alarmIntent())++ // ---- on-wrist sensor -------------------------------------------------------------++ private fun registerSensor() {+ if (sensorManager != null) return+ val sm = getSystemService(SensorManager::class.java) ?: return+ val s = sm.getDefaultSensor(Sensor.TYPE_LOW_LATENCY_OFFBODY_DETECT, true) ?: run {+ Log.i(TAG, "no off-body sensor: treating the watch as always worn"); return+ }+ sensorManager = sm+ sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL)+ }++ private fun unregisterSensor() {+ sensorManager?.unregisterListener(this)+ sensorManager = null+ }++ override fun onSensorChanged(event: SensorEvent) {+ val nowWorn = event.values.firstOrNull() == 1f+ if (nowWorn != worn) {+ worn = nowWorn+ Log.i(TAG, "on wrist: $worn")+ main.post { evaluate() }+ }+ }++ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}++ // ---- audio thread ------------------------------------------------------------------++ private fun ensureThread() {+ if (thread?.isAlive == true) return+ shutdown = false+ wakeLock = (getSystemService(POWER_SERVICE) as PowerManager)+ .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VoiceCapture:mic").apply { acquire(14 * 60 * 60 * 1000L) }+ thread = Thread({ audioLoop() }, "audio").apply { start() }+ }++ /** Called on the main thread once the audio thread has exited. */+ private fun audioThreadDone() {+ thread = null+ wakeLock?.let { if (it.isHeld) it.release() }+ wakeLock = null+ if (AppState.mode(this) != Mode.AUTO) quit()+ else { evaluate(); if (listenAllowed) ensureThread() }+ }++ private inner class Session(val trigger: String, startedAt: OffsetDateTime) {+ val recId = UUID.randomUUID().toString().replace("-", "").take(20)+ val startedAt: OffsetDateTime = startedAt.truncatedTo(ChronoUnit.SECONDS)+ val manual = trigger == "manual"+ private val chunkSamples = ChunkWriter.SAMPLE_RATE.toLong() * CHUNK_SECONDS+ private var idx = 0+ private var chunkStart = this.startedAt+ private var writer: ChunkWriter = newWriter()+ // A finished chunk is committed only once the next one has audio, so the final chunk can+ // always carry is_last=true even when the stop lands right on a boundary.+ private var held: Pair<ChunkWriter, JSONObject>? = null+ private val bytes = ByteArray(Vad.FRAME * 2)+ private val deviceId = ServerConfig.load(this@RecorderService)?.deviceId ?: "galaxy-watch"++ private fun newWriter() = ChunkWriter.create(File(Outbox.dir(this@RecorderService), "${recId}__${"%05d".format(idx)}"))++ private fun meta(i: Int, w: ChunkWriter, start: OffsetDateTime) = JSONObject().apply {+ put("recording_id", recId); put("idx", i); put("is_last", false)+ put("started_at", startedAt.toString()); put("chunk_started_at", start.toString())+ put("duration_s", w.durationS); put("trigger", trigger); put("device_id", deviceId)+ }++ fun write(frame: ShortArray, n: Int) {+ for (i in 0 until n) { bytes[2 * i] = (frame[i].toInt() and 0xff).toByte(); bytes[2 * i + 1] = (frame[i].toInt() shr 8).toByte() }+ writer.write(bytes, n * 2)+ held?.let { (hw, hm) ->+ Outbox.commit(hw.file, hm); held = null+ AppState.pendingChunks.value = Outbox.count(this@RecorderService)+ Uploader.kick(this@RecorderService)+ }+ if (writer.samplesWritten >= chunkSamples) {+ if (writer.finish()) held = writer to meta(idx, writer, chunkStart)+ idx += 1+ chunkStart = OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)+ writer = newWriter()+ }+ }++ fun finish() {+ val w = writer+ if (w.samplesWritten > 0 && w.finish()) {+ held?.let { (hw, hm) -> Outbox.commit(hw.file, hm) }+ Outbox.commit(w.file, meta(idx, w, chunkStart).put("is_last", true))+ } else {+ w.finish()+ held?.let { (hw, hm) -> Outbox.commit(hw.file, hm.put("is_last", true)) }+ }+ AppState.pendingChunks.value = Outbox.count(this@RecorderService)+ }+ }++ @SuppressLint("MissingPermission")+ private fun audioLoop() {+ val rate = ChunkWriter.SAMPLE_RATE+ val minBuf = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)+ val rec = AudioRecord(MediaRecorder.AudioSource.MIC, rate, AudioFormat.CHANNEL_IN_MONO,+ AudioFormat.ENCODING_PCM_16BIT, maxOf(minBuf * 4, rate))+ val vad = runCatching { Vad(this) }.onFailure { Log.e(TAG, "VAD load failed", it) }.getOrNull()+ val preroll = ArrayDeque<ShortArray>()+ val recent = BooleanArray(START_WINDOW)+ var recentPos = 0+ var recentCount = 0+ var speechRun = 0+ var quietFrames = 0+ var session: Session? = null+ var lastSpeechMs = 0L+ var silenceLimitMs = Long.MAX_VALUE+ // While the mic is open the CPU is awake anyway: check the PC for setting changes every+ // 2 min so dashboard edits reach the watch almost right away.+ var lastFetchMs = SystemClock.elapsedRealtime()+ val fetching = java.util.concurrent.atomic.AtomicBoolean(false)++ fun startSession(trigger: String) {+ val prerollMs = preroll.size * Vad.FRAME * 1000L / rate+ val s = Session(trigger, OffsetDateTime.now().minusNanos(prerollMs * 1_000_000))+ preroll.forEach { s.write(it, it.size) }+ preroll.clear()+ session = s+ lastSpeechMs = SystemClock.elapsedRealtime()+ val mins = Schedule.silenceMinutes(this, s.manual)+ silenceLimitMs = if (mins <= 0) Long.MAX_VALUE else mins * 60_000L+ Log.i(TAG, "recording ${s.recId} ($trigger, silence stop ${mins} min, preroll ${prerollMs} ms)")+ main.post {+ AppState.recording.value = true+ AppState.recordingSince.value = System.currentTimeMillis() - prerollMs+ buzz(start = true)+ updateNotification()+ RecComplicationService.refresh(this)+ }+ }++ fun endSession(why: String) {+ val s = session ?: return+ s.finish()+ session = null+ Log.i(TAG, "recording ${s.recId} ended: $why")+ main.post {+ AppState.recording.value = false+ AppState.recordingSince.value = null+ buzz(start = false)+ Uploader.kick(this)+ updateNotification()+ RecComplicationService.refresh(this)+ }+ }++ try {+ rec.startRecording()+ if (rec.recordingState != AudioRecord.RECORDSTATE_RECORDING) throw IllegalStateException("mic busy")+ main.post { AppState.listening.value = true; RecComplicationService.refresh(this) }+ while (true) {+ if (manualStartRequested) {+ manualStartRequested = false+ if (session != null && session!!.manual.not()) {+ // Button pressed while auto was already recording: keep going, it's now a manual one.+ silenceLimitMs = Schedule.silenceMinutes(this, true).let { if (it <= 0) Long.MAX_VALUE else it * 60_000L }+ } else if (session == null) startSession("manual")+ }+ if (stopRequested) {+ stopRequested = false+ endSession("stopped by button")+ }+ if (session == null && (!listenAllowed || shutdown)) break++ val frame = ShortArray(Vad.FRAME)+ var got = 0+ while (got < Vad.FRAME) {+ val n = rec.read(frame, got, Vad.FRAME - got)+ if (n < 0) throw IllegalStateException("AudioRecord read error $n")+ got += n+ }++ if (SystemClock.elapsedRealtime() - lastFetchMs >= 120_000 && fetching.compareAndSet(false, true)) {+ lastFetchMs = SystemClock.elapsedRealtime()+ Thread({+ try { if (Schedule.fetch(this)) main.post { evaluate() } } finally { fetching.set(false) }+ }, "schedule").start()+ }++ // Speech probability; the model only runs when there is some sound.+ val level = rms(frame, got)+ val p = if (vad != null && level >= RMS_FLOOR) { quietFrames = 0; vad.prob(frame) }+ else { if (++quietFrames == 30) vad?.reset(); 0f }+ val speech = p >= SPEECH_P+ speechRun = if (speech) speechRun + 1 else 0++ val s = session+ if (s != null) {+ s.write(frame, got)+ val now = SystemClock.elapsedRealtime()+ if (speechRun >= 3) lastSpeechMs = now+ if (now - lastSpeechMs >= silenceLimitMs) endSession("silence")+ } else {+ // Listening: keep ~2 s of pre-roll and look for sustained speech.+ preroll.addLast(frame)+ if (preroll.size > PREROLL_FRAMES) preroll.removeFirst()+ if (recent[recentPos]) recentCount--+ recent[recentPos] = speech+ if (speech) recentCount+++ recentPos = (recentPos + 1) % START_WINDOW+ if (recentCount >= START_SPEECH_FRAMES && listenAllowed) {+ recent.fill(false); recentCount = 0+ startSession(gateTrigger)+ }+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "audio loop stopped: ${e.message}", e)+ } finally {+ runCatching { endSession("audio loop exit") }+ runCatching { rec.stop() }+ rec.release()+ vad?.close()+ main.post {+ AppState.listening.value = false+ RecComplicationService.refresh(this)+ audioThreadDone()+ }+ }+ }++ private fun buzz(start: Boolean) {+ val v = getSystemService(Vibrator::class.java) ?: return+ val effect = if (start) VibrationEffect.createWaveform(longArrayOf(0, 60, 80, 60), -1)+ else VibrationEffect.createOneShot(250, VibrationEffect.DEFAULT_AMPLITUDE)+ v.vibrate(effect)+ }++ override fun onDestroy() {+ shutdown = true+ listenAllowed = false+ unregisterSensor()+ super.onDestroy()+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/Schedule.kt b/watch/app/src/main/java/com/leveledai/voicecapture/Schedule.ktnew file mode 100644index 0000000..278ccf3--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/Schedule.kt@@ -0,0 +1,129 @@+package com.leveledai.voicecapture++import android.content.Context+import android.util.Log+import okhttp3.OkHttpClient+import okhttp3.Request+import org.json.JSONObject+import java.time.LocalDate+import java.time.LocalTime+import java.time.OffsetDateTime+import java.time.ZoneId+import java.time.ZonedDateTime+import java.util.concurrent.TimeUnit++/**+ * Auto-mode schedule. The PC is the source of truth (dashboard Settings + Google Calendar); the+ * watch caches the last `/api/v1/schedule` reply so auto mode keeps working offline.+ */+object Schedule {+ private const val TAG = "VoiceSchedule"+ private val http = OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build()+ private val DAYS = arrayOf("mon", "tue", "wed", "thu", "fri", "sat", "sun")++ /** Is auto listening allowed right now, why, and when does that answer next change. */+ data class Gate(val open: Boolean, val trigger: String, val reason: String, val nextChangeMs: Long)++ fun cached(ctx: Context): JSONObject? =+ AppState.prefs(ctx).getString("schedule_json", null)?.let { runCatching { JSONObject(it) }.getOrNull() }++ /** Blocking network call: never on the main thread. Returns true when a fresh schedule was stored. */+ fun fetch(ctx: Context): Boolean {+ val cfg = ServerConfig.load(ctx) ?: return false+ val req = Request.Builder().url("${cfg.serverUrl}/api/v1/schedule")+ .header("Authorization", "Bearer ${cfg.ingestToken}")+ .apply {+ cfg.cfClientId?.let { header("CF-Access-Client-Id", it) }+ cfg.cfClientSecret?.let { header("CF-Access-Client-Secret", it) }+ }.build()+ return try {+ http.newCall(req).execute().use { r ->+ val body = r.body?.string().orEmpty()+ if (r.code != 200) { Log.w(TAG, "schedule HTTP ${r.code}"); return false }+ JSONObject(body) // validate before storing+ AppState.prefs(ctx).edit().putString("schedule_json", body)+ .putLong("schedule_at", System.currentTimeMillis()).apply()+ true+ }+ } catch (e: Exception) {+ Log.w(TAG, "schedule fetch failed: ${e.message}")+ false+ }+ }++ fun silenceMinutes(ctx: Context, manual: Boolean): Int {+ val s = cached(ctx)?.optJSONObject("silence")+ return if (manual) s?.optInt("manual_stop_min", 10) ?: 10 else maxOf(1, s?.optInt("auto_end_min", 2) ?: 2)+ }++ fun gate(ctx: Context, now: ZonedDateTime = ZonedDateTime.now()): Gate {+ val nowMs = now.toInstant().toEpochMilli()+ val pausedUntil = AppState.prefs(ctx).getLong("auto_paused_until", 0L)+ val sched = cached(ctx) ?: return Gate(false, "auto", "waiting for schedule", nowMs + 10 * 60_000)+ val auto = sched.optJSONObject("auto") ?: JSONObject()+ val boundaries = mutableListOf<Long>()+ var open: Pair<String, String>? = null // trigger to reason++ // Weekly windows, local watch time; today and tomorrow give every boundary in the next 24 h.+ // Windows are optional: with none set on any day, auto mode listens whenever the watch is worn.+ val windows = auto.optJSONObject("windows")+ val anyWindow = DAYS.any { (windows?.optJSONArray(it)?.length() ?: 0) > 0 }+ if (auto.optBoolean("always_while_worn", false) || !anyWindow) open = "auto" to "whenever worn"++ for (dayOffset in 0..1) {+ val date: LocalDate = now.toLocalDate().plusDays(dayOffset.toLong())+ val list = windows?.optJSONArray(DAYS[date.dayOfWeek.value - 1]) ?: continue+ for (i in 0 until list.length()) {+ val w = list.optJSONArray(i) ?: continue+ val start = runCatching { ZonedDateTime.of(date, LocalTime.parse(w.getString(0)), now.zone) }.getOrNull() ?: continue+ val end = runCatching { ZonedDateTime.of(date, LocalTime.parse(w.getString(1)), now.zone) }.getOrNull() ?: continue+ boundaries += start.toInstant().toEpochMilli(); boundaries += end.toInstant().toEpochMilli()+ if (!now.isBefore(start) && now.isBefore(end) && open == null) open = "auto" to "window until ${clock(w.getString(1))}"+ }+ }++ // Calendar meetings (the PC already dropped all-day, declined and solo events).+ val cal = auto.optJSONObject("calendar")+ if (cal?.optBoolean("enabled", true) != false) {+ val lead = (cal?.optInt("lead_min", 2) ?: 2).toLong()+ val meetings = sched.optJSONArray("meetings")+ for (i in 0 until (meetings?.length() ?: 0)) {+ val m = meetings!!.optJSONObject(i) ?: continue+ val s = runCatching { OffsetDateTime.parse(m.getString("start")).minusMinutes(lead) }.getOrNull() ?: continue+ val e = runCatching { OffsetDateTime.parse(m.getString("end")) }.getOrNull() ?: continue+ boundaries += s.toInstant().toEpochMilli(); boundaries += e.toInstant().toEpochMilli()+ val n = now.toOffsetDateTime()+ if (!n.isBefore(s) && n.isBefore(e)) {+ val until = hhmm(e.toInstant().toEpochMilli())+ open = "calendar" to "meeting until $until" // a meeting wins: it labels the recording+ }+ }+ }++ val upcoming = boundaries.filter { it > nowMs }.minOrNull()+ val next = upcoming ?: (nowMs + 6 * 60 * 60_000L) // nothing scheduled: just re-check later+ if (pausedUntil > nowMs && open != null) {+ return Gate(false, open.first, "paused", minOf(next, pausedUntil))+ }+ return if (open != null) Gate(true, open.first, open.second, next)+ else Gate(false, "auto", if (upcoming == null) "off, no window or meeting today" else "off until ${hhmm(next)}", next)+ }++ /** End of the current auto period, used to pause auto mode after a manual stop. */+ fun pauseUntil(ctx: Context): Long {+ val g = gate(ctx.also { AppState.prefs(it).edit().remove("auto_paused_until").apply() })+ val now = System.currentTimeMillis()+ val a = cached(ctx)?.optJSONObject("auto")+ val noWindows = DAYS.none { (a?.optJSONObject("windows")?.optJSONArray(it)?.length() ?: 0) > 0 }+ val alwaysOn = a?.optBoolean("always_while_worn", false) == true || noWindows+ return if (alwaysOn) now + 60 * 60_000L else minOf(g.nextChangeMs, now + 4 * 60 * 60_000L)+ }++ private val CLOCK = java.time.format.DateTimeFormatter.ofPattern("h:mm a", java.util.Locale.US)++ fun hhmm(ms: Long): String =+ java.time.Instant.ofEpochMilli(ms).atZone(ZoneId.systemDefault()).format(CLOCK)++ private fun clock(hhmm24: String): String =+ runCatching { LocalTime.parse(hhmm24).format(CLOCK) }.getOrDefault(hhmm24)+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/ToggleActivity.kt b/watch/app/src/main/java/com/leveledai/voicecapture/ToggleActivity.ktnew file mode 100644index 0000000..79f5933--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/ToggleActivity.kt@@ -0,0 +1,24 @@+package com.leveledai.voicecapture++import android.Manifest+import android.app.Activity+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Bundle++/**+ * Invisible: flips recording on/off and closes. Launched by the complication tap and by the+ * "Rec toggle" launcher entry (assign it to the Home key double press). Being a visible+ * activity at that instant is what lets a microphone foreground service start on Android 14+.+ */+class ToggleActivity : Activity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {+ startActivity(Intent(this, MainActivity::class.java)) // main screen asks for the permission+ } else {+ startForegroundService(RecorderService.intent(this, RecorderService.ACTION_TOGGLE))+ }+ finish()+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/Uploader.kt b/watch/app/src/main/java/com/leveledai/voicecapture/Uploader.ktnew file mode 100644index 0000000..e06d5f5--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/Uploader.kt@@ -0,0 +1,133 @@+package com.leveledai.voicecapture++import android.content.Context+import androidx.work.BackoffPolicy+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.MultipartBody+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.RequestBody.Companion.asRequestBody+import org.json.JSONObject+import java.io.IOException+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import java.util.concurrent.TimeUnit++/**+ * Uploads finished chunks whenever any network is up: Wear OS routes through the phone over+ * Bluetooth when it's near, or Wi-Fi when it isn't. Battery saver = wait for unmetered (Wi-Fi).+ * A file is deleted only after the server answers 200 with the same SHA-256.+ */+object Uploader {+ private const val NOW = "upload-now"+ private const val PERIODIC = "upload-periodic"++ private fun constraints(ctx: Context) = Constraints.Builder()+ .setRequiredNetworkType(+ if (AppState.prefs(ctx).getBoolean("battery_saver", false)) NetworkType.UNMETERED else NetworkType.CONNECTED)+ .build()++ fun kick(ctx: Context) {+ val req = OneTimeWorkRequestBuilder<UploadWorker>()+ .setConstraints(constraints(ctx))+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)+ .build()+ WorkManager.getInstance(ctx).enqueueUniqueWork(NOW, ExistingWorkPolicy.REPLACE, req) // fresh kick skips any retry backoff; server dedupes by sha+ }++ /** Safety net: every 15 minutes (WorkManager's minimum), in case a kick was lost. */+ fun schedulePeriodic(ctx: Context) {+ val req = PeriodicWorkRequestBuilder<UploadWorker>(15, TimeUnit.MINUTES)+ .setConstraints(constraints(ctx)).build()+ WorkManager.getInstance(ctx).enqueueUniquePeriodicWork(PERIODIC, ExistingPeriodicWorkPolicy.UPDATE, req)+ }+}++class UploadWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {++ private val http = OkHttpClient.Builder()+ .connectTimeout(20, TimeUnit.SECONDS)+ .writeTimeout(120, TimeUnit.SECONDS)+ .readTimeout(60, TimeUnit.SECONDS)+ .build()++ private fun stamp() = SimpleDateFormat("HH:mm", Locale.US).format(Date())++ override suspend fun doWork(): Result = withContext(Dispatchers.IO) {+ val ctx = applicationContext+ val cfg = ServerConfig.load(ctx) ?: run {+ AppState.setLastUpload(ctx, "Not set up (no server config)")+ return@withContext Result.failure()+ }+ var sent = 0+ for (item in Outbox.pending(ctx)) {+ val m = item.meta+ val type = if (item.audio.extension == "ogg") "audio/ogg" else "audio/mp4"+ val body = MultipartBody.Builder().setType(MultipartBody.FORM)+ .addFormDataPart("file", item.audio.name, item.audio.asRequestBody(type.toMediaType()))+ .apply {+ for (k in listOf("recording_id", "idx", "is_last", "started_at", "chunk_started_at",+ "duration_s", "trigger", "device_id", "sha256")) {+ if (m.has(k)) addFormDataPart(k, m.get(k).toString())+ }+ }.build()+ val req = Request.Builder().url("${cfg.serverUrl}/api/v1/chunks").post(body)+ .header("Authorization", "Bearer ${cfg.ingestToken}")+ .apply {+ cfg.cfClientId?.let { header("CF-Access-Client-Id", it) }+ cfg.cfClientSecret?.let { header("CF-Access-Client-Secret", it) }+ }.build()+ try {+ http.newCall(req).execute().use { resp ->+ val text = resp.body?.string().orEmpty()+ when (resp.code) {+ 200 -> {+ val got = runCatching { JSONObject(text).optString("sha256") }.getOrDefault("")+ if (got.equals(m.getString("sha256"), ignoreCase = true)) {+ Outbox.remove(item); sent += 1+ } else {+ AppState.setLastUpload(ctx, "${stamp()} server checksum differs, will retry")+ return@withContext Result.retry()+ }+ }+ 400 -> return@withContext Result.retry() // checksum mismatch in transit+ 401, 403 -> {+ AppState.setLastUpload(ctx, "${stamp()} rejected: check tokens (${resp.code})")+ return@withContext Result.failure()+ }+ 409 -> AppState.setLastUpload(ctx, "${stamp()} conflict on ${item.audio.name}, kept")+ else -> {+ AppState.setLastUpload(ctx, "${stamp()} server error ${resp.code}, will retry")+ return@withContext Result.retry()+ }+ }+ }+ } catch (e: IOException) {+ android.util.Log.w("VoiceUpload", "upload failed: ${e.message}")+ AppState.setLastUpload(ctx, "${stamp()} offline, will retry")+ AppState.pendingChunks.value = Outbox.count(ctx)+ return@withContext Result.retry()+ }+ AppState.pendingChunks.value = Outbox.count(ctx)+ }+ if (sent > 0) AppState.setLastUpload(ctx, "${stamp()} sent $sent chunk${if (sent == 1) "" else "s"}")+ // Piggyback: keep the auto-mode schedule (windows + calendar) fresh while we're online.+ if (AppState.mode(ctx) == Mode.AUTO &&+ System.currentTimeMillis() - AppState.prefs(ctx).getLong("schedule_at", 0) > 10 * 60_000L &&+ Schedule.fetch(ctx)) RecorderService.poke(ctx)+ AppState.pendingChunks.value = Outbox.count(ctx)+ Result.success()+ }+}diff --git a/watch/app/src/main/java/com/leveledai/voicecapture/Vad.kt b/watch/app/src/main/java/com/leveledai/voicecapture/Vad.ktnew file mode 100644index 0000000..2b5f710--- /dev/null+++ b/watch/app/src/main/java/com/leveledai/voicecapture/Vad.kt@@ -0,0 +1,80 @@+package com.leveledai.voicecapture++import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession+import android.content.Context+import java.nio.FloatBuffer+import kotlin.math.sqrt++/**+ * Silero VAD v5 (ONNX, ~2 MB, assets/silero_vad.onnx) on 32 ms frames of 16 kHz audio.+ * The model wants each 512-sample frame prefixed with the previous frame's last 64 samples,+ * plus its recurrent state carried between calls. Interface checked against the real model:+ * inputs input[1,576] float, state[2,1,128] float, sr int64 scalar; outputs output[1,1], stateN.+ */+class Vad(ctx: Context) : AutoCloseable {+ companion object {+ const val FRAME = 512+ private const val CONTEXT = 64+ }++ private val env = OrtEnvironment.getEnvironment()+ // Load from a file path, not a byte array: on the watch's 32-bit ARM, parsing from a Java+ // byte[] hits an unaligned read in ORT and dies with SIGBUS (BUS_ADRALN).+ private val session: OrtSession = env.createSession(modelFile(ctx).absolutePath,+ OrtSession.SessionOptions().apply {+ setIntraOpNumThreads(1); setInterOpNumThreads(1)+ setOptimizationLevel(OrtSession.SessionOptions.OptLevel.NO_OPT)+ })++ private fun modelFile(ctx: Context): java.io.File {+ val f = java.io.File(ctx.noBackupFilesDir, "silero_vad.onnx")+ val size = ctx.assets.openFd("silero_vad.onnx").use { it.length }+ if (!f.exists() || f.length() != size) {+ ctx.assets.open("silero_vad.onnx").use { i -> f.outputStream().use { o -> i.copyTo(o) } }+ }+ return f+ }+ private val sr = OnnxTensor.createTensor(env, 16000L)+ private var state = FloatArray(2 * 128)+ private val context = FloatArray(CONTEXT)+ private val input = FloatArray(CONTEXT + FRAME)++ fun reset() {+ state.fill(0f)+ context.fill(0f)+ }++ /** Speech probability 0..1 for one FRAME-sample frame. */+ fun prob(frame: ShortArray): Float {+ System.arraycopy(context, 0, input, 0, CONTEXT)+ for (i in 0 until FRAME) input[CONTEXT + i] = frame[i] / 32768f+ System.arraycopy(input, FRAME, context, 0, CONTEXT) // last 64 samples become next context+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, (CONTEXT + FRAME).toLong())).use { inT ->+ OnnxTensor.createTensor(env, FloatBuffer.wrap(state), longArrayOf(2, 1, 128)).use { stT ->+ session.run(mapOf("input" to inT, "state" to stT, "sr" to sr)).use { r ->+ @Suppress("UNCHECKED_CAST")+ val p = (r[0].value as Array<FloatArray>)[0][0]+ @Suppress("UNCHECKED_CAST")+ val sn = r[1].value as Array<Array<FloatArray>>+ var k = 0+ for (a in sn) for (b in a) for (v in b) state[k++] = v+ return p+ }+ }+ }+ }++ override fun close() {+ runCatching { sr.close() }+ runCatching { session.close() }+ }+}++/** Root-mean-square level of a frame, 0..1. Cheap gate so the model only runs when there's sound. */+fun rms(frame: ShortArray, n: Int): Float {+ var acc = 0.0+ for (i in 0 until n) { val v = frame[i] / 32768.0; acc += v * v }+ return sqrt(acc / maxOf(1, n)).toFloat()+}diff --git a/watch/app/src/main/res/drawable/ic_launcher.xml b/watch/app/src/main/res/drawable/ic_launcher.xmlnew file mode 100644index 0000000..afc3b5b--- /dev/null+++ b/watch/app/src/main/res/drawable/ic_launcher.xml@@ -0,0 +1,17 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">+ <!-- Robot holding a mic, on brand blue. Navy = eyes/mouth. -->+ <path android:fillColor="#FF2563EB" android:pathData="M24,24m-24,0a24,24 0,1 1,48 0a24,24 0,1 1,-48 0" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M19,8.5m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M18.2,9h1.6v5h-1.6z" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M13,14h12a4,4 0,0 1,4 4v8a4,4 0,0 1,-4 4h-12a4,4 0,0 1,-4 -4v-8a4,4 0,0 1,4 -4z" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M8,19a1,1 0,0 1,1 1v4a1,1 0,0 1,-2 0v-4a1,1 0,0 1,1 -1zM30,19a1,1 0,0 1,1 1v4a1,1 0,0 1,-2 0v-4a1,1 0,0 1,1 -1z" />+ <path android:fillColor="#FF1E3A8A" android:pathData="M15,21m-2.2,0a2.2,2.2 0,1 1,4.4 0a2.2,2.2 0,1 1,-4.4 0M23,21m-2.2,0a2.2,2.2 0,1 1,4.4 0a2.2,2.2 0,1 1,-4.4 0" />+ <path android:fillColor="#FF1E3A8A" android:pathData="M15.8,25.5h6.4a0.8,0.8 0,0 1,0 1.6h-6.4a0.8,0.8 0,0 1,0 -1.6z" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M16,30h6v3h-6z" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M12,33h14a3,3 0,0 1,3 3v4h-20v-4a3,3 0,0 1,3 -3z" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M37,15a3,3 0,0 1,3 3v6a3,3 0,0 1,-6 0v-6a3,3 0,0 1,3 -3z" />+ <path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.6" android:pathData="M32.5,23.5a4.5,4.5 0,0 0,9 0" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M36.2,28h1.6v4h-1.6zM34.8,32h4.4a0.8,0.8 0,0 1,0 1.6h-4.4a0.8,0.8 0,0 1,0 -1.6z" />+ <path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="2.2" android:strokeLineCap="round" android:pathData="M27,36L35,32.8" />+</vector>diff --git a/watch/app/src/main/res/drawable/ic_mic.xml b/watch/app/src/main/res/drawable/ic_mic.xmlnew file mode 100644index 0000000..5a40f73--- /dev/null+++ b/watch/app/src/main/res/drawable/ic_mic.xml@@ -0,0 +1,5 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:fillColor="#FFFFFFFF"+ android:pathData="M12,14c1.66,0 3,-1.34 3,-3V5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11H5c0,3.41 2.72,6.23 6,6.72V21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />+</vector>diff --git a/watch/app/src/main/res/drawable/ic_rec.xml b/watch/app/src/main/res/drawable/ic_rec.xmlnew file mode 100644index 0000000..5d01e4b--- /dev/null+++ b/watch/app/src/main/res/drawable/ic_rec.xml@@ -0,0 +1,5 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:fillColor="#FF1E3A8A"+ android:pathData="M12,12m-8,0a8,8 0,1 1,16 0a8,8 0,1 1,-16 0" />+</vector>diff --git a/watch/app/src/main/res/drawable/ic_toggle.xml b/watch/app/src/main/res/drawable/ic_toggle.xmlnew file mode 100644index 0000000..fa13445--- /dev/null+++ b/watch/app/src/main/res/drawable/ic_toggle.xml@@ -0,0 +1,8 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">+ <!-- Quick Rec: navy disc, white ring, white dot (a record symbol, no mic, so it can't be confused with the app) -->+ <path android:fillColor="#FF1E3A8A" android:pathData="M24,24m-24,0a24,24 0,1 1,48 0a24,24 0,1 1,-48 0" />+ <path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="3"+ android:pathData="M24,24m-13,0a13,13 0,1 1,26 0a13,13 0,1 1,-26 0" />+ <path android:fillColor="#FFFFFFFF" android:pathData="M24,24m-7,0a7,7 0,1 1,14 0a7,7 0,1 1,-14 0" />+</vector>diff --git a/watch/app/src/main/res/values/strings.xml b/watch/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000..466ce70--- /dev/null+++ b/watch/app/src/main/res/values/strings.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Voice Capture</string>+ <string name="toggle_name">Quick Rec</string>+ <string name="complication_name">Voice Capture</string>+</resources>diff --git a/watch/app/src/main/res/xml/network_security_config.xml b/watch/app/src/main/res/xml/network_security_config.xmlnew file mode 100644index 0000000..65fd2b6--- /dev/null+++ b/watch/app/src/main/res/xml/network_security_config.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Plain HTTP is allowed because Wi-Fi mode uploads to the PC's address on the home network+ (http://192.168.x.x:8808), and Android can't allow-list a whole private range here.+ Every upload still carries the bearer token. Tunnel mode uses HTTPS. -->+<network-security-config>+ <base-config cleartextTrafficPermitted="true" />+</network-security-config>diff --git a/watch/build.gradle.kts b/watch/build.gradle.ktsnew file mode 100644index 0000000..59354df--- /dev/null+++ b/watch/build.gradle.kts@@ -0,0 +1,5 @@+plugins {+ id("com.android.application") version "8.13.2" apply false+ id("org.jetbrains.kotlin.android") version "2.4.21" apply false+ id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false+}diff --git a/watch/gradle.properties b/watch/gradle.propertiesnew file mode 100644index 0000000..e696167--- /dev/null+++ b/watch/gradle.properties@@ -0,0 +1,3 @@+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8+android.useAndroidX=true+kotlin.code.style=officialdiff --git a/watch/gradle/wrapper/gradle-wrapper.jar b/watch/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 0000000..9bbc975Binary files /dev/null and b/watch/gradle/wrapper/gradle-wrapper.jar differdiff --git a/watch/gradle/wrapper/gradle-wrapper.properties b/watch/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..37f853b--- /dev/null+++ b/watch/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,7 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip+networkTimeout=10000+validateDistributionUrl=true+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/watch/gradlew b/watch/gradlewnew file mode 100644index 0000000..faf9300--- /dev/null+++ b/watch/gradlew@@ -0,0 +1,251 @@+#!/bin/sh++#+# Copyright © 2015-2021 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar+++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ if ! command -v java >/dev/null 2>&1+ then+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -classpath "$CLASSPATH" \+ org.gradle.wrapper.GradleWrapperMain \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/watch/gradlew.bat b/watch/gradlew.batnew file mode 100644index 0000000..9d21a21--- /dev/null+++ b/watch/gradlew.bat@@ -0,0 +1,94 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem+@rem SPDX-License-Identifier: Apache-2.0+@rem++@if "%DEBUG%"=="" @echo off+@rem ##########################################################################+@rem+@rem Gradle startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables with windows NT shell+if "%OS%"=="Windows_NT" setlocal++set DIRNAME=%~dp0+if "%DIRNAME%"=="" set DIRNAME=.+@rem This is normally unused+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if %ERRORLEVEL% equ 0 goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++echo. 1>&2+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2+echo. 1>&2+echo Please set the JAVA_HOME variable in your environment to match the 1>&2+echo location of your Java installation. 1>&2++goto fail++:execute+@rem Setup the command line++set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar+++@rem Execute Gradle+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*++:end+@rem End local scope for the variables with windows NT shell+if %ERRORLEVEL% equ 0 goto mainEnd++:fail+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of+rem the _cmd.exe /c_ return code!+set EXIT_CODE=%ERRORLEVEL%+if %EXIT_CODE% equ 0 set EXIT_CODE=1+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%+exit /b %EXIT_CODE%++:mainEnd+if "%OS%"=="Windows_NT" endlocal++:omegadiff --git a/watch/settings.gradle.kts b/watch/settings.gradle.ktsnew file mode 100644index 0000000..44f25f1--- /dev/null+++ b/watch/settings.gradle.kts@@ -0,0 +1,16 @@+pluginManagement {+ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}+dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ google()+ mavenCentral()+ }+}+rootProject.name = "voice-capture-watch"+include(":app")diff --git a/worker.py b/worker.pynew file mode 100644index 0000000..7fbd271--- /dev/null+++ b/worker.py@@ -0,0 +1,293 @@+"""Background worker: recordings -> transcripts -> summaries -> daily digests.++ .venv\\Scripts\\python.exe worker.py (launch.py starts it)++Loop, every few seconds:+ 1. heartbeat (the dashboard's health dot reads it)+ 2. enrollment jobs (voiceprints)+ 3. one ready recording: join chunks -> WhisperX -> speakers -> delete audio [GPU]+ 4. one transcribed recording: AI summary [the provider chosen in Settings > Summaries]+ 5. dirty days: daily digest [same provider]+ 6. drop GPU models after idle+"""++from __future__ import annotations++import json+import shutil+import time+import traceback+from datetime import datetime, timedelta, timezone+from pathlib import Path++import numpy as np++import config+import db+import stitch+import store+import summarize+import transcribe++TICK_S = 5+MAX_ATTEMPTS = 3+RESUMMARIZE_SETTLE_S = 60+++def log(msg: str) -> None:+ print(f"{datetime.now().strftime('%H:%M:%S')} {msg}", flush=True)+++# ---- stage helpers --------------------------------------------------------------++def ready_recordings(c) -> list:+ stale = (datetime.now(timezone.utc) - timedelta(minutes=config.tunables()["recording_stale_minutes"])).isoformat()+ rows = c.execute("""select r.*, (select count(*) from chunks k where k.recording_id=r.id) n+ from recordings r where r.status in ('receiving','waiting') order by r.started_at""").fetchall()+ out = []+ for r in rows:+ complete = r["last_idx"] is not None and r["n"] == r["last_idx"] + 1+ if r["n"] and (complete or r["updated_at"] < stale or r["status"] == "waiting"):+ out.append(r)+ return out+++def match_speakers(c, rec_id: str, speakers: dict[str, dict]) -> None:+ thr = config.tunables()["speaker_match_threshold"]+ known = [(s["id"], store.emb_load(s["embedding"])) for s in c.execute("select id, embedding from speakers")]+ known = [(i, e) for i, e in known if e is not None]+ taken: set[int] = set()+ letters = iter("ABCDEFGHIJKLMNOPQRSTUVWXYZ")+ c.execute("delete from recording_speakers where recording_id=?", (rec_id,))+ for label, info in sorted(speakers.items(), key=lambda kv: -kv[1]["speech_s"]):+ emb = info["embedding"]+ sid, best = None, -1.0+ if emb is not None and known:+ e = emb / (np.linalg.norm(emb) or 1.0)+ for kid, kemb in known:+ sim = float(np.dot(e, kemb))+ if sim > best and kid not in taken:+ sid, best = kid, sim+ if best < thr:+ sid = None+ if sid:+ taken.add(sid)+ if best >= thr + 0.1: # only confident matches sharpen the voiceprint+ store.fold_into_speaker(c, sid, store.emb_dump(emb))+ else:+ c.execute("update speakers set last_heard=? where id=?", (db.now_iso(), sid))+ c.execute("""insert into recording_speakers(recording_id, label, display, speaker_id, embedding, speech_s)+ values(?,?,?,?,?,?)""",+ (rec_id, label, f"Speaker {next(letters, 'X')}", sid,+ store.emb_dump(emb) if emb is not None else None, info["speech_s"]))+++def process_recording(c, eng: transcribe.Engine, r) -> None:+ rid = r["id"]+ c.execute("update recordings set status='transcribing', updated_at=? where id=?", (db.now_iso(), rid))+ chunks = c.execute("select path from chunks where recording_id=? order by idx", (rid,)).fetchall()+ paths = [Path(k["path"]) for k in chunks if k["path"] and Path(k["path"]).exists()]+ if not paths:+ raise RuntimeError("audio files are missing")+ wav = transcribe.to_wav(paths, config.AUDIO_DIR / rid / "joined.wav")+ t0 = time.time()+ res = eng.run(wav)+ log(f"{rid}: {res.duration_s / 60:.1f} min audio -> {len(res.segments)} segments, "+ f"{len(res.speakers)} speaker(s) in {time.time() - t0:.0f}s")+ words = sum(len(s["text"].split()) for s in res.segments)+ ended = r["ended_at"] or (datetime.fromisoformat(r["started_at"]) + timedelta(seconds=res.duration_s)).isoformat(timespec="seconds")+ with db.tx(c):+ c.execute("delete from segments where recording_id=?", (rid,))+ c.executemany("insert into segments(recording_id, start_s, end_s, label, text) values(?,?,?,?,?)",+ [(rid, s["start_s"], s["end_s"], s["label"], s["text"]) for s in res.segments])+ match_speakers(c, rid, res.speakers)+ store.refresh_transcript(c, rid)+ status = "transcribed" if words else "empty"+ c.execute("""update recordings set status=?, error=null, duration_s=?, speech_s=?, words=?, ended_at=?,+ updated_at=? where id=?""",+ (status, res.duration_s, sum(v["speech_s"] for v in res.speakers.values()), words, ended,+ db.now_iso(), rid))+ db.mark_day_dirty(c, r["day"])+ if not config.tunables()["keep_audio"]:+ shutil.rmtree(config.AUDIO_DIR / rid, ignore_errors=True)+ c.execute("update chunks set path=null where recording_id=?", (rid,))+++def meeting_title(r) -> str | None:+ if r["trigger"] != "calendar":+ return None+ try:+ import calendar_feed+ for m in calendar_feed.meetings():+ if m["start"] <= (r["ended_at"] or r["started_at"]) and m["end"] >= r["started_at"]:+ return m["title"]+ except Exception:+ pass+ return None+++def wearer(c) -> str | None:+ """Name of the enrolled "this is me" voice, so summaries know who wore the watch."""+ row = c.execute("select name from speakers where is_self=1 limit 1").fetchone()+ return row["name"] if row else None+++def summarize_recording(c, r) -> None:+ rid = r["id"]+ cfg = config.tunables()+ if (r["words"] or 0) < cfg["min_words_to_summarize"]:+ first = (r["transcript_text"] or "").split(":", 1)[-1].strip()+ title = (" ".join(first.split()[:6]) + "...") if first else "Short exchange"+ c.execute("update recordings set status='done', title=?, summary_json=null, summary_text=null, updated_at=? where id=?",+ (title, db.now_iso(), rid))+ db.mark_day_dirty(c, r["day"])+ return+ c.execute("update recordings set status='summarizing', updated_at=? where id=?", (db.now_iso(), rid))+ when = datetime.fromisoformat(r["started_at"]).astimezone().strftime("%a %b %d %Y, %I:%M %p")+ s = summarize.conversation(r["transcript_text"], when, (r["duration_s"] or 0) / 60, r["trigger"], meeting_title(r),+ db.settings(c)["summary"], wearer(c))+ with db.tx(c):+ c.execute("""update recordings set status='done', error=null, title=?, summary_json=?, summary_text=?, updated_at=?+ where id=?""", (s.get("title"), json.dumps(s), store.summary_text(s), db.now_iso(), rid))+ db.mark_day_dirty(c, r["day"])+ log(f"{rid}: summarized: {s.get('title')}")+++def rebuild_day(c, day: str) -> None:+ rows = c.execute("""select started_at, title, summary_json from recordings+ where day=? and status='done' and summary_json is not null order by started_at""", (day,)).fetchall()+ if not rows:+ c.execute("update days set summary_json=null, summary_text=null, dirty=0, dirty_since=null, updated_at=? where day=?",+ (db.now_iso(), day))+ return+ items = []+ for r in rows:+ s = json.loads(r["summary_json"])+ items.append({"time": datetime.fromisoformat(r["started_at"]).astimezone().strftime("%I:%M %p"),+ "title": s.get("title") or r["title"] or "", "summary": s.get("summary", ""),+ "key_points": s.get("key_points", []), "action_items": s.get("action_items", []),+ "people": s.get("people", [])})+ label = datetime.strptime(day, "%Y-%m-%d").strftime("%A, %B %d %Y")+ s = summarize.day(label, items, db.settings(c)["summary"], wearer(c))+ text = "\n".join([s.get("headline", ""), s.get("summary", "")] + [f"- {k}" for k in s.get("key_points", [])])+ c.execute("update days set summary_json=?, summary_text=?, dirty=0, dirty_since=null, updated_at=? where day=?",+ (json.dumps(s), text, db.now_iso(), day))+ log(f"day {day}: digest rebuilt from {len(items)} conversation(s)")+++def due_days(c) -> list[str]:+ debounce = (datetime.now(timezone.utc) - timedelta(minutes=config.tunables()["day_rebuild_debounce_minutes"])).isoformat()+ out = []+ for d in c.execute("select day, dirty_since from days where dirty=1").fetchall():+ pending = c.execute("""select count(*) from recordings where day=? and status in+ ('receiving','waiting','transcribing','transcribed','summarizing')""", (d["day"],)).fetchone()[0]+ if not pending or (d["dirty_since"] or "") < debounce:+ out.append(d["day"])+ return out+++def run_jobs(c, eng: transcribe.Engine) -> None:+ for j in c.execute("select * from jobs where status='queued' order by id").fetchall():+ p = json.loads(j["payload"])+ try:+ emb = eng.voiceprint(Path(p["path"]))+ with db.tx(c):+ row = c.execute("select id from speakers where lower(name)=lower(?)", (p["name"],)).fetchone()+ sid = row["id"] if row else c.execute("insert into speakers(name, created_at) values(?,?)",+ (p["name"], db.now_iso())).lastrowid+ if p.get("is_self"):+ c.execute("update speakers set is_self = (id = ?)", (sid,))+ store.fold_into_speaker(c, sid, store.emb_dump(emb))+ c.execute("update jobs set status='done', done_at=? where id=?", (db.now_iso(), j["id"]))+ log(f"voiceprint enrolled for {p['name']}")+ except Exception as e:+ c.execute("update jobs set status='failed', error=?, done_at=? where id=?", (str(e)[:500], db.now_iso(), j["id"]))+ log(f"enroll failed: {e}")+ finally:+ Path(p["path"]).unlink(missing_ok=True)+++def fail(c, rid: str, stage: str, e: Exception, retry_status: str) -> None:+ attempts = c.execute("select attempts from recordings where id=?", (rid,)).fetchone()[0] + 1+ status = "failed" if attempts >= MAX_ATTEMPTS else retry_status+ c.execute("update recordings set status=?, attempts=?, error=?, updated_at=? where id=?",+ (status, attempts, f"{stage}: {e}"[:800], db.now_iso(), rid))+ log(f"{rid}: {stage} error ({attempts}/{MAX_ATTEMPTS}): {e}")+++# ---- main loop ------------------------------------------------------------------++def main() -> None:+ config.ensure_dirs()+ db.init()+ c = db.connect()+ eng = transcribe.Engine()+ summary_wait_until = 0.0+ # A crash mid-step leaves rows in a working state; put them back in line.+ c.execute("update recordings set status='waiting' where status='transcribing'")+ c.execute("update recordings set status='transcribed' where status='summarizing'")+ log("worker started")+ while True:+ state = "idle"+ try:+ jobs = c.execute("select count(*) from jobs where status='queued'").fetchone()[0]+ if jobs:+ state = "enrolling"+ db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state})+ run_jobs(c, eng)++ ready = ready_recordings(c)+ if ready:+ r = ready[0]+ state = "transcribing"+ db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state})+ try:+ process_recording(c, eng, r)+ try:+ into = stitch.auto_merge(c, r["id"])+ if into:+ log(f"{r['id']}: joined onto {into}")+ except Exception as e: # a failed stitch must never cost the transcript+ traceback.print_exc()+ log(f"{r['id']}: auto-merge skipped: {e}")+ except Exception as e:+ traceback.print_exc()+ fail(c, r["id"], "transcribe", e, "waiting")++ # A provider change or a new API key in Settings ends the pause right away.+ stamp = db.get_kv(c, "summary_changed_at")+ if stamp and stamp != getattr(main, "_seen_stamp", None):+ main._seen_stamp = stamp+ summary_wait_until = 0.0+ config.reload_env()+ if time.time() >= summary_wait_until:+ settle = (datetime.now(timezone.utc) - timedelta(seconds=RESUMMARIZE_SETTLE_S)).isoformat()+ todo = c.execute("""select * from recordings where status='transcribed' and updated_at < ?+ order by started_at limit 1""", (settle,)).fetchone()+ try:+ if todo:+ state = "summarizing"+ db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state})+ summarize_recording(c, todo)+ else:+ for day in due_days(c)[:1]:+ state = "daily digest"+ rebuild_day(c, day)+ except Exception as e:+ if not isinstance(e, summarize.SummaryError):+ traceback.print_exc()+ log(f"summary step error: {e}; pausing summaries 10 min")+ if todo:+ fail(c, todo["id"], "summary", e, "transcribed")+ summary_wait_until = time.time() + 600++ eng.maybe_unload()+ except Exception as e:+ traceback.print_exc()+ state = f"error: {e}"+ db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state, "models_loaded": eng.loaded()})+ time.sleep(TICK_S)+++if __name__ == "__main__":+ main()