A Python desktop copilot for macOS that listens to both sides of a live business call (your microphone and the
remote participant via Core Audio Multi-Output / BlackHole loopback), transcribes phrases locally on the CPU
with faster-whisper, retrieves strictly isolated client facts from local ChromaDB collections, and
writes a 1–2 sentence response you can speak aloud—refusing to invent budgets, dates, or commitments
when the history lacks the answer.
During a live client call, generic AI assistants are dangerous: if asked about an unrecorded delivery date, SLA target, or budget cap, they eagerly improvise plausible-sounding numbers. In real engineering consulting, a hallucinated commitment creates immediate contractual liability.
conversations.json or
account .zip), and the copilot indexes them locally on disk under
`~/.context_assistant/vector_db`.prof_<slug>). Default_Client and
Other_Client never share embeddings.UPDATE_WORKSPACE_MEMORY_PROTOCOL_INIT block ready to paste back into your
ChatGPT thread.Capturing both sides of a call on macOS while wearing AirPods or headphones requires bridging low-level audio driver gaps and speech model quirks:
audio_devices.py queries Core Audio directly via ctypes (dev#
and agrp selectors) to locate the underlying BlackHole loopback input member.prepare_speech_audio scores 20 ms frames by RMS, drops clips below
0.005, trims quiet tails, and normalizes robust 99.9th-percentile peaks to
0.95.SequenceMatcher (ratio
≥ 0.72 across opposite speakers) drops the duplicate while preserving legitimate self-repetition.
Explore all 12 captures across both desktop editions: live call transcription, ChromaDB citations, knowledge browsers, post-call review packets, and hardware settings.
Rust/Skia desktop interface displaying active client profile, 16 kHz audio pipeline status, and Ollama llama3.1:8b engine readiness.
Real-time descending dialogue stream with 48 kHz to 16 kHz resampling, 1-click copy suggestion, and Top-3 ChromaDB source chunks.
Isolated client profile selector, ChatGPT JSON/ZIP context importer, and indexed fragment browser showing SLA and budget threads.
Browse generated Markdown review packets, export conversations or meeting resumes, and copy the ChatGPT memory sync protocol block.
Configure Ollama, OpenAI, or custom OpenAI-compatible endpoints, dynamically fetch remote models, and customize the {context} system prompt.
Select microphone and Multi-Output loopback devices, switch spoken languages, adapt Whisper checkpoints, and restore factory defaults.
Animated shutdown overlay safely stopping active audio streams, flushing final phrases, persisting config.json, and releasing hardware hooks.
Zero-dependency CPython Tkinter edition featuring custom label-backed ActionButtons, thread-safe UI queue polling, and AppKit window activation.
Active call session answering participant timeline questions strictly from Project Alpha ChromaDB chunks with follow-up prompt suggestions.
Manage isolated ChromaDB client vector collections, create profiles, import ChatGPT exports, or wipe and reset a profile's memory.
Inspect timestamped post-call review packets, export verbatim call transcripts or resumes in MD/TXT/CSV, and copy the ChatGPT sync block.
Unified configuration panel for LLM providers, dynamic model discovery, Whisper checkpoints, Multi-Output audio devices, and prompt templates.
Every spoken phrase follows a deterministic, non-blocking path from hardware audio capture through signal conditioning, local CPU speech-to-text, cross-talk filtering, and isolated vector retrieval before reaching the language model.
+----------------------------------------------------------------------------------------------------+
| MACOS CORE AUDIO & PORTAUDIO CAPTURE LAYER |
| [Physical Microphone / AirPods] [Meeting Audio: Multi-Output -> BlackHole 2ch] |
| (sd.InputStream @ native Hz, 250ms blocks) (CoreAudio ctypes 'agrp' lookup -> high-energy ch) |
+----------------------+-------------------------------------------------------+---------------------+
│ │
└───────────────────────────┬───────────────────────────┘
|
+--------------------------------------------------+-------------------------------------------------+
| PER-SPEAKER PHRASE DETECTOR (speech_audio.take_speech_phrase) |
| - Slow-average noise floor tracker + 350 ms rolling pre-roll buffer (prevents clipped word onset) |
| - Opens phrase after 200 ms above floor; closes after 0.7 s silence or 8.0 s max duration |
+--------------------------------------------------+-------------------------------------------------+
│
put_nowait() to Background Worker
(Generation Counter Guards Stale Calls)
|
+--------------------------------------------------+-------------------------------------------------+
| SIGNAL CONDITIONING & LOCAL CPU SPEECH-TO-TEXT |
| 1. prepare_speech_audio(): 20 ms frame RMS gate (>= 0.005) drops room hiss; trims quiet tails |
| 2. _resample_16k(): SciPy Kaiser-windowed (beta=14.0) polyphase resampler to 16 kHz mono |
| 3. _level(): 99.9th-percentile click-resistant peak normalization to 0.95 (max gain 6.0x) |
| 4. transcribe_speech(): faster-whisper (int8_float32, temp 0.0) + hallucination & loop filters |
| 5. is_cross_talk_echo(): SequenceMatcher (>= 0.72) drops acoustic bleed across opposite streams |
+--------------------------------------------------+-------------------------------------------------+
│
│
+----------------------------------+ +--------+-------------------------------------------------+
| CHROMADB VECTOR STORE | | GROUNDED INFERENCE ENGINE (Ollama / OpenAI SDK) |
| ~/.context_assistant/vector_db |─────| - Substitutes Top-6 deduplicated chunks into {context} |
| - Isolated prof_<slug> per client| | - Enforces 1-2 sentence first-person reply at temp 0.0 |
| - Queries current + prev turn | | - Outputs strict refusal line if fact is undocumented |
+----------------------------------+ +--------+-------------------------------------------------+
│
┌─────────────────────────┴─────────────────────────┐
| |
+------------------------+------------------------+ +------------------------+-----------------------+
| DESKTOP UI EDITIONS (Shared Session Pipeline) | | POST-CALL ARTIFACTS & EXPORTS |
| - app_aurora.py: Aurora UI (Rust/Skia + Signals)| | - review_packet_<timestamp>.md (ChatGPT sync) |
| - app.py: Elevated Tkinter (Queue + AppKit) | | - call_export.py: Verbatim MD / TXT / CSV |
+-------------------------------------------------+ +------------------------------------------------+
| Module / File | Primary Stack | Core Responsibility | Reliability & Platform Safeguards |
|---|---|---|---|
| app_aurora.py | Aurora UI (Rust / Skia / Taffy) | Reactive desktop edition driven by Signals, flexbox layout, floating toasts, and citation cards. | Background daemon threads update reactive signals; serialized Whisper loading via
_whisper_lock. |
| app.py | CPython Tkinter + PyObjC AppKit | Multi-page desktop edition with Midnight/Daylight themes, custom ActionButton labels, and
packet inspector. |
Thread-safe ui_queue drained on main loop prevents GIL/Tk crashes; AppKit forces
foreground focus on macOS. |
| audio_devices.py | Core Audio (ctypes) + PortAudio |
Enumerates macOS aggregate/Multi-Output devices and maps multi:<name> to its
BlackHole input index. |
Gracefully falls back to auto-detected BlackHole input or standard microphone when aggregate devices change. |
| speech_audio.py | NumPy, SciPy, faster-whisper | Energy VAD state machine, 16 kHz Kaiser resampling, robust leveling, Whisper decoding, and echo suppression. | Rejects clips < 350 ms, filters silence before inference, blocks known Whisper hallucinations, and drops cross-talk. |
| call_export.py | Python csv, re, Markdown |
Exports full call transcripts or structured meeting resumes in Markdown, plain text, or CSV formats. | Strictly restates captured turns; labels copilot suggestions separately and never fabricates unstated decisions. |
| ui_icons.py | SVG Byte Vectors + Pillow / AppKit | Provides crisp vector iconography directly to Aurora Skia and rasterizes icons for Tkinter
PhotoImage. |
Attempts native macOS AppKit SVG rasterization first, falling back cleanly to Pillow drawing primitives. |
| test_audio.py | sounddevice + NumPy CLI | Standalone 8-second terminal VU-meter diagnostic utility for testing single inputs (mic or BlackHole). | Flags peak amplitude < 0.005 with actionable macOS Privacy & Security microphone permission guidance. |
| test_workflow.py & E2E | Headless Test Harnesses | Exercises ChromaDB ingestion, grounded retrieval, refusal invariants, and both UI editions without live audio. | Verifies profile isolation (prof_*), prompt restoration, and zero-hallucination responses
in CI/local runs. |
Inspect the key engineering mechanisms from the codebase: resolving hidden macOS Multi-Output devices via Core Audio, trailing-window phrase detection with rolling pre-roll, hallucination-guarded speech conditioning, and verbatim post-call resume rendering.
# audio_devices.py
def multi_output_devices() -> List[Dict[str, object]]:
"""Return Multi-Output / aggregate devices and the input used to record them."""
try:
members = _aggregate_members()
except Exception:
return []
listed = []
for name, member_names in members:
capture_index = None
capture_name = None
ordered = sorted(
member_names,
key=lambda item: (0 if "blackhole" in item.lower() else 1, item.lower()),
)
for member in ordered:
found = _input_index_by_name(member)
if found is not None:
capture_index = found
capture_name = member
break
listed.append({
"id": MULTI_PREFIX + name,
"label": short_device_label(name),
"capture_index": capture_index,
"capture_name": capture_name,
})
return listed
# speech_audio.py
def take_speech_phrase(state: dict, chunk) -> Optional[np.ndarray]:
sr = int(state["sr"])
samples = np.asarray(chunk, dtype=np.float32).reshape(-1)
rms = float(np.sqrt(np.mean(np.square(samples))))
speaking = bool(state.get("is_speaking"))
if not speaking:
floor = float(state.get("noise_floor", 0.0015))
state["noise_floor"] = (0.95 * floor) + (0.05 * rms)
floor = max(float(state.get("noise_floor", 0.0015)), 1e-5)
ceiling = min(max(float(state.get("cfg_thresh") or 0.008), 0.004), 0.01)
open_at = max(0.004, min(ceiling, max(floor * 3.0, 0.004)))
is_speech = rms >= (open_at * 0.5 if speaking else open_at)
# 350ms rolling pre-roll prevents clipping word onsets;
# 0.7s silence or 8.0s max closes the active utterance
ended = state["silent_frames"] >= int(sr * 0.7) or len(buffer) >= int(sr * 8.0)
# speech_audio.py
def _level(audio: np.ndarray) -> np.ndarray:
"""Bring speech up to a clear peak. A single click must not set the gain."""
magnitude = np.abs(audio)
peak = float(np.max(magnitude))
robust_peak = float(np.quantile(magnitude, 0.999))
if peak < 1e-4:
return audio
reference = robust_peak if peak > robust_peak * 4.0 else peak
gain = min(TARGET_PEAK / max(reference, 1e-4), MAX_GAIN)
return np.clip(audio * gain, -0.95, 0.95).astype(np.float32)
def is_cross_talk_echo(previous_speaker: str, previous_text: str, speaker: str, text: str) -> bool:
if not previous_text or not text or previous_speaker == speaker:
return False
prev_line, new_line = " ".join(_words(previous_text)), " ".join(_words(text))
return SequenceMatcher(None, prev_line, new_line).ratio() >= 0.72
# call_export.py
def _overview_lines(turns: Sequence[Turn], markdown: bool) -> List[str]:
heading = "## Overview" if markdown else "Overview"
lines = [
"",
heading,
"",
"This resume restates the captured transcript. "
"It does not add agreements, dates, or decisions that were not spoken.",
"",
]
if not turns:
lines.append("No speech was captured.")
return lines
lines.append(f"First line: {turns[0][0]}")
lines.append(f"Last line: {turns[-1][0]}")
lines.append(f"Turns: {len(turns)}")
for speaker, count in _speaker_counts(turns):
lines.append(f"{speaker}: {count} turns")
return lines