Turn a Galaxy Watch into a wearable AI note taker. Local transcription with speaker labels, summaries from the AI you already pay for.
Python
Summary schedule, busy-PC wait, and local model support
Alex1599dba1e406
diff --git a/AGENTS.md b/AGENTS.mdindex 7e4d1f9..a047108 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -28,7 +28,8 @@ When the user says "set this up" (or similar), run the setup below. Work throughProviders: `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.+ - Local: follow "Using a free local model" in SETUP.md. 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. Suggest a small model (7B to 12B). Ask before downloading one, since it is several GB.+ - With a local model, ask whether they game, edit or render on this PC. If yes, suggest `"when": "daily"` with a `daily_time`, and `{"system": {"pause_when_busy": true}}` (same settings endpoint).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.@@ -60,4 +61,6 @@ When the user says "set this up" (or similar), run the setup below. Work through- 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`.+- Local models: `summarize.py` sends `reasoning_effort: none` to local endpoints and splits conversations that exceed the model's context. If a local summary takes over a minute, check that the model's thinking is really off before changing anything else. `POST /api/summary/test` returns the seconds taken.+- If you are running inside VS Code, your shell has `ELECTRON_RUN_AS_NODE=1` set. LM Studio (and any Electron app) won't start from it, and `lms` reports "no valid installation was found". Clear the variable for that command first.- Don't set `JAVA_HOME` for the gradle build unless it is missing. A wrong one breaks it.diff --git a/README.md b/README.mdindex 5a7f394..1da27f9 100644--- a/README.md+++ b/README.md@@ -16,6 +16,7 @@ Tap the watch to record a conversation. Your PC transcribes it with speaker name- any API key (OpenAI, Gemini, Anthropic, OpenRouter)- a free local model (Ollama or LM Studio)- **A daily digest** of everything you recorded that day.+- **Easy on your PC.** Summarize right away, in one batch at a set time, or only when you ask. It can also wait while you game or render.- **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.@@ -71,9 +72,9 @@ data/voice.db (SQLite) -> dashboard at http://127.0.0.1:8808## 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.+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. The local-model path was tested on LM Studio with Qwen 3.5 9B (Q4): 10 to 20 seconds per summary with thinking off for conversations up to 30 minutes, about a minute for a 1 hour one. Planted facts were all kept in synthetic 10, 30 and 60 minute transcripts, and 5 of 6 in a 2 hour one. The summary schedule and the busy-PC wait were tested with forced conditions.-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.+Not tested yet: real OpenAI, Gemini and Ollama endpoints, local-model quality on real (not synthetic) long conversations, the busy-PC thresholds against a real game or render, 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.## Licensediff --git a/SETUP.md b/SETUP.mdindex 96d9ac5..0379ad9 100644--- a/SETUP.md+++ b/SETUP.md@@ -56,12 +56,50 @@ Open http://127.0.0.1:8808 and go to **Settings > Summaries**. Pick a provider a| 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 |+| Local model | See "Using a free local model" below. 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`.+### Using a free local model++A summary is an easy job, so a small model is enough. A model in the 7B to 12B range (about 5 to 8 GB) fits on the GPU next to the transcription models.++**Ollama**++```powershell+winget install Ollama.Ollama+ollama pull <model>+```++Pick a small instruct model from ollama.com/library. In Settings > Summaries choose "API key or local model", service **Ollama**, and type the model name exactly as `ollama list` shows it.++**LM Studio**++```powershell+lms get qwen/qwen3.5-9b+lms server start+```++Choose service **LM Studio** and type the model name as `lms ls` shows it. In LM Studio's server settings, keep "Just-in-Time model loading" on.++**Thinking is switched off for you.** Many small models "think" for a long time before answering, which a summary doesn't need. On local endpoints the app asks the model not to (it sends `reasoning_effort: none`). On Qwen 3.5 9B that cut a short summary from 34 seconds to 4. If your model ignores that setting and summaries take a minute or more, turn reasoning off in the model's own settings, or pick a model without a thinking mode.++**Long conversations.** Local models often load with a small context (LM Studio defaulted to 8,192 tokens here, which is about 30 minutes of talk). When a conversation doesn't fit, the app summarizes it in parts and merges them, so nothing fails. For better results on long meetings, raise the model's context length to 16K or 32K in LM Studio or Ollama if your GPU has the memory.++**The model does not stay loaded.** Both tools load the model when a summary is requested and unload it after it has been idle (Ollama after 5 minutes by default, LM Studio after its idle time). To set LM Studio's idle time from this app, create `config.json` in this folder with `{"summary_extra_body": {"ttl": 300}}` (seconds).++To keep the PC free during the day, also look at **When to summarize** in Settings:++| Setting | What happens |+|---|---|+| Right away | Each conversation is summarized about a minute after it ends |+| Once a day | Transcripts appear right away. All summaries and the digest run in one batch at the time you pick. If the PC was off then, the batch runs when it is next on |+| Only when I ask | Nothing is summarized until you press "Summarize pending now" in Settings or "Re-summarize" on a conversation |++And under Settings > System, **Wait while the PC is busy** holds transcription and local-model summaries while other programs are using the GPU or CPU heavily (a game, a render). Recordings wait in the queue and are processed when the PC calms down.+## 5. Connect the watchOn the watch:@@ -149,5 +187,6 @@ Wi-Fi mode only uploads at home. To upload from anywhere, put the PC behind a tu| `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. |+| Summaries never appear | Settings > Summaries > Save and test shows the exact error. Also check "When to summarize": on the daily or manual setting they wait on purpose. |+| Recordings sit at "queued" | "Wait while the PC is busy" is on and something is loading the GPU or CPU. Pipeline status shows the reason. || Dashboard says "wrong Python" | Start it with `python launch.py start`, which uses the `.venv` in this folder. |diff --git a/config.py b/config.pyindex 1ce5f2c..3973c73 100644--- a/config.py+++ b/config.py@@ -46,6 +46,11 @@ DEFAULTS = {"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+ "gpu_busy_percent": 50, # "wait while the PC is busy": hold work at or above this GPU load...+ "cpu_busy_percent": 80, # ...or this CPU load, sustained over a few seconds+ # Extra fields added to every request to an OpenAI-compatible endpoint, e.g. LM Studio's+ # idle unload: {"ttl": 300}. Leave empty for cloud services, which reject unknown fields.+ "summary_extra_body": {},}diff --git a/db.py b/db.pyindex 65690f9..7f759cb 100644--- a/db.py+++ b/db.py@@ -119,7 +119,10 @@ DEFAULT_SETTINGS = {"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": ""},+ # when: now (a minute after each conversation) | daily (one batch at daily_time) | manual (only on request).+ "summary": {"provider": "claude_subscription", "model": "", "base_url": "", "when": "now", "daily_time": "23:00"},+ # Hold transcription and local-model summaries while something else is loading the GPU or CPU.+ "system": {"pause_when_busy": False},}@@ -155,6 +158,9 @@ def tx(con: sqlite3.Connection):def init() -> None:con = connect()con.executescript(SCHEMA)+ cols = {r["name"] for r in con.execute("pragma table_info(recordings)")}+ if "summary_requested" not in cols: # "summarize this one now", for the daily and manual schedules+ con.execute("alter table recordings add column summary_requested integer not null default 0")con.close()@@ -180,6 +186,7 @@ def settings(con) -> dict:merged["silence"].update(s.get("silence", {}))merged["merge"].update(s.get("merge", {}))merged["summary"].update(s.get("summary", {}))+ merged["system"].update(s.get("system", {}))return mergeddiff --git a/requirements.txt b/requirements.txtindex 65fb079..df221db 100644--- a/requirements.txt+++ b/requirements.txt@@ -6,6 +6,8 @@ uvicorn>=0.30python-multipartpython-dotenvhttpx+psutil>=6+nvidia-ml-pyicalendar>=6recurring-ical-events>=3# Only needed for the "Claude subscription" summary provider:diff --git a/server.py b/server.pyindex 2b52e03..4d73261 100644--- a/server.py+++ b/server.py@@ -313,8 +313,8 @@ async def name_speaker(rec_id: str, label: str, request: Request):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+ n = c.execute("""update recordings set status='transcribed', error=null, attempts=0, summary_requested=1,+ updated_at=? where id=? and transcript_text is not null""", (db.now_iso(), rec_id)).rowcountfinally:c.close()if not n:@@ -543,6 +543,21 @@ async def put_settings(request: Request):raise HTTPException(422, "base URL must start with http:// or https://")changed |= s["summary"][k] != vs["summary"][k] = v+ if "when" in summ:+ if summ["when"] not in ("now", "daily", "manual"):+ raise HTTPException(422, "summary schedule must be now, daily or manual")+ if summ["when"] == "daily" and s["summary"]["when"] != "daily":+ # Start counting from now, so switching to daily doesn't fire a batch on the spot.+ b = db.get_kv(c, "summary_batch") or {}+ db.set_kv(c, "summary_batch", {"active": bool(b.get("active")),+ "last_at": datetime.now().isoformat(timespec="seconds")})+ s["summary"]["when"] = summ["when"]+ if "daily_time" in summ:+ if not TIME_RE.match(str(summ["daily_time"] or "")):+ raise HTTPException(422, "daily summary time must look like 23:00")+ s["summary"]["daily_time"] = summ["daily_time"]+ if "pause_when_busy" in (body.get("system") or {}):+ s["system"]["pause_when_busy"] = bool(body["system"]["pause_when_busy"])if "api_key" in summ: # "" keeps the saved key; clear_api_key removes itkey = str(summ["api_key"] or "").strip()if key:@@ -573,6 +588,20 @@ def summary_test():return {"ok": False, "error": str(e)[:500]}[email protected]("/api/summary/run")+def summary_run():+ """Summarize everything that is waiting, now. Used by the daily and manual schedules."""+ c = con()+ try:+ n = c.execute("select count(*) from recordings where status='transcribed'").fetchone()[0]+ b = db.get_kv(c, "summary_batch") or {}+ db.set_kv(c, "summary_batch", {**b, "active": True})+ db.set_kv(c, "summary_changed_at", db.now_iso()) # also clears a 10 minute error pause+ finally:+ c.close()+ return {"ok": True, "pending": n}++@app.post("/api/upload")async def upload(file: UploadFile = File(...)):tmp, sha, ext = await _save_upload(file)diff --git a/static/app.js b/static/app.jsindex 28f36ee..d5c19ff 100644--- a/static/app.js+++ b/static/app.js@@ -130,7 +130,7 @@ 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;+ const label = { waiting: 'queued', empty: 'no speech', transcribed: 'summary pending' }[status] || status;return '<span class="' + cls + '">' + esc(label) + '</span>';}function triggerBadge(t) { return t ? '<span class="badge">' + esc(t) + '</span>' : ''; }@@ -816,6 +816,10 @@ function normalizeSettings(s) {s.summary.model = s.summary.model || '';s.summary.base_url = s.summary.base_url || '';s.summary.api_key_set = !!s.summary.api_key_set;+ s.summary.when = s.summary.when || 'now';+ s.summary.daily_time = s.summary.daily_time || '23:00';+ s.system = s.system || {};+ s.system.pause_when_busy = !!s.system.pause_when_busy;return s;}@@ -886,6 +890,27 @@ const PROVIDER_HELP = {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.',};+const WHEN = [+ ['now', 'Right away, a minute after each conversation'],+ ['daily', 'Once a day, all at a set time'],+ ['manual', 'Only when I ask'],+];+const WHEN_HELP = {+ now: 'Each conversation is summarized about a minute after it ends.',+ daily: 'Transcripts appear right away. Summaries and the daily digest run in one batch at this time. If the PC was off then, the batch runs when it is next on.',+ manual: 'Transcripts appear right away. Nothing is summarized until you press "Summarize pending now" here, or "Re-summarize" on a conversation.',+};++function whenFieldsHtml(st) {+ const sm = st.summary;+ return '<div class="field-row"><label for="sm-when">When</label><select id="sm-when">' ++ WHEN.map(([v, l]) => '<option value="' + v + '"' + (sm.when === v ? ' selected' : '') + '>' + esc(l) + '</option>').join('') + '</select>' ++ (sm.when === 'daily' ? '<input type="time" id="sm-time" value="' + esc(sm.daily_time) + '" aria-label="Daily summary time">' : '') + '</div>' ++ '<p class="card-meta" style="margin:0 0 10px">' + esc(WHEN_HELP[sm.when] || '') + '</p>' ++ (sm.when !== 'now' ? '<div class="btn-row" style="margin-top:6px"><button class="btn" type="button" id="sm-run">Summarize pending now</button></div>' : '') ++ '<div class="card-meta" id="sm-run-status"></div>';+}+function summaryFieldsHtml(st) {const sm = st.summary;const compat = sm.provider === 'openai_compatible';@@ -965,10 +990,14 @@ async function renderSettings(token) {'<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>') ++ sRow('When to summarize', 'Summaries are light on a cloud provider. With a local model you may want them batched, so the model only loads once a day.',+ '<div id="sm-when-fields">' + whenFieldsHtml(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('Busy PC', 'Useful if you game, edit video or render on this PC. Recordings wait in the queue and are processed when the PC calms down.',+ '<label class="row-check"><input type="checkbox" id="st-busy"' + (st.system.pause_when_busy ? ' checked' : '') + '> Wait while the PC is busy (heavy GPU or CPU use by other programs)</label>') +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>' +@@ -1014,6 +1043,24 @@ async function renderSettings(token) {smHost.innerHTML = summaryFieldsHtml(st);$('#sm-status').textContent = status;};+ const whenHost = $('#sm-when-fields');+ whenHost.addEventListener('change', e => {+ if (e.target.id === 'sm-when') { st.summary.when = e.target.value; whenHost.innerHTML = whenFieldsHtml(st); }+ else if (e.target.id === 'sm-time' && e.target.value) st.summary.daily_time = e.target.value;+ });+ whenHost.addEventListener('click', async e => {+ if (!e.target.closest('#sm-run')) return;+ try {+ await saveSettings();+ const r = await api('api/summary/run', { method: 'POST' });+ if (token !== state.nav) return;+ $('#sm-run-status').textContent = r && r.pending+ ? 'Started. Summarizing ' + r.pending + ' conversation' + (r.pending === 1 ? '' : 's') + ', then the daily digest.'+ : 'Nothing is waiting for a summary. Any digest that needs a refresh will run.';+ } catch (err) { fail(err); }+ });+ $('#st-busy').addEventListener('change', e => { st.system.pause_when_busy = e.target.checked; });+smHost.addEventListener('click', async e => {if (!e.target.closest('#sm-test')) return;try {diff --git a/static/index.html b/static/index.htmlindex 3867c32..87af16d 100644--- a/static/index.html+++ b/static/index.html@@ -9,7 +9,7 @@<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">+ <link rel="stylesheet" href="style.css?v=3"></head><body><div class="shell">@@ -65,6 +65,6 @@<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>- <script src="app.js?v=1"></script>+ <script src="app.js?v=2"></script></body></html>diff --git a/static/style.css b/static/style.cssindex 788e1fa..5f95c6e 100644--- a/static/style.css+++ b/static/style.css@@ -453,3 +453,4 @@ a.hit:hover { background: var(--panel-2); }.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; }+.field-row input[type="time"] { width: auto; }diff --git a/summarize.py b/summarize.pyindex f1ee31e..70961ed 100644--- a/summarize.py+++ b/summarize.py@@ -220,16 +220,23 @@ def _compatible(prompt: str, system: str, schema: dict, model: str, base_url: st# 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]+ extra = dict(config.tunables().get("summary_extra_body") or {})+ # Small local models often "think" for a minute before a ten second answer. A summary doesn't need it,+ # so thinking is switched off on local endpoints (measured on Qwen 3.5 9B: 34 s -> 4 s). Servers that+ # don't know the field get one retry without it. Override with "reasoning_effort" in summary_extra_body.+ attempts = [(fmt, extra) for fmt in formats]+ if is_local({"provider": "openai_compatible", "base_url": base_url}) and "reasoning_effort" not in extra:+ attempts.insert(0, (formats[0], {**extra, "reasoning_effort": "none"}))last = ""- for fmt in formats:- body = {"model": model, "messages": messages}+ for n, (fmt, more) in enumerate(attempts):+ body = {**more, "model": model, "messages": messages}if fmt:body["response_format"] = fmttry:- r = httpx.post(url, headers=headers, json=body, timeout=600)+ r = httpx.post(url, headers=headers, json=body, timeout=900)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:+ if r.status_code in (400, 404, 415, 422, 501) and n < len(attempts) - 1:last = r.text[:300]continueif r.status_code >= 400:@@ -260,6 +267,34 @@ def _run(prompt: str, system: str, schema: dict, cfg: dict) -> dict:return _normalize(out, schema)+def is_local(cfg: dict) -> bool:+ """True when summaries run on this PC (Ollama, LM Studio...), so they compete with other work."""+ if (cfg.get("provider") or "") != "openai_compatible":+ return False+ return bool(re.match(r"^https?://(localhost|127\.0\.0\.1|\[::1\])[:/]", (cfg.get("base_url") or "") + "/"))+++CONTEXT_ERROR = re.compile(r"context|too long|too many tokens|maximum.{0,20}tokens|token limit", re.I)+PART_CHARS = 18_000 # about 3,000 words: fits an 8K-token context with room for the answer++MERGE_SYSTEM = """You are given summaries of consecutive parts of ONE long recorded conversation, in order.+Merge them into a single summary of the whole conversation. Keep every concrete fact, number, date, name,+decision and action item. Remove repeats. Plain and concrete, no filler. Return only the JSON object."""+++def _parts(transcript: str) -> list[str]:+ parts, cur, size = [], [], 0+ for line in transcript.splitlines():+ if size + len(line) > PART_CHARS and cur:+ parts.append("\n".join(cur))+ cur, size = [], 0+ cur.append(line)+ size += len(line) + 1+ if cur:+ parts.append("\n".join(cur))+ return parts++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}."@@ -268,7 +303,20 @@ def conversation(transcript: str, when: str, duration_min: float, trigger: str,# ~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)+ system = _conv_system(wearer)+ try:+ return _run(f"{head}\n\nTranscript:\n{transcript}", system, CONV_SCHEMA, cfg)+ except SummaryError as e:+ parts = _parts(transcript)+ if not CONTEXT_ERROR.search(str(e)) or len(parts) < 2:+ raise+ # The conversation doesn't fit the model's context (common with local models, which often load at+ # 4K-8K tokens). Summarize it in parts, then merge the part summaries.+ notes = []+ for n, part in enumerate(parts, 1):+ s = _run(f"{head} This is part {n} of {len(parts)} of the conversation.\n\nTranscript:\n{part}", system, CONV_SCHEMA, cfg)+ notes.append(f"PART {n} of {len(parts)}\n{json.dumps(s, ensure_ascii=False)}")+ return _run(f"{head}\n\nPart summaries:\n\n" + "\n\n".join(notes), MERGE_SYSTEM, CONV_SCHEMA, cfg)def day(day_label: str, items: list[dict], cfg: dict, wearer: str | None = None) -> dict:diff --git a/worker.py b/worker.pyindex 7fbd271..c5cf665 100644--- a/worker.py+++ b/worker.py@@ -9,6 +9,9 @@ Loop, every few seconds: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++Settings > Summaries decides when steps 4-5 run (right away, one daily batch, or only on request).+Settings > System can hold steps 2-3 (and local-model summaries) while the PC is busy with other work."""from __future__ import annotations@@ -103,10 +106,12 @@ def process_recording(c, eng: transcribe.Engine, r) -> None:match_speakers(c, rid, res.speakers)store.refresh_transcript(c, rid)status = "transcribed" if words else "empty"+ # Placeholder title from the first words, so the list reads well before a summary exists.+ opening = " ".join(" ".join(s["text"] for s in res.segments[:3]).split()[:7])c.execute("""update recordings set status=?, error=null, duration_s=?, speech_s=?, words=?, ended_at=?,- updated_at=? where id=?""",+ title=coalesce(title, ?), updated_at=? where id=?""",(status, res.duration_s, sum(v["speech_s"] for v in res.speakers.values()), words, ended,- db.now_iso(), rid))+ (opening + "...") if opening else None, 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)@@ -138,8 +143,8 @@ def summarize_recording(c, r) -> None: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))+ c.execute("""update recordings set status='done', title=?, summary_json=null, summary_text=null,+ summary_requested=0, updated_at=? where id=?""", (title, db.now_iso(), rid))db.mark_day_dirty(c, r["day"])returnc.execute("update recordings set status='summarizing', updated_at=? where id=?", (db.now_iso(), rid))@@ -147,8 +152,9 @@ def summarize_recording(c, r) -> None: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))+ c.execute("""update recordings set status='done', error=null, title=?, summary_json=?, summary_text=?,+ summary_requested=0, 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')}")@@ -210,11 +216,72 @@ def run_jobs(c, eng: transcribe.Engine) -> None: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] + 1status = "failed" if attempts >= MAX_ATTEMPTS else retry_status- c.execute("update recordings set status=?, attempts=?, error=?, updated_at=? where id=?",+ c.execute("update recordings set status=?, attempts=?, error=?, summary_requested=0, updated_at=? where id=?",(status, attempts, f"{stage}: {e}"[:800], db.now_iso(), rid))log(f"{rid}: {stage} error ({attempts}/{MAX_ATTEMPTS}): {e}")+# ---- when to work -----------------------------------------------------------------++def busy_reason() -> str | None:+ """"GPU 87%" / "CPU 93%" when something else has kept this PC loaded for the last few seconds.++ Called only while our own models are not running a job, so the load measured is other software's.+ The lowest of three samples is used: a short spike never blocks, steady load does.+ """+ cfg = config.tunables()+ gpu, cpu = [], []+ try:+ import psutil+ import pynvml+ try:+ pynvml.nvmlInit()+ handle = pynvml.nvmlDeviceGetHandleByIndex(0)+ except Exception:+ handle = None+ for _ in range(3):+ cpu.append(psutil.cpu_percent(interval=1.0))+ if handle is not None:+ gpu.append(pynvml.nvmlDeviceGetUtilizationRates(handle).gpu)+ except Exception as e:+ log(f"busy check unavailable ({e}); not waiting")+ return None+ if gpu and min(gpu) >= cfg["gpu_busy_percent"]:+ return f"GPU {min(gpu):.0f}%"+ if cpu and min(cpu) >= cfg["cpu_busy_percent"]:+ return f"CPU {min(cpu):.0f}%"+ return None+++def batch_active(c, cfg: dict) -> bool:+ """Is a summary batch running? The daily schedule starts one; so does "Summarize pending now"."""+ b = db.get_kv(c, "summary_batch") or {}+ if cfg.get("when") == "daily":+ now = datetime.now()+ try:+ hh, mm = (int(x) for x in (cfg.get("daily_time") or "23:00").split(":"))+ except ValueError:+ hh, mm = 23, 0+ sched = now.replace(hour=hh, minute=mm, second=0, microsecond=0)+ if sched > now:+ sched -= timedelta(days=1) # the most recent scheduled time, even if the PC was off then+ if not b.get("last_at"):+ b = {"active": bool(b.get("active")), "last_at": now.isoformat(timespec="seconds")}+ db.set_kv(c, "summary_batch", b)+ elif b["last_at"] < sched.isoformat(timespec="seconds"):+ b = {"active": True, "last_at": now.isoformat(timespec="seconds")}+ db.set_kv(c, "summary_batch", b)+ log("daily summary batch started")+ return bool(b.get("active"))+++def end_batch(c) -> None:+ b = db.get_kv(c, "summary_batch") or {}+ if b.get("active"):+ db.set_kv(c, "summary_batch", {**b, "active": False})+ log("summary batch finished")++# ---- main loop ------------------------------------------------------------------def main() -> None:@@ -228,16 +295,47 @@ def main() -> None:c.execute("update recordings set status='transcribed' where status='summarizing'")log("worker started")while True:- state = "idle"+ state, busy = "idle", Nonetry:+ settings = db.settings(c)+ summ = settings["summary"]jobs = c.execute("select count(*) from jobs where status='queued'").fetchone()[0]- if jobs:+ ready = ready_recordings(c)++ # 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()++ # What summary work is allowed right now?+ todo, batch = None, False+ if time.time() >= summary_wait_until:+ settle = (datetime.now(timezone.utc) - timedelta(seconds=RESUMMARIZE_SETTLE_S)).isoformat()+ batch = batch_active(c, summ)+ if summ.get("when", "now") == "now" or batch:+ todo = c.execute("""select * from recordings where status='transcribed' and updated_at < ?+ order by started_at limit 1""", (settle,)).fetchone()+ else: # daily (outside its batch) or manual: only what the user asked for+ # ...plus exchanges too short to need an AI summary, which cost nothing to finish.+ todo = c.execute("""select * from recordings where status='transcribed' and updated_at < ?+ and (summary_requested=1 or coalesce(words,0) < ?)+ order by started_at limit 1""",+ (settle, config.tunables()["min_words_to_summarize"])).fetchone()+ run_days = time.time() >= summary_wait_until and (summ.get("when", "now") == "now" or batch)+ days_due = due_days(c)[:1] if run_days and not todo else []++ local_summary = summarize.is_local(summ) and bool(todo or days_due)+ if settings["system"]["pause_when_busy"] and (jobs or ready or local_summary):+ busy = busy_reason()++ if jobs and not busy:state = "enrolling"db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state})run_jobs(c, eng)- ready = ready_recordings(c)- if ready:+ if ready and not busy:r = ready[0]state = "transcribing"db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state})@@ -253,26 +351,20 @@ def main() -> None:except Exception as e:traceback.print_exc()fail(c, r["id"], "transcribe", e, "waiting")+ elif ready:+ c.execute("update recordings set status='waiting' where status='receiving' and id in (%s)"+ % ",".join("?" * len(ready)), [r["id"] for r in ready])- # 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()+ if (todo or days_due) and not (busy and local_summary):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)+ state = "daily digest"+ db.set_kv(c, "worker_heartbeat", {"at": db.now_iso(), "state": state})+ rebuild_day(c, days_due[0])except Exception as e:if not isinstance(e, summarize.SummaryError):traceback.print_exc()@@ -280,7 +372,13 @@ def main() -> None:if todo:fail(c, todo["id"], "summary", e, "transcribed")summary_wait_until = time.time() + 600+ elif batch and not todo and not days_due and not ready:+ pending = c.execute("select count(*) from recordings where status in ('transcribed','summarizing')").fetchone()[0]+ if not pending:+ end_batch(c)+ if busy:+ state = f"waiting, the PC is busy ({busy})"eng.maybe_unload()except Exception as e:traceback.print_exc()