SPB Git

Repository Public License

make-diagrams.py 14.8 KB 212 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Audio10# File             : docs/assets/diagrams/make-diagrams.py11# Module           : docs12# Repository       : https://git.spboucher.ai/orix-audio13# Created          : 2026-11-2014# Last Modified    : 2026-11-2015#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author           : Simon-Pierre Boucher21# Position         : Professor of Finance22# Institution      : Université du Québec en Outaouais (UQO)23# Department       : Département des sciences administratives24# Organization     : SP Boucher25#26# Website          : https://spboucher.ai27# Git              : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General          : info@spboucher.ai34# Professional     : contact@spboucher.ai35# Direct           : simon@spboucher.ai36# Research         : research@spboucher.ai37# Development      : dev@spboucher.ai38# Support          : support@spboucher.ai39# Security/Admin   : admin@spboucher.ai40# Notifications    : notifications@spboucher.ai41#42# Preferred Contact: support@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification   : Public67# Distribution     : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License          : Proprietary, all rights reserved (see license file)81# License File     : LICENSE82# Maintainer       : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889# ORIX Audio90# File: docs/assets/diagrams/make-diagrams.py91# Description: Writes the architecture diagrams as plain SVG (boxes, arrows, notes) so they render on any git host.92#93# Author: Simon-Pierre Boucher94# Contact: contact@spboucher.ai95#96# Each diagram is described as rows of boxes plus arrows between box ids. The Mermaid source of the same diagrams is97# kept next to the prose in docs/architecture/*.md.98import pathlib99from xml.sax.saxutils import escape100101OUT = pathlib.Path(__file__).resolve().parent102BG, FG, MUTED, CYAN, VIOLET, SURFACE, LINE = "#0A0D18", "#F2F4FB", "#A3AAC2", "#22D3EE", "#8B5CF6", "#141828", "#262C42"103BW, BH, GX, GY, PAD = 190, 62, 46, 54, 36104105def diagram(name, title, rows, arrows, notes=()):106    cols = max(len(r) for r in rows)107    w = PAD * 2 + cols * BW + (cols - 1) * GX108    h = PAD + 44 + len(rows) * BH + (len(rows) - 1) * GY + 26 * len(notes) + PAD109    pos, parts = {}, []110    parts.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" aria-label="{escape(title)}">')111    parts.append(f'<title>{escape(title)}</title>')112    parts.append(f'<defs><marker id="a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="{MUTED}"/></marker></defs>')113    parts.append(f'<rect width="{w}" height="{h}" rx="18" fill="{BG}"/>')114    parts.append(f'<text x="{PAD}" y="{PAD + 14}" fill="{FG}" font-family="-apple-system,Helvetica,Arial,sans-serif" font-size="19" font-weight="700">{escape(title)}</text>')115    y0 = PAD + 44116    for r, row in enumerate(rows):117        offset = (cols - len(row)) * (BW + GX) / 2118        for c, box in enumerate(row):119            if box is None:120                continue121            bid, line1, line2, accent = box122            x, y = PAD + offset + c * (BW + GX), y0 + r * (BH + GY)123            pos[bid] = (x, y)124            stroke = {"c": CYAN, "v": VIOLET, "n": LINE}[accent]125            parts.append(f'<rect x="{x}" y="{y}" width="{BW}" height="{BH}" rx="12" fill="{SURFACE}" stroke="{stroke}" stroke-width="1.6"/>')126            parts.append(f'<text x="{x + BW / 2}" y="{y + (27 if line2 else 36)}" text-anchor="middle" fill="{FG}" font-family="-apple-system,Helvetica,Arial,sans-serif" font-size="14" font-weight="600">{escape(line1)}</text>')127            if line2:128                parts.append(f'<text x="{x + BW / 2}" y="{y + 46}" text-anchor="middle" fill="{MUTED}" font-family="-apple-system,Helvetica,Arial,sans-serif" font-size="11.5">{escape(line2)}</text>')129    for a in arrows:130        src, dst, label = (a + ("",))[:3]131        (x1, y1), (x2, y2) = pos[src], pos[dst]132        if abs(y1 - y2) < 1:                                   # same row133            if x2 > x1: p = (x1 + BW, y1 + BH / 2, x2 - 3, y2 + BH / 2)134            else: p = (x1, y1 + BH / 2, x2 + BW + 3, y2 + BH / 2)135        elif y2 > y1: p = (x1 + BW / 2, y1 + BH, x2 + BW / 2, y2 - 3)136        else: p = (x1 + BW / 2, y1, x2 + BW / 2, y2 + BH + 3)137        parts.append(f'<line x1="{p[0]}" y1="{p[1]}" x2="{p[2]}" y2="{p[3]}" stroke="{MUTED}" stroke-width="1.5" marker-end="url(#a)"/>')138        if label:139            mx, my = (p[0] + p[2]) / 2, (p[1] + p[3]) / 2140            parts.append(f'<text x="{mx + (0 if abs(y1 - y2) < 1 else 8)}" y="{my - (7 if abs(y1 - y2) < 1 else -4)}" text-anchor="{"middle" if abs(y1 - y2) < 1 else "start"}" fill="{CYAN}" font-family="-apple-system,Helvetica,Arial,sans-serif" font-size="11">{escape(label)}</text>')141    ny = y0 + len(rows) * BH + (len(rows) - 1) * GY + 30142    for i, note in enumerate(notes):143        parts.append(f'<text x="{PAD}" y="{ny + i * 24}" fill="{MUTED}" font-family="-apple-system,Helvetica,Arial,sans-serif" font-size="12.5">{escape(note)}</text>')144    parts.append('</svg>')145    (OUT / f"{name}.svg").write_text("\n".join(parts) + "\n")146147diagram("capture-pipeline", "Audio capture pipeline", [148    [("mic", "Audio input", "AVAudioEngine input node", "c"), ("tap", "Tap block", "copy only, no I/O", "c"), ("wr", "Writer ring", "SPSC, 4 s, wait-free", "n"), ("wt", "Writer thread", "fsync every 2 s", "v")],149    [None, None, ("ar", "Analysis ring", "SPSC, 2 s, mono mix", "n"), ("caf", "CAF master", "PCM, data size −1", "v")],150    [None, None, ("at", "Analysis thread", "DSP for visuals", "c"), ("fin", "Finalizer", "encode + verify", "v")],151    [None, None, ("vis", "LiveVisuals", "mutex-protected store", "n"), ("lib", "Library file", "WAV / ALAC / AAC", "v")],152], [("mic", "tap"), ("tap", "wr"), ("wr", "wt"), ("wt", "caf"), ("caf", "fin", "on stop"), ("fin", "lib"), ("tap", "ar"), ("ar", "at"), ("at", "vis")],153    ["The tap never blocks: when a ring is full the excess is counted as dropped and reported in the UI.",154     "A slow UI or FFT cannot delay a write; a slow disk cannot block the tap."])155156diagram("realtime-dsp", "Real-time analysis thread", [157    [("ring", "Analysis ring", "mono chunks ≤ 8192", "n"), ("recent", "Sliding window", "last 32 768 samples", "n"), ("spec", "SpectrumAnalyzer", "FFT, smoothing, peak hold", "c")],158    [("wave", "WaveformProcessor", "min / max / RMS + 7 bands", "c"), ("stft", "SpectrogramProcessor", "1024-point STFT, hop 512", "c"), ("loud", "LoudnessMeter", "momentary LUFS", "v")],159    [("lvl", "Level meter", "peak, RMS, hold, clip", "v"), ("store", "LiveVisuals", "bounded history", "n"), ("ui", "SwiftUI timeline", "reads at display rate", "c")],160], [("ring", "recent"), ("recent", "spec"), ("ring", "wave"), ("wave", "store"), ("stft", "store"), ("lvl", "store"), ("store", "ui")],161    ["Analysis rate follows the audio (about 30–90 updates per second); display rate follows the screen. Neither waits for the other.",162     "History is bounded: 8192 waveform buckets and 1024 spectrogram columns."])163164diagram("waveform-rendering", "Waveform rendering", [165    [("pcm", "PCM samples", "live or file", "n"), ("bucket", "512-sample bucket", "min, max, RMS (exact)", "c"), ("fft", "4096-point Hann FFT", "window ends at the bucket", "c")],166    [("bands", "7 band powers", "sum of bins ÷ ENBW", "v"), ("pyr", "Pyramid", "each level halves resolution", "n"), ("cache", "waveform.owf", "40 bytes per bucket", "n")],167    [("pick", "Level selection", "≥ one bucket per bar", "n"), ("rebin", "Re-bin to bars", "min of mins, max of maxes", "c"), ("draw", "Canvas", "4 styles, 3 pt bars", "v")],168], [("pcm", "bucket"), ("bucket", "fft"), ("fft", "bands"), ("bands", "pyr"), ("pyr", "cache"), ("pyr", "pick"), ("pick", "rebin"), ("rebin", "draw")],169    ["A bar's colour is the amplitude-weighted mix of the seven band colours measured for that moment — never a decoration.",170     "The “band shares” style draws the same measurement as stacked segments, readable without colour vision."])171172diagram("spectrogram-tiles", "Spectrogram tile processing", [173    [("zoom", "Visible time range", "seconds per point", "n"), ("level", "Level L", "hop = fft/4 · 2^L", "c"), ("keys", "Tile keys", "256 columns each", "n")],174    [("read", "Read mono range", "chunks of 262 144 frames", "n"), ("stft", "STFT", "hop ≤ one FFT length", "c"), ("pool", "Max-pool columns", "no audio skipped", "v")],175    [("cache", "Tile cache", "28 tiles of dB values", "n"), ("lut", "Palette LUT", "256 entries, dB → colour", "c"), ("img", "CGImage tile", "drawn in Canvas", "v")],176], [("zoom", "level"), ("level", "keys"), ("keys", "read"), ("read", "stft"), ("stft", "pool"), ("pool", "cache"), ("cache", "lut"), ("lut", "img")],177    ["Only the tiles on screen are computed, so a multi-hour file is never analysed or held in memory as a whole.",178     "Changing palette or dB range re-rasterises cached dB values; it does not recompute the STFT."])179180diagram("transcription", "On-device transcription", [181    [("file", "Audio file", "recording or import", "n"), ("path", "Path check", "per locale, at run time", "c"), ("st", "SpeechTranscriber", "SpeechAnalyzer module", "c")],182    [("dl", "Model download", "only when the user agrees", "n"), ("legacy", "SFSpeechRecognizer", "requiresOnDeviceRecognition", "v"), ("none", "Unavailable", "explained, never uploaded", "n")],183    [("runs", "Timed runs", "audioTimeRange per run", "c"), ("seg", "Segments", "sentence / 14 s breaks", "c"), ("json", "transcript.json", "editable, searchable", "v")],184], [("file", "path"), ("path", "st", "installed"), ("path", "legacy", "fallback"), ("st", "runs"), ("runs", "seg"), ("seg", "json")],185    ["There is no server path. If neither on-device recogniser can serve the locale, the app says so and stops.",186     "Downloading a speech model transfers a model to the device; audio is never sent anywhere."])187188diagram("foundation-models", "Meeting intelligence: map → verify → reduce", [189    [("tr", "Transcript", "numbered lines [n]", "n"), ("chunk", "Chunks", "≤ 4200 characters", "n"), ("map", "Section notes", "guided generation", "c")],190    [("cite", "Cited line n", "per point, action, decision", "c"), ("verify", "Verification", "line exists + shared words", "v"), ("flag", "Unverified", "shown separately", "n")],191    [("owner", "Owner check", "name must be in transcript", "v"), ("reduce", "Overview", "from section summaries", "c"), ("notes", "notes.json", "labelled AI, editable", "v")],192], [("tr", "chunk"), ("chunk", "map"), ("map", "cite"), ("cite", "verify"), ("verify", "flag", "fails"), ("verify", "owner"), ("owner", "reduce"), ("reduce", "notes")],193    ["The language model only reads recognised text; it never hears audio. On context overflow a chunk is split in two and retried.",194     "Questions use the same rule: an answer without a valid cited line is reported as “not answered by the transcript”."])195196diagram("storage-layout", "Recording storage layout", [197    [("root", "Application Support", "ORIXAudio/", "n"), ("rec", "Recordings/<uuid>/", "one folder per recording", "c"), ("audio", "audio.<ext>", "the library file", "v")],198    [("cap", "Capture/", "<uuid>.caf + <uuid>.json", "v"), ("side", "Sidecars", "waveform.owf, analysis.json", "n"), ("text", "Text sidecars", "transcript, notes, edit.json", "n")],199    [("db", "SwiftData store", "metadata, folders, workflows", "c"), ("exp", "tmp/Exports/", "purged at launch", "n"), ("prot", "File protection", "until first unlock", "v")],200], [("root", "rec"), ("rec", "audio"), ("root", "cap"), ("rec", "side"), ("side", "text"), ("root", "db")],201    ["Protection class “complete until first user authentication” keeps files writable while the device is locked.",202     "Sidecars are written atomically; deleting a recording removes its whole folder."])203204diagram("background-lifecycle", "Background recording lifecycle", [205    [("idle", "Idle", "", "n"), ("rec", "Recording", "session .playAndRecord", "c"), ("paused", "Paused", "tap discards audio", "n")],206    [("int", "Interrupted", "call, alarm, other app", "v"), ("locked", "Locked / background", "UIBackgroundModes audio", "c"), ("fin", "Finishing", "drain, close, encode", "v")],207    [("crash", "Process ended", "kill, crash, power loss", "v"), ("recover", "Recovery offer", "next launch", "c"), ("saved", "In the library", "verified file", "v")],208], [("idle", "rec", "start"), ("rec", "paused", "pause"), ("rec", "int", "system"), ("rec", "locked"), ("paused", "fin", "stop"), ("fin", "saved"), ("int", "crash"), ("crash", "recover"), ("recover", "saved", "finalize")],209    ["Interrupted → Recording when iOS signals “should resume”, otherwise on the user's tap. A marker records each interruption.",210     "The master is a valid CAF file after every write, so whatever reached the disk (fsync every 2 s) is recoverable."])211print("8 diagrams written")212
Files main
Menu

Theme