diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83aecc5..d2fab82 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,8 +10,21 @@ permissions: contents: read jobs: - build: + mac: runs-on: macos-26 steps: - uses: actions/checkout@v6 - run: swift build + working-directory: mac + mobile: + runs-on: macos-26 + steps: + - uses: actions/checkout@v6 + - run: brew install xcodegen + - run: make gen + working-directory: mobile + - run: >- + xcodebuild -project steno-mobile.xcodeproj -scheme steno-mobile + -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' + CODE_SIGNING_ALLOWED=NO build + working-directory: mobile diff --git a/.gitignore b/.gitignore index 0f693e2..f81ce98 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,13 @@ -/.build/ -/*.app/ +# Swift / Xcode build output(mac / Core / mobile どこでも) +.build/ +*.app/ +DerivedData/ +*.xcuserstate + +# xcodegen 生成物(mobile。project.yml が SSOT) +*.xcodeproj/ +Generated/ + +# example-server の実行時ログ(受信した文字起こし。個人データなので追跡しない) +received.jsonl +**/received.jsonl diff --git a/Core/Package.swift b/Core/Package.swift new file mode 100644 index 0000000..2b4a26a --- /dev/null +++ b/Core/Package.swift @@ -0,0 +1,26 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// StenoCore — mac / mobile 両アプリで共有する、プラットフォーム非依存の ASR + 話者分離エンジン。 +// - Transcriber Apple SpeechAnalyzer ラッパ(確定発話を onFinal で流す) +// - SpeakerSegmenter Streaming Sortformer(FluidAudio)で話者ターン境界を検出 +// - BufferConverter SpeechAnalyzer が要求する format への PCM 変換(内部) +// capture 層・writer・UI はプラットフォーム固有なので各アプリに残す。ここは「音を食って +// 確定発話と話者境界を出す」ところまで。両アプリで完全に同一の部分だけを抽出している。 +let package = Package( + name: "StenoCore", + platforms: [.macOS("26.0"), .iOS("26.0")], + products: [ + .library(name: "StenoCore", targets: ["StenoCore"]) + ], + dependencies: [ + .package(url: "https://github.com/FluidInference/FluidAudio.git", from: "0.12.4") + ], + targets: [ + .target( + name: "StenoCore", + dependencies: [.product(name: "FluidAudio", package: "FluidAudio")], + path: "Sources/StenoCore" + ) + ] +) diff --git a/Sources/steno/BufferConversion.swift b/Core/Sources/StenoCore/BufferConverter.swift similarity index 100% rename from Sources/steno/BufferConversion.swift rename to Core/Sources/StenoCore/BufferConverter.swift diff --git a/Core/Sources/StenoCore/Log.swift b/Core/Sources/StenoCore/Log.swift new file mode 100644 index 0000000..7f5bd32 --- /dev/null +++ b/Core/Sources/StenoCore/Log.swift @@ -0,0 +1,19 @@ +import Foundation +import os + +/// Core エンジンのログ。既定は os.Logger へ出す。アプリが `sink` を刺すと、そちらにも流す +/// (mac は steno.log の StenoLog へ橋渡しして、エンジンのログも従来どおりファイルに残す)。 +/// sink は起動直後に一度だけ設定する前提。 +public enum StenoCoreLog { + nonisolated(unsafe) public static var sink: (@Sendable (String) -> Void)? + static let logger = Logger(subsystem: "com.m5d215.steno.core", category: "engine") +} + +func ilog(_ message: String) { + StenoCoreLog.logger.info("\(message, privacy: .public)") + StenoCoreLog.sink?(message) +} + +func dlog(_ message: String) { + StenoCoreLog.logger.debug("\(message, privacy: .public)") +} diff --git a/Sources/steno/SpeakerSegmenter.swift b/Core/Sources/StenoCore/SpeakerSegmenter.swift similarity index 96% rename from Sources/steno/SpeakerSegmenter.swift rename to Core/Sources/StenoCore/SpeakerSegmenter.swift index 1cd884e..76bc560 100644 --- a/Sources/steno/SpeakerSegmenter.swift +++ b/Core/Sources/StenoCore/SpeakerSegmenter.swift @@ -13,7 +13,7 @@ import Foundation /// - thread-safety: SortformerDiarizer は **non thread-safe**。audio callback(Core Audio /// スレッド)から直接触らず、専用 serial queue 上でのみアクセスする。feed() は float 抽出だけ /// audio スレッドで行い、推論は queue に逃がす(audio render を CoreML 推論でブロックしない)。 -final class SpeakerSegmenter: @unchecked Sendable { +public final class SpeakerSegmenter: @unchecked Sendable { private let onTurnBoundary: @Sendable () -> Void private let queue = DispatchQueue(label: "com.m5d215.steno.diar", qos: .userInitiated) @@ -34,13 +34,13 @@ final class SpeakerSegmenter: @unchecked Sendable { /// 代償: これ未満の本物の短いターンも merge される(区切りの目的には許容)。tunable。 private let minCutInterval: TimeInterval = 1.5 - init(onTurnBoundary: @escaping @Sendable () -> Void) { + public init(onTurnBoundary: @escaping @Sendable () -> Void) { self.onTurnBoundary = onTurnBoundary } /// モデルを HuggingFace(初回のみ download、以降 cache)から読み込んで初期化する。async。 /// load 所要を ilog に出す(cache 済みで ~1.3s)。失敗は呼び出し側で catch され、素の動作に縮退する。 - func start(config: SortformerConfig = .default) async throws { + public func start(config: SortformerConfig = .default) async throws { let t0 = Date() let models = try await SortformerModels.loadFromHuggingFace( config: config, computeUnits: .cpuAndGPU) @@ -51,7 +51,7 @@ final class SpeakerSegmenter: @unchecked Sendable { } /// audio callback(Core Audio スレッド)から同期で呼ばれる。mono float を抜いて queue に渡す。 - func feed(_ buffer: AVAudioPCMBuffer) { + public func feed(_ buffer: AVAudioPCMBuffer) { guard let ch = buffer.floatChannelData else { return } let n = Int(buffer.frameLength) guard n > 0 else { return } diff --git a/Sources/steno/Transcriber.swift b/Core/Sources/StenoCore/Transcriber.swift similarity index 91% rename from Sources/steno/Transcriber.swift rename to Core/Sources/StenoCore/Transcriber.swift index c8696cc..09cb79e 100644 --- a/Sources/steno/Transcriber.swift +++ b/Core/Sources/StenoCore/Transcriber.swift @@ -8,7 +8,7 @@ import Speech /// /// App Nap は SpeechAnalyzer を wedge させる(音声は来るのに確定発話が出ない)。これは UI 形態 /// ではなく AppController 側の ProcessInfo.beginActivity で nap を明示的に抑止して対処する。 -final class Transcriber: @unchecked Sendable { +public final class Transcriber: @unchecked Sendable { private let locale: Locale private let label: String private let contextualStrings: [String] @@ -23,7 +23,7 @@ final class Transcriber: @unchecked Sendable { private var recognizerTask: Task? private var streamCount = 0 - init( + public init( locale: Locale, label: String, contextualStrings: [String] = [], onFinal: @escaping @Sendable (String, Date) -> Void @@ -34,7 +34,7 @@ final class Transcriber: @unchecked Sendable { self.onFinal = onFinal } - func start() async throws { + public func start() async throws { // volatile(中間仮説)は使わない(finals のみ消費)ので要求しない。話者ターン区切りは // Sortformer を別途並走させ finalize(through:) で切る方式なので、SpeechAnalyzer 側の // audioTimeRange(token 毎の経過秒区間)も要らない。 @@ -94,7 +94,7 @@ final class Transcriber: @unchecked Sendable { /// SpeakerSegmenter が話者ターン境界を検出したときにこれを呼び、長い掛け合いが 1 つの final に /// merge されるのを防ぐ(発話を話者の切れ目で区切る)。確定発話は ~100ms 後に results へ publish される。 /// `through: nil` = 「最後に consume した音声まで」確定(未 consume なら何もしない)。 - func finalizeThroughLatest() async { + public func finalizeThroughLatest() async { guard let analyzer else { return } do { try await analyzer.finalize(through: nil) @@ -103,8 +103,19 @@ final class Transcriber: @unchecked Sendable { } } + /// 入力を締めてセッションを終える。stop 時に呼ぶ(mac は破棄で足りるので任意)。 + public func finish() async { + inputBuilder?.finish() + recognizerTask?.cancel() + if let analyzer { + try? await analyzer.finalizeAndFinishThroughEndOfInput() + } + analyzer = nil + transcriber = nil + } + /// audio queue から同期で呼ばれる。AsyncStream.Continuation.yield は thread-safe。 - func stream(_ buffer: AVAudioPCMBuffer) { + public func stream(_ buffer: AVAudioPCMBuffer) { streamCount += 1 guard let analyzerFormat, let inputBuilder else { dlog("[Transcriber:\(label)] stream: not ready") diff --git a/README.md b/README.md index 6e0777a..ebb1dce 100644 --- a/README.md +++ b/README.md @@ -1,117 +1,41 @@ # steno -macOS 用の常時オンデバイス文字起こしツール。システム音声(通話相手)とマイク(自分)を同時に -聞き取り、会話をほぼリアルタイムで JSON Lines に書き続ける。 +常時オンデバイス文字起こし。macOS と iOS の 2 アプリが、共有エンジンの上に載る monorepo。 -**音声は一切外に出ない。** 取得・認識・書き出しは全てローカル。ネットワークを使うのは -オンデバイスモデル(Apple 音声認識・話者分離)の初回ダウンロードのみ。サーバもアカウントも -テレメトリも無い。 +**音声は端末の外に出ない。** 取得も認識も Apple のオンデバイス `SpeechAnalyzer` でローカル完結する。 -## 仕組み +## 構成 -```mermaid -flowchart LR - sys[システム音声] -->|Core Audio process tap| asr - sys -->|並走| diar["Sortformer
話者ターン境界検出"] - mic[マイク] -->|AVCaptureSession| asr - diar -->|境界で finalize| asr - asr["SpeechAnalyzer
オンデバイス・ja_JP"] --> file[(daily .jsonl)] - asr --> win[ライブ窓表示] -``` - -- **システム音声** — Core Audio process tap(ScreenCaptureKit ではない)。video pipeline も - `replayd` も持たず、それ起因のハングや無音化が無い。 -- **マイク** — 特定デバイスに固定した `AVCaptureSession`。システム既定の入力が切り替わっても - (イヤホン接続など)選んだマイクで録り続ける。 -- **話者の区別**は **source**(`system`=相手 / `mic`=自分)で取る。さらに system 側のミックス内に - 複数話者がいる場合、Streaming Sortformer(FluidAudio / CoreML)で**話者が変わった点を検出して - 発話を区切る**。掛け合いが 1 行に merge されて意味を失うのを防ぐのが目的で、話者の特定(誰か)は - しない(ラベルは付けない)。`STENO_DIAR=0` で無効化できる。 - -## 要件 - -- **macOS 26.0+**(`SpeechAnalyzer` と Core Audio process tap) -- **Apple Silicon** -- Swift 6 ツールチェイン(Xcode 26 / Command Line Tools) - -## ビルドとインストール - -```sh -make build # → ./steno.app -make install # → ~/Applications/steno.app -``` - -インストール後は `~/Applications` から起動する。初回に **マイク / 音声認識 / 音声キャプチャ** の -許可を求められる(いずれも「音声は外部送信しない」と明記)。 - -**署名**: Apple Development / Developer ID 証明書があればそれで、無ければ ad-hoc 署名になる。macOS -は許可(TCC)を署名単位で管理するため、ad-hoc だと再ビルドごとに許可がリセットされる。頻繁に -ビルドし直すなら自分の証明書で署名すると永続する。 - -## 使い方 - -- 窓にライブの文字起こし(時刻・`system`/`mic` バッジ・system は再生元アプリ名)。 -- **マイク** ドロップダウンで入力デバイスを選択(記憶され、既定が変わっても固定)。 -- **リセット** で再起動せずキャプチャを作り直す。 - -文字起こしは `~/.config/steno/transcripts/YYYY-MM-DD.jsonl` (ローカル日付)に追記される。 - -## 出力フォーマット - -確定発話ごとに JSON 1 行。steno(書く)と後段(読む)の唯一の契約面: - -```json -{"ts":"2026-06-16T15:28:06.186+09:00","epoch":1781591286.18,"isFinal":true,"seq":7,"source":"system","app":"Microsoft Teams","text":"…"} -``` - -| キー | 意味 | +| ディレクトリ | 中身 | |---|---| -| `ts` / `epoch` | ISO 8601 ローカル時刻 / Unix 秒 | -| `isFinal` | 常に `true`(確定発話のみ書く) | -| `seq` | ファイル内通し番号(日付替わり / 起動でリセット) | -| `source` | `system`(相手)/ `mic`(自分) | -| `app` | system のみ: 出力中だったアプリ名 | -| `text` | 文字起こしテキスト | - -スキーマは話者分離の有無で変わらない(話者ラベルは持たない)。ただし `source=system` の発話は -話者が変わった点で区切られるため、複数話者の掛け合いは 1 行に merge されず、話者ターンごとに -別の行(別 `seq`)として並ぶ。 +| [`mac/`](mac/README.md) | macOS 常駐版。システム音声(Core Audio process tap)+マイクを聞き、会話を JSON Lines に書き続ける | +| [`mobile/`](mobile/README.md) | iOS 版。マイク一本の環境音を書き起こし、ローカル記録しつつ Tailscale 越しに指定サーバへリアルタイム POST する | +| `Core/` | 共有エンジン `StenoCore`。両アプリで同一の「音を食って確定発話と話者境界を出す」部分だけを抽出 | -## 設定 +## Core が持つもの / 持たないもの -環境変数(`Info.plist` の `LSEnvironment` で指定): +`Core/`(StenoCore)は**プラットフォーム非依存のエンジンだけ**: -| 変数 | 意味 | -|---|---| -| `STENO_DIR` | 基準ディレクトリ(既定 `~/.config/steno`) | -| `TRANSCRIPT_DIR` | 出力先のみ(既定 `STENO_DIR/transcripts`) | -| `STENO_VOCAB` | 認識ヒント語彙ファイル | -| `STENO_DIAR=0` | system の話者ターン区切りを無効化(既定は有効) | -| `STENO_DEBUG=1` | 詳細ログ | +- `Transcriber` — SpeechAnalyzer ラッパ(確定発話を `onFinal` で流す) +- `SpeakerSegmenter` — Streaming Sortformer(FluidAudio)で話者ターン境界を検出(区切りであってラベル付けではない) +- `BufferConverter` — SpeechAnalyzer 用の PCM format 変換(内部) -**語彙ヒント**: 固有名詞・専門用語(1 行 1 語、`#` でコメント)を `~/.config/steno/vocabulary.txt` -に置くと認識ヒント(contextual strings)として渡され、一般モデルが崩す名前や用語が当たるように -なる。再起動で反映。 +capture 層・writer・UI・転送はプラットフォームで別物なので**各アプリに残す**。境界を「純粋なエンジン」に絞ることで `#if os(...)` の氾濫を避けている。両アプリは `Core` を local package として依存する(mac は SwiftPM path 依存、mobile は xcodegen の local package)。 -## ログ +## ビルド -`~/.config/steno/` に出力する: +各アプリのディレクトリで: -- `steno.log` — 時刻付きの重要イベント(起動・復旧・エラー)。**まずここを見る** -- `stdout.log` / `stderr.log` — 生の標準出力 / 標準エラー(フレームワーク警告やクラッシュ直前の出力まで)。各 1 世代ローテート +```sh +# macOS +cd mac && make build # → mac/steno.app -## 既知の制限 +# iOS +cd mobile && make open # Xcode で開いて実機 run(署名は Team 設定済み) +cd mobile && make build # シミュレータ向けにコンパイル確認 +``` -- **確定までのレイテンシ**は長い発話で数十秒(瞬時ではない)。話者ターン区切りはこれを能動的に - 短縮もする(境界で finalize するため)。 -- **`ja_JP` 専用**(ロケール固定)。他言語は `AppController.swift` のロケールを書き換える -- **話者ターン区切りの粗さ** — 境界検出に ~1s の遅延があり、次話者の冒頭 ~1s が前の行にこぼれる - ことがある。また相槌(「はい」等)の高速な応酬では切りすぎて短い行が増える。区切りの目的(掛け合いを - 分離して意味を保つ)には十分だが、行境界は厳密ではない。 -- **話者分離の同時話者数**は内部モデル上 4。超えても**区切り**は機能する(5 人目が既存スロットに - 寄っても遷移は拾える)が、ラベル相当の分離精度は 4 人想定。 -- 初回起動時のみ話者分離モデル(`FluidInference/diar-streaming-sortformer-coreml`)をダウンロードする - (以降はローカルキャッシュ)。ダウンロードに失敗しても素の文字起こしに縮退して動き続ける。 +詳細は各サブディレクトリの README を見る。 ## ライセンス diff --git a/Info.plist b/mac/Info.plist similarity index 100% rename from Info.plist rename to mac/Info.plist diff --git a/Makefile b/mac/Makefile similarity index 100% rename from Makefile rename to mac/Makefile diff --git a/Package.resolved b/mac/Package.resolved similarity index 100% rename from Package.resolved rename to mac/Package.resolved diff --git a/Package.swift b/mac/Package.swift similarity index 82% rename from Package.swift rename to mac/Package.swift index d20d1b4..afa8eba 100644 --- a/Package.swift +++ b/mac/Package.swift @@ -15,16 +15,19 @@ import PackageDescription // 目的は話者特定ではなく区切りなのでラベル精度は問わない。ANE は SpeechAnalyzer×2 が握るため // diarizer の compute units は ANE を外す(.cpuAndGPU)。 // - メニューバーではなく窓 UI。App Nap は ProcessInfo.beginActivity で明示的に抑止する +// +// ASR + 話者分離のエンジン(Transcriber / SpeakerSegmenter / BufferConverter)は ../Core の +// StenoCore に切り出して mobile と共有する。ここには capture / writer / UI / 認可 など macOS 固有部のみ。 let package = Package( name: "steno", platforms: [.macOS("26.0")], dependencies: [ - .package(url: "https://github.com/FluidInference/FluidAudio.git", from: "0.12.4") + .package(path: "../Core") ], targets: [ .executableTarget( name: "steno", - dependencies: [.product(name: "FluidAudio", package: "FluidAudio")], + dependencies: [.product(name: "StenoCore", package: "Core")], path: "Sources/steno" ) ] diff --git a/mac/README.md b/mac/README.md new file mode 100644 index 0000000..6e0777a --- /dev/null +++ b/mac/README.md @@ -0,0 +1,118 @@ +# steno + +macOS 用の常時オンデバイス文字起こしツール。システム音声(通話相手)とマイク(自分)を同時に +聞き取り、会話をほぼリアルタイムで JSON Lines に書き続ける。 + +**音声は一切外に出ない。** 取得・認識・書き出しは全てローカル。ネットワークを使うのは +オンデバイスモデル(Apple 音声認識・話者分離)の初回ダウンロードのみ。サーバもアカウントも +テレメトリも無い。 + +## 仕組み + +```mermaid +flowchart LR + sys[システム音声] -->|Core Audio process tap| asr + sys -->|並走| diar["Sortformer
話者ターン境界検出"] + mic[マイク] -->|AVCaptureSession| asr + diar -->|境界で finalize| asr + asr["SpeechAnalyzer
オンデバイス・ja_JP"] --> file[(daily .jsonl)] + asr --> win[ライブ窓表示] +``` + +- **システム音声** — Core Audio process tap(ScreenCaptureKit ではない)。video pipeline も + `replayd` も持たず、それ起因のハングや無音化が無い。 +- **マイク** — 特定デバイスに固定した `AVCaptureSession`。システム既定の入力が切り替わっても + (イヤホン接続など)選んだマイクで録り続ける。 +- **話者の区別**は **source**(`system`=相手 / `mic`=自分)で取る。さらに system 側のミックス内に + 複数話者がいる場合、Streaming Sortformer(FluidAudio / CoreML)で**話者が変わった点を検出して + 発話を区切る**。掛け合いが 1 行に merge されて意味を失うのを防ぐのが目的で、話者の特定(誰か)は + しない(ラベルは付けない)。`STENO_DIAR=0` で無効化できる。 + +## 要件 + +- **macOS 26.0+**(`SpeechAnalyzer` と Core Audio process tap) +- **Apple Silicon** +- Swift 6 ツールチェイン(Xcode 26 / Command Line Tools) + +## ビルドとインストール + +```sh +make build # → ./steno.app +make install # → ~/Applications/steno.app +``` + +インストール後は `~/Applications` から起動する。初回に **マイク / 音声認識 / 音声キャプチャ** の +許可を求められる(いずれも「音声は外部送信しない」と明記)。 + +**署名**: Apple Development / Developer ID 証明書があればそれで、無ければ ad-hoc 署名になる。macOS +は許可(TCC)を署名単位で管理するため、ad-hoc だと再ビルドごとに許可がリセットされる。頻繁に +ビルドし直すなら自分の証明書で署名すると永続する。 + +## 使い方 + +- 窓にライブの文字起こし(時刻・`system`/`mic` バッジ・system は再生元アプリ名)。 +- **マイク** ドロップダウンで入力デバイスを選択(記憶され、既定が変わっても固定)。 +- **リセット** で再起動せずキャプチャを作り直す。 + +文字起こしは `~/.config/steno/transcripts/YYYY-MM-DD.jsonl` (ローカル日付)に追記される。 + +## 出力フォーマット + +確定発話ごとに JSON 1 行。steno(書く)と後段(読む)の唯一の契約面: + +```json +{"ts":"2026-06-16T15:28:06.186+09:00","epoch":1781591286.18,"isFinal":true,"seq":7,"source":"system","app":"Microsoft Teams","text":"…"} +``` + +| キー | 意味 | +|---|---| +| `ts` / `epoch` | ISO 8601 ローカル時刻 / Unix 秒 | +| `isFinal` | 常に `true`(確定発話のみ書く) | +| `seq` | ファイル内通し番号(日付替わり / 起動でリセット) | +| `source` | `system`(相手)/ `mic`(自分) | +| `app` | system のみ: 出力中だったアプリ名 | +| `text` | 文字起こしテキスト | + +スキーマは話者分離の有無で変わらない(話者ラベルは持たない)。ただし `source=system` の発話は +話者が変わった点で区切られるため、複数話者の掛け合いは 1 行に merge されず、話者ターンごとに +別の行(別 `seq`)として並ぶ。 + +## 設定 + +環境変数(`Info.plist` の `LSEnvironment` で指定): + +| 変数 | 意味 | +|---|---| +| `STENO_DIR` | 基準ディレクトリ(既定 `~/.config/steno`) | +| `TRANSCRIPT_DIR` | 出力先のみ(既定 `STENO_DIR/transcripts`) | +| `STENO_VOCAB` | 認識ヒント語彙ファイル | +| `STENO_DIAR=0` | system の話者ターン区切りを無効化(既定は有効) | +| `STENO_DEBUG=1` | 詳細ログ | + +**語彙ヒント**: 固有名詞・専門用語(1 行 1 語、`#` でコメント)を `~/.config/steno/vocabulary.txt` +に置くと認識ヒント(contextual strings)として渡され、一般モデルが崩す名前や用語が当たるように +なる。再起動で反映。 + +## ログ + +`~/.config/steno/` に出力する: + +- `steno.log` — 時刻付きの重要イベント(起動・復旧・エラー)。**まずここを見る** +- `stdout.log` / `stderr.log` — 生の標準出力 / 標準エラー(フレームワーク警告やクラッシュ直前の出力まで)。各 1 世代ローテート + +## 既知の制限 + +- **確定までのレイテンシ**は長い発話で数十秒(瞬時ではない)。話者ターン区切りはこれを能動的に + 短縮もする(境界で finalize するため)。 +- **`ja_JP` 専用**(ロケール固定)。他言語は `AppController.swift` のロケールを書き換える +- **話者ターン区切りの粗さ** — 境界検出に ~1s の遅延があり、次話者の冒頭 ~1s が前の行にこぼれる + ことがある。また相槌(「はい」等)の高速な応酬では切りすぎて短い行が増える。区切りの目的(掛け合いを + 分離して意味を保つ)には十分だが、行境界は厳密ではない。 +- **話者分離の同時話者数**は内部モデル上 4。超えても**区切り**は機能する(5 人目が既存スロットに + 寄っても遷移は拾える)が、ラベル相当の分離精度は 4 人想定。 +- 初回起動時のみ話者分離モデル(`FluidInference/diar-streaming-sortformer-coreml`)をダウンロードする + (以降はローカルキャッシュ)。ダウンロードに失敗しても素の文字起こしに縮退して動き続ける。 + +## ライセンス + +MIT — [LICENSE](LICENSE)。 diff --git a/Sources/steno/AppController.swift b/mac/Sources/steno/AppController.swift similarity index 99% rename from Sources/steno/AppController.swift rename to mac/Sources/steno/AppController.swift index 1f2da5f..f79d68b 100644 --- a/Sources/steno/AppController.swift +++ b/mac/Sources/steno/AppController.swift @@ -2,6 +2,7 @@ import AVFoundation import AppKit import Foundation import Speech +import StenoCore import os /// UI 表示用の 1 行。jsonl とは別に、確定発話を in-process でそのまま UI へ流すための型。 diff --git a/Sources/steno/AudioDevices.swift b/mac/Sources/steno/AudioDevices.swift similarity index 100% rename from Sources/steno/AudioDevices.swift rename to mac/Sources/steno/AudioDevices.swift diff --git a/Sources/steno/AudioTapCapturer.swift b/mac/Sources/steno/AudioTapCapturer.swift similarity index 100% rename from Sources/steno/AudioTapCapturer.swift rename to mac/Sources/steno/AudioTapCapturer.swift diff --git a/Sources/steno/Debug.swift b/mac/Sources/steno/Debug.swift similarity index 100% rename from Sources/steno/Debug.swift rename to mac/Sources/steno/Debug.swift diff --git a/Sources/steno/MicCapturer.swift b/mac/Sources/steno/MicCapturer.swift similarity index 100% rename from Sources/steno/MicCapturer.swift rename to mac/Sources/steno/MicCapturer.swift diff --git a/Sources/steno/OutputProcesses.swift b/mac/Sources/steno/OutputProcesses.swift similarity index 100% rename from Sources/steno/OutputProcesses.swift rename to mac/Sources/steno/OutputProcesses.swift diff --git a/Sources/steno/StenoApp.swift b/mac/Sources/steno/StenoApp.swift similarity index 96% rename from Sources/steno/StenoApp.swift rename to mac/Sources/steno/StenoApp.swift index e5fed93..c66c5c9 100644 --- a/Sources/steno/StenoApp.swift +++ b/mac/Sources/steno/StenoApp.swift @@ -1,4 +1,5 @@ import Combine +import StenoCore import SwiftUI /// steno — 常時ローカルで聞いて、喋りを話者付きで書き起こし続ける macOS アプリ。 @@ -7,7 +8,11 @@ import SwiftUI struct StenoApp: App { // 何よりも先に stdout/stderr をファイルへ張り替える(GUI 起動でも生ログを残すため)。 // @StateObject の AppController() は autoclosure で遅延生成されるので、ここが最初に走る。 - init() { redirectStandardStreams() } + init() { + redirectStandardStreams() + // Core(StenoCore)エンジンのログも steno.log へ流す。従来 mac の firehose を保つ。 + StenoCoreLog.sink = { StenoLog.shared.write($0) } + } @StateObject private var controller = AppController() diff --git a/Sources/steno/TranscriptWriter.swift b/mac/Sources/steno/TranscriptWriter.swift similarity index 100% rename from Sources/steno/TranscriptWriter.swift rename to mac/Sources/steno/TranscriptWriter.swift diff --git a/icon/AppIcon.icns b/mac/icon/AppIcon.icns similarity index 100% rename from icon/AppIcon.icns rename to mac/icon/AppIcon.icns diff --git a/icon/make-icon.swift b/mac/icon/make-icon.swift similarity index 100% rename from icon/make-icon.swift rename to mac/icon/make-icon.swift diff --git a/mobile/Makefile b/mobile/Makefile new file mode 100644 index 0000000..d5237df --- /dev/null +++ b/mobile/Makefile @@ -0,0 +1,21 @@ +PROJECT := steno-mobile.xcodeproj +SCHEME := steno-mobile + +.PHONY: gen build sim open clean + +# project.yml から .xcodeproj を生成(SSOT は project.yml)。 +gen: + xcodegen generate + +# シミュレータ向けにビルド(署名不要。コンパイルが通るかの確認用)。 +build: gen + xcodebuild -project $(PROJECT) -scheme $(SCHEME) \ + -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \ + -derivedDataPath DerivedData build + +# Xcode で開く(実機ビルド/署名は Xcode で Team を設定して行う)。 +open: gen + open $(PROJECT) + +clean: + rm -rf DerivedData $(PROJECT) Generated diff --git a/mobile/README.md b/mobile/README.md new file mode 100644 index 0000000..4cb2a2d --- /dev/null +++ b/mobile/README.md @@ -0,0 +1,77 @@ +# steno (iOS) + +iOS 用の常時オンデバイス文字起こし。マイクで周囲の会話を聞き取り、確定発話ごとにローカルの +JSON Lines へ書きながら、同じレコードを指定した宛先へリアルタイムに POST し続ける。 + +ASR + 話者分離のエンジンは共有パッケージ [`StenoCore`](../Core) を使い、macOS 版([`mac/`](../mac))と +同じコードを載せる。mac がシステム音声+マイクの二層を Core Audio process tap で扱うのに対し、 +iOS は tap が無いので**マイク一本の環境音**に割り切り、代わりに「ローカルに書いた発話を別マシンへ +送る」転送層を持つ。 + +**音声は端末の外に出ない。** 取得も認識もローカル(Apple のオンデバイス `SpeechAnalyzer`)。 +外へ出るのは**文字起こし結果のテキストだけ**で、宛先は自分で指定する(Tailscale 上の自宅 PC 等)。 + +## 仕組み + +``` +マイク (AVAudioEngine) ──► Transcriber (SpeechAnalyzer, ja_JP) + │ 確定発話 + ▼ + TranscriptStore ──► ローカル jsonl (SSOT, append-only) + │ 未送信キュー + ▼ + Shipper ──► POST /ingest (Bearer 認証) +``` + +- **エンジンは共有**。`Transcriber`(SpeechAnalyzer)は [`StenoCore`](../Core) のもの。capture・ + `TranscriptStore`・`Shipper`・UI が iOS 固有部として本ディレクトリに載る。 +- **capture と network を分離**する。capture は「まずローカル jsonl に書く」だけ。送信は Shipper が + 別で追いかける。宛先が落ちていても発話は失われず、復帰したら溜まったぶんを drain する。 +- **at-least-once**。各レコードはグローバル単調増加の `seq` を持ち、サーバは `(deviceId, seq)` で + 冪等に dedup する前提。送信済みカーソル(`lastShippedSeq`)は永続し、アプリ再起動を跨いで復元する。 +- **常時録音**は `UIBackgroundModes: audio` + `.record` の AVAudioSession。interruption(電話等)や + 経路変化からは interruption 通知と liveness watchdog の 2 系統で復帰する。 + +## 送信フォーマット + +確定発話ごとに 1 レコード。ローカル jsonl と POST ペイロードで同一: + +```json +{"deviceId":"iphone","ts":"2026-07-03T15:28:06.186+09:00","epoch":1783060086.18,"seq":42,"source":"mic","text":"…"} +``` + +`POST /ingest` の body はこのレコードの JSON 配列。サーバは受理した最大 seq を +`{"acked": }` で返す(省略時はバッチ末尾の seq を送信済みとみなす)。ローカルの jsonl は +`Documents/transcripts/YYYY-MM-DD.jsonl`。 + +## 設定(アプリ内) + +| 項目 | 意味 | +|---|---| +| 宛先ベース URL | 例 `http://100.x.y.z:8787`。Tailscale 上の PC。末尾に `/ingest` を付けて POST | +| Bearer トークン | `Authorization: Bearer ` に載せる共有シークレット | +| デバイス ID | 送信元の識別子(サーバ dedup キーの一部)。既定 `iphone` | + +WireGuard(Tailscale)がトンネルを暗号化するので、宛先は素の HTTP でよい。 + +## 要件 + +- **iOS 26.0+**(`SpeechAnalyzer`) +- Xcode 26 / Swift 6 + +## ビルド + +[xcodegen](https://github.com/yonaskolb/XcodeGen) で `.xcodeproj` を生成する(SSOT は `project.yml`)。 + +```sh +make gen # project.yml → steno-mobile.xcodeproj +make build # シミュレータ向けにビルド(コンパイル確認) +make open # Xcode で開く(実機は Team を設定して署名) +``` + +実機で常用するには署名が要る。無料プロビジョニングだと 7 日ごとに再署名が必要なので、 +常駐させるなら Apple Developer Program での署名を推奨。 + +## ライセンス + +MIT — [LICENSE](../LICENSE)。 diff --git a/mobile/Sources/AppModel.swift b/mobile/Sources/AppModel.swift new file mode 100644 index 0000000..4bf2dd2 --- /dev/null +++ b/mobile/Sources/AppModel.swift @@ -0,0 +1,111 @@ +import AVFoundation +import Foundation +import Observation +import Speech +import StenoCore + +/// パイプラインの結線と UI 状態。mic → Transcriber → TranscriptStore(SSOT) → Shipper。 +@MainActor +@Observable +final class AppModel { + var isRunning = false + var lines: [WireRecord] = [] + var pendingCount = 0 + var shipStatus = "待機中" + var micStatus = "停止" + + private let store = TranscriptStore() + private var transcriber: Transcriber? + private var mic: MicCapturer? + private var shipper: Shipper? + private var pollTask: Task? + + func start() async { + guard !isRunning else { return } + + guard await requestPermissions() else { + shipStatus = "マイク/音声認識の権限がありません" + return + } + + do { + let store = self.store + + let t = Transcriber(locale: Locale(identifier: "ja-JP"), label: "mic") { + [weak self] text, date in + Task { @MainActor in await self?.handleFinal(text, date) } + } + try await t.start() + self.transcriber = t + + let mic = MicCapturer { [weak t] buffer in t?.stream(buffer) } + try mic.start() + self.mic = mic + self.micStatus = "録音中" + + let shipper = Shipper(store: store) { [weak self] status in + self?.shipStatus = status + } + shipper.start() + self.shipper = shipper + + startPolling() + isRunning = true + ilog("pipeline started") + } catch { + shipStatus = "起動失敗: \(error.localizedDescription)" + ilog("start failed: \(error.localizedDescription)") + await stop() + } + } + + func stop() async { + mic?.stop() + mic = nil + shipper?.stop() + shipper = nil + await transcriber?.finish() + transcriber = nil + pollTask?.cancel() + pollTask = nil + micStatus = "停止" + isRunning = false + ilog("pipeline stopped") + } + + private func handleFinal(_ text: String, _ date: Date) async { + let rec = await store.append(text: text, at: date) + lines.append(rec) + if lines.count > 200 { + lines.removeFirst(lines.count - 200) + } + } + + private func startPolling() { + pollTask?.cancel() + pollTask = Task { [weak self] in + while !Task.isCancelled { + guard let self else { break } + self.pendingCount = await self.store.pendingCount + try? await Task.sleep(for: .seconds(1)) + } + } + } + + // nonisolated: 許可コールバックは TCC がバックグラウンドの XPC キューで呼ぶ。@MainActor を + // 継承したクロージャだと Swift 6 の実行 executor 検査(_swift_task_checkIsolatedSwift)が + // main 以外で trap する。self の状態は触らないので nonisolated にしてクロージャの隔離を外す。 + private nonisolated func requestPermissions() async -> Bool { + let mic = await withCheckedContinuation { (c: CheckedContinuation) in + AVAudioApplication.requestRecordPermission { granted in + c.resume(returning: granted) + } + } + let speech = await withCheckedContinuation { (c: CheckedContinuation) in + SFSpeechRecognizer.requestAuthorization { status in + c.resume(returning: status == .authorized) + } + } + return mic && speech + } +} diff --git a/mobile/Sources/Config.swift b/mobile/Sources/Config.swift new file mode 100644 index 0000000..2868616 --- /dev/null +++ b/mobile/Sources/Config.swift @@ -0,0 +1,18 @@ +import Foundation + +/// 設定値。SettingsView は同じキーで @AppStorage bind し、非 UI 層(Shipper)はここから読む。 +/// UserDefaults が SSOT なので設定変更は次の送信ループから即反映される。 +enum Config { + static let endpointKey = "endpoint" // 例: http://100.x.y.z:8787 (Tailscale の宛先ベース URL) + static let tokenKey = "token" // Bearer トークン + static let deviceIdKey = "deviceId" // 送信元の識別子(サーバ側 dedup キーの一部) + + static let defaultDeviceId = "iphone" + + static var endpoint: String { UserDefaults.standard.string(forKey: endpointKey) ?? "" } + static var token: String { UserDefaults.standard.string(forKey: tokenKey) ?? "" } + static var deviceId: String { + let v = UserDefaults.standard.string(forKey: deviceIdKey) ?? "" + return v.isEmpty ? defaultDeviceId : v + } +} diff --git a/mobile/Sources/ContentView.swift b/mobile/Sources/ContentView.swift new file mode 100644 index 0000000..7e6777e --- /dev/null +++ b/mobile/Sources/ContentView.swift @@ -0,0 +1,104 @@ +import SwiftUI + +struct ContentView: View { + @Environment(AppModel.self) private var model + @State private var showSettings = false + + private let timeFmt: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm:ss" + return f + }() + + var body: some View { + NavigationStack { + VStack(spacing: 12) { + statusBar + transcript + controlButton + } + .padding() + .navigationTitle("steno") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { + showSettings = true + } label: { + Image(systemName: "gearshape") + } + } + } + .sheet(isPresented: $showSettings) { + SettingsView() + } + } + } + + private var statusBar: some View { + HStack { + Label(model.micStatus, systemImage: "mic.fill") + .foregroundStyle(model.isRunning ? .green : .secondary) + Spacer() + Text("未送信 \(model.pendingCount)") + .foregroundStyle(model.pendingCount > 0 ? .orange : .secondary) + } + .font(.footnote) + .padding(.horizontal, 4) + } + + private var transcript: some View { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 8) { + ForEach(model.lines) { line in + VStack(alignment: .leading, spacing: 2) { + Text(timeFmt.string(from: Date(timeIntervalSince1970: line.epoch))) + .font(.caption2) + .foregroundStyle(.secondary) + Text(line.text) + .font(.body) + } + .frame(maxWidth: .infinity, alignment: .leading) + .id(line.seq) + } + } + .padding(.vertical, 4) + } + .onChange(of: model.lines.count) { + if let last = model.lines.last { + withAnimation { proxy.scrollTo(last.seq, anchor: .bottom) } + } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Color(.secondarySystemBackground)) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + + private var controlButton: some View { + VStack(spacing: 6) { + Button { + Task { + if model.isRunning { + await model.stop() + } else { + await model.start() + } + } + } label: { + Text(model.isRunning ? "停止" : "開始") + .font(.headline) + .frame(maxWidth: .infinity) + .padding(.vertical, 10) + } + .buttonStyle(.borderedProminent) + .tint(model.isRunning ? .red : .accentColor) + + Text(model.shipStatus) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } +} diff --git a/mobile/Sources/Log.swift b/mobile/Sources/Log.swift new file mode 100644 index 0000000..2528534 --- /dev/null +++ b/mobile/Sources/Log.swift @@ -0,0 +1,8 @@ +import Foundation +import os + +/// アプリ共通ログ。Console.app / `log stream` で拾える。 +private let logger = Logger(subsystem: "com.m5d215.steno-mobile", category: "app") + +func ilog(_ msg: String) { logger.info("\(msg, privacy: .public)") } +func dlog(_ msg: String) { logger.debug("\(msg, privacy: .public)") } diff --git a/mobile/Sources/MicCapturer.swift b/mobile/Sources/MicCapturer.swift new file mode 100644 index 0000000..cab91b9 --- /dev/null +++ b/mobile/Sources/MicCapturer.swift @@ -0,0 +1,158 @@ +@preconcurrency import AVFoundation +import Foundation +import os + +/// マイク入力を AVAudioEngine で取得し、AVAudioPCMBuffer で渡す。 +/// +/// iOS はデバイスが実質 1 本で、経路(内蔵/イヤホン/BT)は AVAudioSession が扱う。 +/// steno(macOS)は特定デバイス固定のため AVCaptureSession だったが、iOS では inputNode tap が素直。 +/// +/// 常時録音のキモ: +/// - category `.record` の AVAudioSession を activate し、`UIBackgroundModes: audio` と併せて +/// バックグラウンドでも録り続ける。 +/// - **interruption / route change で wedge する** のを 2 系統で復帰させる: +/// 1. `interruptionNotification`(電話・他アプリが audio を奪う)の .ended で再開。 +/// 2. liveness watchdog: 一定秒バッファが来なければ engine を作り直す(経路変化後の取りこぼし保険)。 +/// - tap の format は inputNode の実フォーマットから取る(固定しない。steno の教訓)。 +final class MicCapturer: @unchecked Sendable { + private let onBuffer: @Sendable (AVAudioPCMBuffer) -> Void + private var engine = AVAudioEngine() + + // engine の生成/差し替えは全てこのキュー上でだけ行う(watchdog と通知ハンドラの競合を直列化)。 + private let engineQueue = DispatchQueue(label: "com.m5d215.steno-mobile.mic.engine") + + private let lastBufferAt = OSAllocatedUnfairLock(initialState: Date.distantPast) + private var watchdogTask: Task? + private var observers: [NSObjectProtocol] = [] + private let staleThreshold: TimeInterval = 8 + + init(onBuffer: @escaping @Sendable (AVAudioPCMBuffer) -> Void) { + self.onBuffer = onBuffer + } + + func start() throws { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.record, mode: .default, options: []) + try session.setActive(true) + try startEngine() + registerObservers() + startWatchdog() + ilog("mic started") + } + + func stop() { + watchdogTask?.cancel() + watchdogTask = nil + for o in observers { NotificationCenter.default.removeObserver(o) } + observers.removeAll() + engineQueue.sync { stopEngine() } + try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation]) + ilog("mic stopped") + } + + // MARK: - engine + + private func startEngine() throws { + let input = engine.inputNode + let format = input.outputFormat(forBus: 0) // 実 hardware format。固定しない。 + input.removeTap(onBus: 0) + let onBuffer = self.onBuffer + let lastBufferAt = self.lastBufferAt + input.installTap(onBus: 0, bufferSize: 4096, format: format) { buffer, _ in + lastBufferAt.withLock { $0 = Date() } + onBuffer(buffer) + } + engine.prepare() + try engine.start() + lastBufferAt.withLock { $0 = Date() } + } + + private func stopEngine() { + engine.inputNode.removeTap(onBus: 0) + if engine.isRunning { engine.stop() } + } + + /// engine を作り直して再開(wedge からの復帰)。engineQueue 上で直列に実行する。 + private func restart(reason: String) { + engineQueue.async { [weak self] in + guard let self else { return } + ilog("mic restart: \(reason)") + self.stopEngine() + self.engine = AVAudioEngine() + do { + try AVAudioSession.sharedInstance().setActive(true) + try self.startEngine() + } catch { + ilog("mic restart failed: \(error.localizedDescription)") + } + } + } + + // MARK: - interruption / route change + + private func registerObservers() { + let nc = NotificationCenter.default + observers.append( + nc.addObserver( + forName: AVAudioSession.interruptionNotification, object: nil, queue: nil + ) { [weak self] note in + self?.handleInterruption(note) + }) + observers.append( + nc.addObserver( + forName: AVAudioSession.routeChangeNotification, object: nil, queue: nil + ) { [weak self] note in + self?.handleRouteChange(note) + }) + } + + private func handleInterruption(_ note: Notification) { + guard let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt, + let type = AVAudioSession.InterruptionType(rawValue: raw) + else { return } + switch type { + case .began: + ilog("mic interruption began") + case .ended: + let opts: AVAudioSession.InterruptionOptions + if let o = note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt { + opts = AVAudioSession.InterruptionOptions(rawValue: o) + } else { + opts = [] + } + if opts.contains(.shouldResume) { + restart(reason: "interruption ended") + } + @unknown default: + break + } + } + + private func handleRouteChange(_ note: Notification) { + guard let raw = note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt, + let reason = AVAudioSession.RouteChangeReason(rawValue: raw) + else { return } + switch reason { + case .oldDeviceUnavailable, .newDeviceAvailable, .override, .categoryChange: + restart(reason: "route change (\(reason.rawValue))") + default: + break + } + } + + // MARK: - liveness watchdog + + private func startWatchdog() { + watchdogTask?.cancel() + watchdogTask = Task { [weak self] in + while !Task.isCancelled { + try? await Task.sleep(for: .seconds(4)) + guard let self else { break } + let idle = Date().timeIntervalSince(self.lastBufferAt.withLock { $0 }) + if idle > self.staleThreshold { + self.restart(reason: "watchdog: no samples \(Int(idle))s") + } + } + } + } +} diff --git a/mobile/Sources/SettingsView.swift b/mobile/Sources/SettingsView.swift new file mode 100644 index 0000000..bf570c0 --- /dev/null +++ b/mobile/Sources/SettingsView.swift @@ -0,0 +1,49 @@ +import SwiftUI + +struct SettingsView: View { + @Environment(\.dismiss) private var dismiss + + @AppStorage(Config.endpointKey) private var endpoint = "" + @AppStorage(Config.tokenKey) private var token = "" + @AppStorage(Config.deviceIdKey) private var deviceId = "" + + var body: some View { + NavigationStack { + Form { + Section { + TextField("http://100.x.y.z:8787", text: $endpoint) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(.URL) + } header: { + Text("宛先ベース URL") + } footer: { + Text("Tailscale 上の PC のベース URL。末尾に /ingest を付けて POST する。") + } + + Section("Bearer トークン") { + TextField("token", text: $token) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } + + Section { + TextField(Config.defaultDeviceId, text: $deviceId) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } header: { + Text("デバイス ID") + } footer: { + Text("送信元の識別子。空なら \(Config.defaultDeviceId)。") + } + } + .navigationTitle("設定") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button("完了") { dismiss() } + } + } + } + } +} diff --git a/mobile/Sources/Shipper.swift b/mobile/Sources/Shipper.swift new file mode 100644 index 0000000..22be989 --- /dev/null +++ b/mobile/Sources/Shipper.swift @@ -0,0 +1,91 @@ +import Foundation + +/// 未送信レコードを宛先へ POST し続ける。capture からは独立して動く。 +/// +/// - `POST /ingest` body = WireRecord の JSON 配列 / header `Authorization: Bearer ` +/// - サーバは受理した最大 seq を `{"acked": }` で返す(無ければ送ったバッチ末尾の seq を採用)。 +/// - at-least-once。サーバ側は `(deviceId, seq)` で冪等 dedup する前提。 +/// - 失敗(PC 停止 / Tailscale 未接続 等)は指数 backoff で retry。復帰したら溜まったぶんを drain。 +final class Shipper: @unchecked Sendable { + private let store: TranscriptStore + private let onStatus: @MainActor (String) -> Void + private var task: Task? + + init(store: TranscriptStore, onStatus: @escaping @MainActor (String) -> Void) { + self.store = store + self.onStatus = onStatus + } + + func start() { + task = Task { await loop() } + } + + func stop() { + task?.cancel() + task = nil + } + + private func loop() async { + var backoff: Double = 1 + while !Task.isCancelled { + let batch = await store.pendingBatch(max: 50) + if batch.isEmpty { + try? await Task.sleep(for: .seconds(1)) + continue + } + guard let url = ingestURL(Config.endpoint) else { + await setStatus("宛先 URL が未設定") + try? await Task.sleep(for: .seconds(3)) + continue + } + do { + let acked = try await post(batch, to: url, token: Config.token) + await store.markShipped(throughSeq: acked) + backoff = 1 + await setStatus("送信 OK (〜seq \(acked), 残 \(await store.pendingCount))") + } catch { + await setStatus("送信失敗: \(error.localizedDescription) — \(Int(backoff))s 後に再試行") + try? await Task.sleep(for: .seconds(backoff)) + backoff = min(backoff * 2, 30) + } + } + } + + private func ingestURL(_ base: String) -> URL? { + let trimmed = base.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty, var url = URL(string: trimmed) else { return nil } + url.append(path: "ingest") + return url + } + + private struct Ack: Decodable { let acked: Int? } + + /// バッチを POST し、サーバが ack した最大 seq を返す。 + private func post(_ batch: [WireRecord], to url: URL, token: String) async throws -> Int { + var req = URLRequest(url: url) + req.httpMethod = "POST" + req.setValue("application/json", forHTTPHeaderField: "Content-Type") + if !token.isEmpty { + req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + req.httpBody = try JSONEncoder().encode(batch) + req.timeoutInterval = 15 + + let (data, resp) = try await URLSession.shared.data(for: req) + guard let http = resp as? HTTPURLResponse else { + throw NSError(domain: "Shipper", code: 1, + userInfo: [NSLocalizedDescriptionKey: "no HTTP response"]) + } + guard (200..<300).contains(http.statusCode) else { + throw NSError(domain: "Shipper", code: http.statusCode, + userInfo: [NSLocalizedDescriptionKey: "HTTP \(http.statusCode)"]) + } + // ack があればそれを、無ければ送ったバッチ末尾の seq を送信済みとみなす。 + let ack = try? JSONDecoder().decode(Ack.self, from: data) + return ack?.acked ?? (batch.last?.seq ?? 0) + } + + private func setStatus(_ s: String) async { + await onStatus(s) + } +} diff --git a/mobile/Sources/StenoMobileApp.swift b/mobile/Sources/StenoMobileApp.swift new file mode 100644 index 0000000..cc3b9a6 --- /dev/null +++ b/mobile/Sources/StenoMobileApp.swift @@ -0,0 +1,13 @@ +import SwiftUI + +@main +struct StenoMobileApp: App { + @State private var model = AppModel() + + var body: some Scene { + WindowGroup { + ContentView() + .environment(model) + } + } +} diff --git a/mobile/Sources/TranscriptStore.swift b/mobile/Sources/TranscriptStore.swift new file mode 100644 index 0000000..49a4c32 --- /dev/null +++ b/mobile/Sources/TranscriptStore.swift @@ -0,0 +1,152 @@ +import Foundation + +/// 1 確定発話 = 1 レコード。ローカル jsonl と送信ペイロードの唯一の契約面。 +/// `seq` はファイルを跨いだ **グローバル単調増加**(steno の日次リセットとは違う)。 +/// 送信カーソルとサーバ側 dedup を `(deviceId, seq)` で単純にするための選択。 +struct WireRecord: Sendable, Codable, Identifiable { + let deviceId: String + let ts: String // ISO 8601 ローカル時刻 + let epoch: Double // Unix 秒 + let seq: Int // グローバル単調増加 + let source: String // "mic"(iOS は mic 一本) + let text: String + + var id: Int { seq } +} + +/// 確定発話を **ローカル jsonl に append(SSOT)** し、未送信ぶんを in-memory キューに積む。 +/// capture と network を分離する: capture は「まず書く」だけ、送信は Shipper が別で追いかける。 +/// +/// - jsonl は `Documents/transcripts/YYYY-MM-DD.jsonl`(ローカル日付)へ O_APPEND で追記。 +/// - `seq` / `lastShippedSeq` は UserDefaults に永続。 +/// - 起動時に jsonl から未送信(seq > lastShippedSeq)を復元 → アプリ再起動を跨いで取りこぼさない。 +actor TranscriptStore { + private let baseDir: URL + private var handle: FileHandle? + private var currentDateKey = "" + + private var lastSeq: Int + private var lastShippedSeq: Int + private var pending: [WireRecord] = [] + + private let iso: ISO8601DateFormatter + private let dateKeyFmt: DateFormatter + private let encoder: JSONEncoder + + init() { + let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + baseDir = docs.appendingPathComponent("transcripts", isDirectory: true) + try? FileManager.default.createDirectory(at: baseDir, withIntermediateDirectories: true) + + lastSeq = UserDefaults.standard.integer(forKey: "lastSeq") + lastShippedSeq = UserDefaults.standard.integer(forKey: "lastShippedSeq") + + let f = ISO8601DateFormatter() + f.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + f.timeZone = .current + iso = f + + let df = DateFormatter() + df.locale = Locale(identifier: "en_US_POSIX") + df.dateFormat = "yyyy-MM-dd" + df.timeZone = .current + dateKeyFmt = df + + let enc = JSONEncoder() + enc.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + encoder = enc + + // 起動時に jsonl から未送信ぶんを復元(actor init は nonisolated なので self を使わない + // static ヘルパで計算して pending に入れる)。 + pending = Self.recoverUnshipped(baseDir: baseDir, after: lastShippedSeq) + } + + /// 確定発話を記録する。jsonl へ追記し、送信キューに積んで、そのレコードを返す。 + func append(text: String, at date: Date) -> WireRecord { + lastSeq += 1 + UserDefaults.standard.set(lastSeq, forKey: "lastSeq") + + let rec = WireRecord( + deviceId: Config.deviceId, + ts: iso.string(from: date), + epoch: date.timeIntervalSince1970, + seq: lastSeq, + source: "mic", + text: text) + + writeLine(rec, date: date) + pending.append(rec) + return rec + } + + /// 送信対象の先頭バッチ(seq 昇順)。 + func pendingBatch(max: Int) -> [WireRecord] { + Array(pending.sorted { $0.seq < $1.seq }.prefix(max)) + } + + /// `seq` まで送信済みにする。キューから外し、カーソルを進める。 + func markShipped(throughSeq seq: Int) { + pending.removeAll { $0.seq <= seq } + if seq > lastShippedSeq { + lastShippedSeq = seq + UserDefaults.standard.set(seq, forKey: "lastShippedSeq") + } + } + + var pendingCount: Int { pending.count } + + // MARK: - jsonl 追記 + + private func writeLine(_ rec: WireRecord, date: Date) { + let dateKey = dateKeyFmt.string(from: date) + rotateIfNeeded(to: dateKey) + guard let handle else { return } + guard let data = try? encoder.encode(rec) else { return } + var line = data + line.append(0x0a) // "\n" + do { + try handle.write(contentsOf: line) + } catch { + ilog("write failed: \(error.localizedDescription)") + } + } + + private func rotateIfNeeded(to dateKey: String) { + guard dateKey != currentDateKey else { return } + try? handle?.close() + handle = nil + + let url = baseDir.appendingPathComponent("\(dateKey).jsonl") + let fd = open(url.path, O_WRONLY | O_APPEND | O_CREAT, 0o644) + guard fd >= 0 else { + ilog("cannot open \(url.lastPathComponent): errno \(errno)") + return + } + handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + currentDateKey = dateKey + } + + // MARK: - 起動時の未送信復元 + + private static func recoverUnshipped(baseDir: URL, after lastShipped: Int) -> [WireRecord] { + let fm = FileManager.default + guard let files = try? fm.contentsOfDirectory(at: baseDir, includingPropertiesForKeys: nil) + else { return [] } + let decoder = JSONDecoder() + var recovered: [WireRecord] = [] + for url in files where url.pathExtension == "jsonl" { + guard let content = try? String(contentsOf: url, encoding: .utf8) else { continue } + for line in content.split(separator: "\n") { + guard let data = line.data(using: .utf8), + let rec = try? decoder.decode(WireRecord.self, from: data), + rec.seq > lastShipped + else { continue } + recovered.append(rec) + } + } + if !recovered.isEmpty { + ilog("recovered \(recovered.count) unshipped records") + } + return recovered.sorted { $0.seq < $1.seq } + } +} diff --git a/mobile/example-server/ingest.mjs b/mobile/example-server/ingest.mjs new file mode 100644 index 0000000..d3dee51 --- /dev/null +++ b/mobile/example-server/ingest.mjs @@ -0,0 +1,104 @@ +// steno-mobile の POST /ingest を受ける最小サーバ(依存ゼロ・Node 標準のみ)。 +// pipe(iPhone → 受け口)を実機で検証するためのリファレンス実装。本番の Slack 注入サーバは +// この contract(下記)を満たせば差し替え可能。 +// +// 実行: node example-server/ingest.mjs +// 環境: PORT 待受ポート(既定 8787) +// TOKEN 設定すると Authorization: Bearer を必須にする(未設定なら認証なし) +// LOG 受信レコードを追記する jsonl パス(未設定なら書かない。標準出力には常に出す) +// +// contract: +// GET / → 200 "ok"(ヘルスチェック) +// POST /ingest body = WireRecord の JSON 配列 +// header Authorization: Bearer (TOKEN 設定時) +// → 200 {"acked": <受理した最大 seq>} +// WireRecord = { deviceId, ts, epoch, seq, source, text } +// dedup は (deviceId, seq)。seq はクライアント側でグローバル単調増加。 +// ack した seq までクライアントは送信済みとみなし再送しない(at-least-once)。 + +import { createServer } from "node:http"; +import { appendFile } from "node:fs/promises"; + +const PORT = Number(process.env.PORT ?? 8787); +const TOKEN = process.env.TOKEN ?? ""; +const LOG = process.env.LOG ?? ""; + +// deviceId → これまでに受理した最大 seq。再起動で消える(PoC 用途では十分)。 +const lastSeq = new Map(); + +const server = createServer((req, res) => { + if (req.method === "GET" && req.url === "/") { + res.writeHead(200, { "content-type": "text/plain" }); + res.end("ok"); + return; + } + + if (req.method !== "POST" || req.url !== "/ingest") { + res.writeHead(404).end(); + return; + } + + if (TOKEN && req.headers.authorization !== `Bearer ${TOKEN}`) { + res.writeHead(401, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "unauthorized" })); + return; + } + + let body = ""; + req.on("data", (chunk) => { + body += chunk; + if (body.length > 4_000_000) req.destroy(); // 暴走ガード + }); + req.on("end", () => { + void handle(body, res); + }); +}); + +async function handle(body, res) { + let records; + try { + records = JSON.parse(body); + if (!Array.isArray(records)) throw new Error("body must be a JSON array"); + } catch (e) { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: String(e.message ?? e) })); + return; + } + + let ackedMax = 0; + const lines = []; + + for (const r of records) { + if ( + typeof r?.deviceId !== "string" || + typeof r?.seq !== "number" || + typeof r?.text !== "string" + ) { + continue; // 壊れたレコードは黙って捨てる + } + ackedMax = Math.max(ackedMax, r.seq); + + const seen = lastSeq.get(r.deviceId) ?? 0; + if (r.seq <= seen) continue; // dedup: 既に受理済み + lastSeq.set(r.deviceId, r.seq); + + const t = typeof r.ts === "string" ? r.ts.slice(11, 19) : "--:--:--"; + console.log(`[${t}] ${r.deviceId} #${r.seq} ${r.source ?? "?"}: ${r.text}`); + if (LOG) lines.push(JSON.stringify(r)); + } + + if (LOG && lines.length) { + try { + await appendFile(LOG, lines.join("\n") + "\n"); + } catch (e) { + console.error(`append failed: ${e.message ?? e}`); + } + } + + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ acked: ackedMax })); +} + +server.listen(PORT, () => { + console.log(`ingest server on :${PORT}` + (TOKEN ? " (bearer required)" : " (no auth)")); +}); diff --git a/mobile/project.yml b/mobile/project.yml new file mode 100644 index 0000000..6682b7b --- /dev/null +++ b/mobile/project.yml @@ -0,0 +1,66 @@ +name: steno-mobile +options: + bundleIdPrefix: com.m5d215 + deploymentTarget: + iOS: "26.0" + createIntermediateGroups: true + generateEmptyDirectories: true + +settings: + base: + SWIFT_VERSION: "6.0" + MARKETING_VERSION: "0.1.0" + CURRENT_PROJECT_VERSION: "1" + # 実機署名用の Team は各自ローカルで設定する(Xcode の Signing、または gitignore した + # xcconfig)。public repo に個人アカウント紐付きの Team ID を載せないため空にしている。 + # シミュレータビルドは署名不要なので空でも通る。 + DEVELOPMENT_TEAM: "" + CODE_SIGN_STYLE: Automatic + +packages: + StenoCore: + path: ../Core + +targets: + steno-mobile: + type: application + platform: iOS + sources: + - Sources + dependencies: + - package: StenoCore + product: StenoCore + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: com.m5d215.steno-mobile + PRODUCT_NAME: steno + GENERATE_INFOPLIST_FILE: NO + TARGETED_DEVICE_FAMILY: "1" + INFOPLIST_KEY_UILaunchScreen_Generation: YES + info: + path: Generated/Info.plist + properties: + CFBundleDisplayName: steno + CFBundleShortVersionString: "0.1.0" + CFBundleVersion: "1" + LSMinimumSystemVersion: "26.0" + UILaunchScreen: {} + UISupportedInterfaceOrientations: + - UIInterfaceOrientationPortrait + # 常時録音のためのバックグラウンド audio。アプリ稼働中は録り続ける。 + UIBackgroundModes: + - audio + NSMicrophoneUsageDescription: >- + 周囲の会話を文字起こしするため、マイク音声を取得します。音声は端末内でのみ処理し、 + 文字起こし結果だけを指定した宛先へ送信します。 + NSSpeechRecognitionUsageDescription: >- + 取得した音声をオンデバイスで文字起こしします。音声は外部に送信されません。 + # ATS 例外。宛先は Tailscale(WireGuard がトンネルを暗号化済み)なので素の HTTP を許す。 + # 全 HTTP を開けず、tailnet の MagicDNS 名(*.ts.net)と private IP だけに絞る。 + # 100.x の IP 直打ちで通らない場合は NSAllowsArbitraryLoads: true に切り替える。 + NSAppTransportSecurity: + NSAllowsLocalNetworking: true + NSExceptionDomains: + ts.net: + NSExceptionAllowsInsecureHTTPLoads: true + NSIncludesSubdomains: true