fix(ios): 保留停顿前后的录音文字并简化录入
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-26 16:06:52 +08:00
parent 6c161d1c5f
commit 0d68e6a429
10 changed files with 450 additions and 149 deletions

View File

@ -117,7 +117,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 6;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";
@ -138,7 +138,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 6;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";

View File

@ -84,17 +84,6 @@ final class AtlasAccount {
private var refreshTask: Task<String, Error>?
private var generation = UUID()
var preferenceScope: String? {
guard let segment = tokens?.grant.access_token.split(separator: ".").dropFirst().first,
let issuer = configuration?.issuer else { return nil }
let payload = segment.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let padding = String(repeating: "=", count: (4 - payload.count % 4) % 4)
guard let data = Data(base64Encoded: payload + padding),
let claims = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
let subject = claims["sub"] as? String, !subject.isEmpty else { return nil }
return issuer.absoluteString + "/" + subject
}
init() {
let config = URLSessionConfiguration.ephemeral
config.urlCache = nil

View File

@ -0,0 +1,138 @@
import AVFoundation
import CoreMedia
import Speech
import os
@available(iOS 26.0, *)
@MainActor
final class ContinuousDictation {
private static var assetPreparation: Task<Void, Never>?
private let transcriber: DictationTranscriber
private let analyzer: SpeechAnalyzer
private let input: AsyncStream<AnalyzerInput>
let audioInput: AudioInput
private var task: Task<Void, Never>?
static func prepare(locale: Locale, inputFormat: AVAudioFormat, context: [String]) async throws -> ContinuousDictation? {
guard let locale = await DictationTranscriber.supportedLocale(equivalentTo: locale) else { return nil }
let transcriber = DictationTranscriber(locale: locale, preset: .progressiveLongDictation)
let assetStatus = await AssetInventory.status(forModules: [transcriber])
if assetStatus == .supported, assetPreparation == nil {
// Keep the first recording responsive while iOS prepares its local model.
assetPreparation = Task(priority: .utility) {
if let installation = try? await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
try? await installation.downloadAndInstall()
}
}
}
guard assetStatus == .installed,
let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber], considering: inputFormat),
let converter = AVAudioConverter(from: inputFormat, to: format) else { return nil }
let analyzer = SpeechAnalyzer(modules: [transcriber])
let hints = AnalysisContext()
hints.contextualStrings[.general] = context
try await analyzer.setContext(hints)
try await analyzer.prepareToAnalyze(in: format)
return ContinuousDictation(transcriber: transcriber, analyzer: analyzer, converter: converter)
}
private init(transcriber: DictationTranscriber, analyzer: SpeechAnalyzer, converter: AVAudioConverter) {
self.transcriber = transcriber
self.analyzer = analyzer
let (stream, continuation) = AsyncStream.makeStream(of: AnalyzerInput.self)
input = stream
audioInput = AudioInput(converter: converter, continuation: continuation)
}
func start(onUpdate: @escaping (String, Bool) -> Void, onFinish: @escaping (Bool) -> Void) {
task = Task { [analyzer, transcriber, input, audioInput] in
do {
async let analysis: Void = Self.analyze(analyzer, input: input)
for try await result in transcriber.results {
guard !Task.isCancelled else { return }
onUpdate(String(result.text.characters), result.isFinal)
}
try await analysis
if !Task.isCancelled { onFinish(!audioInput.failed) }
} catch {
if !Task.isCancelled { onFinish(false) }
}
}
}
private nonisolated static func analyze(_ analyzer: SpeechAnalyzer, input: AsyncStream<AnalyzerInput>) async throws {
do {
if let last = try await analyzer.analyzeSequence(input) {
try await analyzer.finalizeAndFinish(through: last)
} else {
await analyzer.cancelAndFinishNow()
}
} catch {
await analyzer.cancelAndFinishNow()
throw error
}
}
func stop() {
audioInput.finish()
}
func cancel() {
audioInput.finish()
task?.cancel()
let analyzer = self.analyzer
Task { await analyzer.cancelAndFinishNow() }
}
// The audio tap owns the converter. The result task only reads the locked failure flag.
final class AudioInput: @unchecked Sendable {
private let converter: AVAudioConverter
private let continuation: AsyncStream<AnalyzerInput>.Continuation
private let failure = OSAllocatedUnfairLock(initialState: false)
var failed: Bool { failure.withLock { $0 } }
init(converter: AVAudioConverter, continuation: AsyncStream<AnalyzerInput>.Continuation) {
self.converter = converter
self.continuation = continuation
converter.primeMethod = .none
}
func append(_ buffer: AVAudioPCMBuffer) {
guard buffer.frameLength > 0 else { return }
let format = converter.outputFormat
let ratio = format.sampleRate / buffer.format.sampleRate
let capacity = AVAudioFrameCount(ceil(Double(buffer.frameLength) * ratio))
guard let output = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else {
markFailed()
return
}
var supplied = false
var error: NSError?
let status = converter.convert(to: output, error: &error) { _, inputStatus in
if supplied {
inputStatus.pointee = .noDataNow
return nil
}
supplied = true
inputStatus.pointee = .haveData
return buffer
}
guard status != .error else {
markFailed()
return
}
if output.frameLength > 0 { continuation.yield(AnalyzerInput(buffer: output)) }
}
func finish() {
continuation.finish()
}
private func markFailed() {
failure.withLock { $0 = true }
finish()
}
}
}

View File

@ -38,7 +38,7 @@ struct ItemEditor: View {
if let error { Text(error).foregroundStyle(.red) }
}
.dismissibleKeyboard(active: focus != nil) { focus = nil }
.navigationTitle(existing == nil ? "记一件" : "编辑物品")
.navigationTitle(existing == nil ? "添加物品" : "编辑物品")
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {

View File

@ -3,7 +3,8 @@ import SwiftUI
struct IntakeView: View {
let store: InventoryStore
@Environment(\.scenePhase) private var scenePhase
@AppStorage private var automaticSave: Bool
@AppStorage("atlas.voice.recording-mode") private var recordingMode: RecordingMode = .tap
@GestureState private var holdingMicrophone = false
@FocusState private var typing: Bool
@State private var voice = VoiceCapture()
@State private var text = ""
@ -13,14 +14,10 @@ struct IntakeView: View {
@State private var busy = false
@State private var showingAdd = false
@State private var error: String?
@State private var receipt: String?
@State private var showingReceipt = false
@State private var showingVoiceReview = false
@State private var showingHelp = false
init(store: InventoryStore) {
self.store = store
let scope = store.account.preferenceScope ?? "unavailable"
_automaticSave = AppStorage(wrappedValue: false, "atlas.voice-auto-save." + scope)
private enum RecordingMode: String {
case tap, hold
}
private struct Draft: Decodable {
@ -28,7 +25,6 @@ struct IntakeView: View {
let originalText: String
let candidates: [Candidate]
let status: String
let source: String?
let version: Int
}
private struct Candidate: Decodable {
@ -38,10 +34,10 @@ struct IntakeView: View {
let location: String?
}
private struct Operation: Decodable { let id: UUID; let status: String }
private struct Confirm: Encodable { let version: Int; let items: [ItemInput]; let automatic: Bool }
private struct Confirm: Encodable { let version: Int; let items: [ItemInput] }
private var canParse: Bool {
!busy && voice.phase == .idle && operation == nil && text.count <= 4000 &&
!busy && voice.phase == .idle && operation == nil && text.utf16.count <= 4000 &&
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
@ -49,31 +45,61 @@ struct IntakeView: View {
NavigationStack {
if store.canWrite {
Form {
Button { showingAdd = true } label: { Label("手工记一件", systemImage: "plus") }
Section("说句话,记下来") {
Section {
Button { showingAdd = true } label: { Label("手动添加物品", systemImage: "plus") }
.disabled(voice.phase != .idle)
}
Section("录音录入") {
voiceButton
if voice.phase == .recording || voice.phase == .finishing {
recordingProgress
}
if !voice.transcript.isEmpty {
Text(voice.transcript).foregroundStyle(.secondary)
}
if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) }
TextEditor(text: $text).frame(minHeight: 96).focused($typing).accessibilityLabel("整理原话")
.disabled(busy || voice.phase != .idle || operation != nil)
Button("提取物品") { typing = false; Task { await parse(source: "VOICE") } }.disabled(!canParse)
Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } }.disabled(!canParse)
if store.account.preferenceScope != nil {
DisclosureGroup("语音设置") {
Toggle("清楚的一句话自动保存", isOn: $automaticSave)
Text("仅自动保存一件物品,位置需匹配完整路径。").font(.footnote).foregroundStyle(.secondary)
DisclosureGroup("录音设置") {
Picker("录音方式", selection: $recordingMode) {
Text("点按开始,再点结束").tag(RecordingMode.tap)
Text("按住录音,松手结束").tag(RecordingMode.hold)
}.disabled(voice.phase != .idle)
}
}
if voice.phase == .idle {
Section("录入文字") {
TextEditor(text: $text)
.frame(minHeight: 88)
.focused($typing)
.accessibilityLabel("录入文字")
.disabled(busy || operation != nil)
.overlay(alignment: .topLeading) {
if text.isEmpty {
Text("录音转写会显示在这里,也可以直接输入。")
.foregroundStyle(.secondary)
.padding(.horizontal, 5)
.padding(.vertical, 8)
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
if text.utf16.count > 4000 {
Text("录入文字达到长度上限,请分开整理。").font(.footnote).foregroundStyle(.secondary)
}
if !text.isEmpty && draft == nil {
Button("生成物品草稿") { typing = false; Task { await parse() } }
.disabled(!canParse)
}
}
}
if let draft {
if voice.phase == .idle, let draft {
Section("核对物品和位置") {
if draft.candidates.isEmpty {
Text(draft.status == "MODEL_UNAVAILABLE"
? "模型暂不可用,原话已保留。"
: "这句话需要再核对。可以改文字、手工录入,或用 AI 整理。")
? "AI 暂不可用。你可以再试一次,或手动添加物品。"
: "还没整理出物品。可以修改原话,或让 AI 整理较长的描述。")
.font(.footnote).foregroundStyle(.secondary)
Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } }
.disabled(!canParse)
}
ForEach(draft.candidates.indices, id: \.self) { index in
let candidate = draft.candidates[index]
@ -85,16 +111,19 @@ struct IntakeView: View {
if let hint = candidate.location, !hint.isEmpty {
Text("原话位置:\(hint)").font(.footnote).foregroundStyle(.secondary)
}
Picker("确认位置", selection: Binding(get: { selections[index] }, set: { selections[index] = $0 })) {
Text("不录入").tag(nil as UUID?)
Picker("存放位置", selection: Binding(get: { selections[index] }, set: { selections[index] = $0 })) {
Text("未选择").tag(nil as UUID?)
ForEach(store.locations) { place in Text(place.path).tag(Optional(place.id)) }
}
}.disabled(operation != nil)
}
}
if !draft.candidates.isEmpty {
Button("确认保存") { Task { await submit(draft) } }
.disabled(busy || selections.isEmpty || operation != nil)
Button("保存物品") { typing = false; Task { await submit(draft) } }
.disabled(busy || selections.isEmpty || operation != nil || voice.phase != .idle)
if selections.isEmpty {
Text("选好存放位置后就可以保存。").font(.footnote).foregroundStyle(.secondary)
}
}
}
}
@ -117,6 +146,12 @@ struct IntakeView: View {
}
.dismissibleKeyboard(active: typing) { typing = false }
.navigationTitle("录入")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") }
.disabled(voice.phase != .idle)
}
}
.onDisappear { voice.cancel() }
.onChange(of: scenePhase) { _, phase in
if phase == .background { voice.cancel() }
@ -127,20 +162,24 @@ struct IntakeView: View {
selections = [:]
}
}
.alert("已存入", isPresented: $showingReceipt) {
Button("知道了", role: .cancel) { receipt = nil }
} message: {
Text(receipt ?? "")
}
.confirmationDialog("核对这条录入", isPresented: $showingVoiceReview, titleVisibility: .visible) {
Button("确认保存") {
if let draft { Task { await submit(draft) } }
}
Button("返回编辑", role: .cancel) {}
} message: {
if let item = draft?.candidates.first,
let place = store.locations.first(where: { $0.id == selections[0] }) {
Text("\(item.name) ×\(item.quantity ?? 1)\n\(place.path)")
.sheet(isPresented: $showingHelp) {
NavigationStack {
List {
Section("录音录入") {
Text("默认点一下开始,再点一下结束。录音设置也可以改成按住说、松手结束。")
Text("每次最多 25 秒,中间停一下可以接着说。首次允许权限后,可重新开始录音。")
Text("结束后可以修改转写。见物会先生成物品草稿。描述比较长时,可以点「用 AI 整理」。")
Text("核对物品和存放位置,然后点「保存物品」。")
}
Section("手动添加") {
Text("点「手动添加物品」,填写名称,选好存放位置再保存。")
}
}
.navigationTitle("怎么录入")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) { Button("完成") { showingHelp = false } }
}
}
}
.sheet(isPresented: $showingAdd) { ItemEditor(store: store) }
@ -150,58 +189,89 @@ struct IntakeView: View {
}
}
@ViewBuilder
private var voiceButton: some View {
Button {
if voice.phase == .recording {
voice.stop()
} else {
typing = false
let hadText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
Task {
await voice.start(context: store.locations.map(\.name)) { phrase, final in
text = hadText ? text + "\n" + phrase : phrase
let canSave = final && !hadText && automaticSave && store.account.preferenceScope != nil
if text.count <= 4000 {
Task { await parse(source: "VOICE", fromVoice: true, automatically: canSave) }
}
}
if recordingMode == .tap {
Button(action: toggleRecording) { recordingLabel }
.disabled(busy || operation != nil || voice.phase == .finishing)
} else {
recordingLabel
.foregroundStyle(Color.accentColor)
.gesture(DragGesture(minimumDistance: 0).updating($holdingMicrophone) { _, active, _ in
active = true
})
.onChange(of: holdingMicrophone) { _, active in
if active { beginRecording(whileHeld: true) } else { voice.stop() }
}
}
} label: {
.accessibilityAddTraits(.isButton)
.accessibilityAction { toggleRecording() }
.accessibilityHint("使用旁白时,轻点两下开始,再轻点两下结束。")
.allowsHitTesting(!busy && operation == nil && voice.phase != .finishing)
}
}
private var recordingLabel: some View {
Group {
switch voice.phase {
case .idle: Label("开始录音", systemImage: "mic.fill")
case .idle: Label(recordingMode == .hold ? "按住录音" : "开始录音", systemImage: "mic.fill")
case .preparing: Label("准备麦克风…", systemImage: "mic")
case .recording: Label("说完了", systemImage: "stop.circle.fill")
case .recording: Label(recordingMode == .hold ? "松手结束" : "结束录音", systemImage: "stop.circle.fill")
case .finishing: Label("正在转写…", systemImage: "waveform")
}
}
.disabled(busy || operation != nil || voice.phase == .preparing || voice.phase == .finishing)
.frame(maxWidth: .infinity, minHeight: 32, alignment: .leading)
.contentShape(Rectangle())
}
private func parse(source: String, fromVoice: Bool = false, automatically: Bool = false) async {
private var recordingProgress: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Label(voice.phase == .finishing ? "完成转写中" : "录音中", systemImage: "waveform")
Spacer()
Text("\(voice.elapsedSeconds) / \(VoiceCapture.maximumDuration) 秒").monospacedDigit()
}
.font(.footnote)
ProgressView(value: Double(voice.elapsedSeconds), total: Double(VoiceCapture.maximumDuration))
.accessibilityHidden(true)
}
}
private func toggleRecording() {
if voice.phase == .idle { beginRecording() } else { voice.stop() }
}
private func beginRecording(whileHeld: Bool = false) {
guard !busy, operation == nil else { return }
typing = false
Task {
if whileHeld && !holdingMicrophone { return }
await voice.start(context: store.locations.map(\.name)) { phrase, complete in
let previous = text.trimmingCharacters(in: .whitespacesAndNewlines)
text = previous.isEmpty ? phrase : previous + "\n" + phrase
if complete { Task { await parse() } }
}
}
}
private func parse(source: String = "VOICE") async {
guard canParse else { return }
let original = text
busy = true
defer { busy = false }
error = nil
do {
try await store.refreshLocations()
let result: Draft = try await store.send(store.root + "/drafts", ["text": text, "source": source])
let result: Draft = try await store.send(store.root + "/drafts", ["text": original, "source": source])
guard text == original else { return }
draft = result
selections = Dictionary(uniqueKeysWithValues: result.candidates.enumerated().compactMap { index, candidate in
guard candidate.action != "SKIP", let place = suggestedPlace(candidate.location) else { return nil }
return (index, place.id)
})
if automatically, result.source == "VOICE", result.candidates.count == 1,
let candidate = result.candidates.first, candidate.action == "RECORD",
let place = suggestedPlace(candidate.location, fullPathOnly: true), place.id == selections[0] {
receipt = "\(candidate.name) ×\(candidate.quantity ?? 1)\n\(place.path)"
await submit(result, automatic: true)
} else if fromVoice && result.candidates.count == 1 && selections[0] != nil {
showingVoiceReview = true
}
} catch { self.error = error.localizedDescription }
}
private func suggestedPlace(_ original: String?, fullPathOnly: Bool = false) -> Place? {
private func suggestedPlace(_ original: String?) -> Place? {
guard let original else { return nil }
func key(_ value: String) -> String {
value.folding(options: [.caseInsensitive, .widthInsensitive], locale: Locale(identifier: "zh-CN"))
@ -213,13 +283,12 @@ struct IntakeView: View {
let exact = store.locations.filter { key($0.path) == hint }
let matches = exact.isEmpty ? store.locations.filter { key($0.path) == spoken } : exact
if !matches.isEmpty { return matches.count == 1 ? matches.first : nil }
if fullPathOnly { return nil }
let names = store.locations.filter { key($0.name) == hint || key($0.name) == spoken }
return names.count == 1 ? names.first : nil
}
private func submit(_ draft: Draft, automatic: Bool = false) async {
guard draft.originalText == text else { return }
private func submit(_ draft: Draft) async {
guard draft.originalText == text, !busy, operation == nil, voice.phase == .idle else { return }
let items = draft.candidates.enumerated().compactMap { index, candidate -> ItemInput? in
guard let location = selections[index], candidate.action != "SKIP" else { return nil }
return ItemInput(name: candidate.name, quantity: candidate.quantity ?? 1, notes: "", locationId: location, aliases: [])
@ -229,13 +298,10 @@ struct IntakeView: View {
defer { busy = false }
do {
let accepted: Operation = try await store.send(store.root + "/drafts/\(draft.id)/confirm",
Confirm(version: draft.version, items: items, automatic: automatic))
Confirm(version: draft.version, items: items))
operation = accepted
await poll(accepted)
} catch {
if automatic { receipt = nil }
self.error = error.localizedDescription
}
} catch { self.error = error.localizedDescription }
}
private func reset(clearText: Bool) {
@ -243,7 +309,6 @@ struct IntakeView: View {
draft = nil
selections = [:]
operation = nil
receipt = nil
error = nil
}
@ -269,7 +334,6 @@ struct IntakeView: View {
operation = status
if status.status == "COMPLETED" {
store.changed()
showingReceipt = receipt != nil
return
}
if ["FAILED", "REJECTED", "NEEDS_REVIEW"].contains(status.status) { return }

View File

@ -7,25 +7,31 @@ import Speech
final class VoiceCapture {
enum Phase { case idle, preparing, recording, finishing }
static let maximumDuration = 25
private static let locale = Locale(identifier: "zh-CN")
private(set) var phase: Phase = .idle
private(set) var elapsedSeconds = 0
private(set) var transcript = ""
private(set) var error: String?
private let engine = AVAudioEngine()
private let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "zh-CN"))
private var request: SFSpeechAudioBufferRecognitionRequest?
private var recognition: SFSpeechRecognitionTask?
private var timer: Task<Void, Never>?
private var sessionID: UUID?
private var tapInstalled = false
private var audioActive = false
private var completion: ((String, Bool) -> Void)?
private var endInput: (() -> Void)?
private var cancelRecognition: (() -> Void)?
private var completed: [String] = []
private var preview = ""
private var legacy = LegacyTranscription()
func start(context: [String], completion: @escaping (String, Bool) -> Void) async {
guard phase == .idle else { return }
let id = UUID()
sessionID = id
error = nil
transcript = ""
phase = .preparing
let microphone = await AVAudioApplication.requestRecordPermission()
guard sessionID == id else { return }
@ -44,10 +50,6 @@ final class VoiceCapture {
fail("语音识别权限已关闭。可以在系统设置中开启,或直接打字。")
return
}
guard let recognizer, recognizer.supportsOnDeviceRecognition, recognizer.isAvailable else {
fail("这台设备暂时无法在本机转写普通话。可以改用键盘听写或直接打字。")
return
}
do {
let audio = AVAudioSession.sharedInstance()
@ -60,79 +62,145 @@ final class VoiceCapture {
fail("当前没有可录音的麦克风。")
return
}
let request = SFSpeechAudioBufferRecognitionRequest()
request.requiresOnDeviceRecognition = true
request.shouldReportPartialResults = true
request.taskHint = .dictation
request.contextualStrings = Array(context.prefix(60))
self.request = request
self.completion = completion
let sink = BufferSink(request)
input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in
sink.append(buffer)
}
tapInstalled = true
recognition = recognizer.recognitionTask(with: request) { @Sendable [weak self] result, failure in
let text = result?.bestTranscription.formattedString
let final = result?.isFinal == true
let failed = failure != nil
Task { @MainActor in
self?.received(id: id, text: text, isFinal: final, failed: failed)
let hints = Array(context.prefix(60))
if #available(iOS 26.0, *),
let dictation = try? await ContinuousDictation.prepare(
locale: Self.locale, inputFormat: format, context: hints
) {
guard sessionID == id else { dictation.cancel(); return }
let sink = dictation.audioInput
input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in
sink.append(buffer)
}
endInput = dictation.stop
cancelRecognition = dictation.cancel
dictation.start { [weak self] text, final in
self?.receivePhrase(id: id, text: text, final: final)
} onFinish: { [weak self] success in
guard let self, self.sessionID == id else { return }
self.finish(final: success && self.phase == .finishing)
}
} else {
guard sessionID == id else { return }
guard startLegacy(id: id, input: input, format: format, context: hints) else {
fail("本机暂时无法转写普通话。可以用键盘听写或直接打字。")
return
}
}
tapInstalled = true
self.completion = completion
engine.prepare()
try engine.start()
phase = .recording
timer = Task { [weak self] in
try? await Task.sleep(for: .seconds(25))
if !Task.isCancelled { self?.stop() }
}
countRecordingTime()
} catch {
fail("麦克风暂时无法使用。")
}
}
func stop() {
if phase == .preparing {
cancel()
return
}
guard phase == .recording else { return }
phase = .finishing
stopMicrophone()
request?.endAudio()
endInput?()
timer?.cancel()
timer = Task { [weak self] in
try? await Task.sleep(for: .seconds(2))
try? await Task.sleep(for: .seconds(6))
if !Task.isCancelled { self?.finish(final: false) }
}
}
func cancel() {
sessionID = nil
stopMicrophone()
recognition?.cancel()
recognition = nil
request = nil
cancelRecognition?()
cancelRecognition = nil
endInput = nil
timer?.cancel()
timer = nil
completion = nil
sessionID = nil
phase = .idle
elapsedSeconds = 0
transcript = ""
completed = []
preview = ""
legacy = LegacyTranscription()
if audioActive {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
audioActive = false
}
}
private func received(id: UUID, text: String?, isFinal: Bool, failed: Bool) {
private func countRecordingTime() {
let clock = ContinuousClock()
let start = clock.now
timer = Task { [weak self] in
for second in 1...Self.maximumDuration {
try? await clock.sleep(until: start.advanced(by: .seconds(second)))
guard !Task.isCancelled, let self else { return }
self.elapsedSeconds = second
}
self?.stop()
}
}
private func receivePhrase(id: UUID, text: String, final: Bool) {
guard sessionID == id else { return }
if let text, !text.isEmpty { transcript = text }
if isFinal || failed { finish(final: isFinal && !failed) }
let phrase = text.trimmingCharacters(in: .whitespacesAndNewlines)
if final {
if !phrase.isEmpty { completed.append(phrase) }
preview = ""
} else {
preview = phrase
}
transcript = (preview.isEmpty ? completed : completed + [preview]).joined(separator: "\n")
}
private func startLegacy(id: UUID, input: AVAudioInputNode, format: AVAudioFormat, context: [String]) -> Bool {
guard let recognizer = SFSpeechRecognizer(locale: Self.locale),
recognizer.supportsOnDeviceRecognition, recognizer.isAvailable else { return false }
let request = SFSpeechAudioBufferRecognitionRequest()
request.requiresOnDeviceRecognition = true
request.shouldReportPartialResults = true
request.taskHint = .dictation
request.contextualStrings = context
let sink = BufferSink(request)
input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in
sink.append(buffer)
}
let recognition = recognizer.recognitionTask(with: request) { @Sendable [weak self] result, error in
let text = result?.bestTranscription.formattedString
let segments = result?.bestTranscription.segments
let start = segments?.first?.timestamp ?? 0
let last = segments?.last
let end = (last?.timestamp ?? 0) + (last?.duration ?? 0)
let final = result?.isFinal == true
let failed = error != nil
let now = ContinuousClock().now
Task { @MainActor in
guard let self, self.sessionID == id else { return }
if let text, !text.isEmpty {
self.legacy.update(text, start: start, end: end, at: now, final: final)
self.transcript = self.legacy.text
}
if final || failed { self.finish(final: final && !failed && self.phase == .finishing) }
}
}
endInput = request.endAudio
cancelRecognition = { recognition.cancel(); _ = recognizer }
return true
}
private func stopMicrophone() {
guard tapInstalled else { return }
engine.stop()
if tapInstalled {
engine.inputNode.removeTap(onBus: 0)
tapInstalled = false
}
engine.inputNode.removeTap(onBus: 0)
tapInstalled = false
}
private func finish(final: Bool) {
@ -142,6 +210,7 @@ final class VoiceCapture {
if text.isEmpty {
error = "没有听清。可以再录一遍,或直接输入。"
} else {
if !final { error = "转写提前结束,已保留听到的文字。请先核对。" }
callback?(text, final)
}
}
@ -151,7 +220,6 @@ final class VoiceCapture {
error = message
}
// Apple's recognition request receives buffers on the audio thread.
private final class BufferSink: @unchecked Sendable {
private let request: SFSpeechAudioBufferRecognitionRequest
@ -160,3 +228,46 @@ final class VoiceCapture {
func append(_ buffer: AVAudioPCMBuffer) { request.append(buffer) }
}
}
// The older API may give a fresh utterance after a pause instead of extending its previous result.
struct LegacyTranscription {
private var committed: [String] = []
private var current = ""
private var lastUpdate: ContinuousClock.Instant?
private var previousEnd: TimeInterval = 0
var text: String { (current.isEmpty ? committed : committed + [current]).joined(separator: "\n") }
mutating func update(_ value: String, start: TimeInterval, end: TimeInterval,
at now: ContinuousClock.Instant, final: Bool) {
let next = value.trimmingCharacters(in: .whitespacesAndNewlines)
guard !next.isEmpty else { return }
let nextKey = comparisonKey(next)
let currentKey = comparisonKey(current)
if final, let first = committed.first.map(comparisonKey), !first.isEmpty, end > start,
nextKey.hasPrefix(first) {
// The final result can include the complete audio after its partials reset.
committed = []
current = next
return
}
let prefix = zip(nextKey, currentKey).prefix { $0 == $1 }.count
let pause = lastUpdate.map { $0.duration(to: now) >= .milliseconds(700) } ?? false
let separateRange = start > previousEnd + 0.15 && previousEnd > 0
if !final && !separateRange && pause && prefix == nextKey.count && nextKey.count < currentKey.count {
return
}
let newUntimedPhrase = (end <= start || previousEnd == 0) && pause &&
currentKey.count - prefix >= max(2, currentKey.count / 2)
if !current.isEmpty && (separateRange || newUntimedPhrase) {
committed.append(current)
}
current = next
previousEnd = end
lastUpdate = now
}
private func comparisonKey(_ text: String) -> String {
String(text.filter { !$0.isPunctuation && !$0.isWhitespace })
}
}

View File

@ -14,7 +14,7 @@
找物、收藏、位置、手工录入和批量草稿使用项目 API。搜索和编辑表单可以手动收起键盘,表单也支持下滑收起。照片从系统照片选择器导入,支持平移、调整放大比例与方形剪裁,按最长边 1600 像素压缩为 JPEG。客户端最多接受 30 MiB 来源文件,上传上限为 5 MiB,每件最多六张。列表使用服务端生成的缩略图。
录入页支持普通话本机转写。说完后可核对和修改原话,规则优先,模型由用户选择。语音自动保存默认关闭。同一个账号的设置只作用于当前设备。家庭邀请用对方的见物账号发出,接收者在空间列表接受。 [语音、搜索和家庭邀请](../../docs/architecture/mobile-capture-and-search.md)
录入页支持普通话本机分段转写。默认点按开始和结束,也可以选择按住说、松手结束。一次最多 25 秒。核对草稿后手动保存,需要模型时由用户选择。家庭邀请用对方的见物账号发出,接收者在空间列表接受。 [语音、搜索和家庭邀请](../../docs/architecture/mobile-capture-and-search.md)
## 构建

View File

@ -15,13 +15,11 @@ flowchart LR
W --> P[物品服务事务写入]
```
iOS 只启动支持本机转写的普通话识别,麦克风采集最长 25 秒,结束后将转写文字交给录入服务。拒绝权限、设备不支持或听不清时仍可打字。音频在内存中处理。识别中的字可即时看见,结束后原话可编辑。 [Apple 语音识别](https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest)
iOS 只启动支持本机转写的普通话识别。录音最多 25 秒,录入页面显示用时。点按与按住两种操作共用同一个录音会话。兼容的 iOS 26 及以上设备有本机语音资源时,使用 `SpeechAnalyzer` 和 `DictationTranscriber`,分开保留已定稿片段与正在更新的文字。录音时若设备支持但缺少资源,系统在后台下载本地识别模型。旧设备或模型未就绪时,回到 `SFSpeechRecognizer`,按语音时间范围和结果变化保留已说片段。音频在内存中处理,录音结束后只留下可编辑的文字。 [Apple SpeechAnalyzer](https://developer.apple.com/documentation/speech/speechanalyzer) · [Apple DictationTranscriber.Result](https://developer.apple.com/documentation/speech/dictationtranscriber/result)
`POST /api/households/{space}/drafts` 的 `source=VOICE` 调用规则,只识别一条明确的放置命令以及有限的数量表达。遇到否定、不确定、多件物品或超出语法的句子,返回空候选,保留原话。用户选择「用 AI 整理」才发起 `source=MODEL` 请求。旧客户端缺省字段时继续走模型。模型已有关闭思考、结构化校验、超时与单实例并发限制。
默认经确认后写入。开启本机账号级自动保存后,App 只对最终转写的单一候选提交 `automatic=true`。录入服务重新校验草稿来源、物品、数量和所在空间中唯一的完整位置路径。只说「右抽屉」时,即使可预填唯一的同名叶子,也保留确认步骤。部分转写、需要模型的文本和冲突候选保留确认。规则匹配表示句式和位置符合条件,语音误听仍可能,需要时经过界面修正。
确认操作复用已部署的 `draft_id + draft_version` 唯一键和 Outbox。物品服务事务内核对当前角色和位置,自动写入还会核对提交时记录的完整路径,位置被移走或改名时拒绝投递。投递重试仍使用同一操作号。完成才显示「已存入」。排错先核对用户角色、草稿来源和完整位置,再按操作号查日志与 Outbox 指标。音频、转写原话和空间名称不进入指标标签。
iOS 录音结束后可预生成草稿,核对并按下「保存物品」才发起确认。部分转写会保留原话并提示先核对。位置含糊时由用户在草稿中选择。确认操作复用已部署的 `draft_id + draft_version` 唯一键和 Outbox,物品服务在事务内重新核对当前角色和位置。兼容旧版客户端的 `automatic=true` 请求仍需要单件、物品及数量一致和唯一完整位置路径,投递时会再次核对路径。排错先看草稿来源和操作号,再查日志与 Outbox 指标。音频、转写原话和空间名称不进入指标标签。
## 检索和权重

View File

@ -4,11 +4,11 @@
入口用「家里有的,心里有数。」和一张家里随手放东西的场景画。用一句实话演示见物的用途,例如「数据线放在书房抽屉」。下方直接进入自己的空间。首次使用时可以新建空空间,或在空间列表里接受家人的邀请。
## 一句话录入
## 录音录入
在录入页点麦克风,说完点停止。转写文字留在输入框,可直接修改。系统先从一句话取出物品、数量和位置,给用户看实际准备保存的内容。默认核对后保存。选择自动保存时,只直接提交规则能完整解析的一件物品,且位置必须对应当前空间内唯一的完整路径。保存成功提示「已存入」,点「知道了」收起。
默认点「开始录音」,说完再点「结束录音」。也可以在「录音设置」选择按住说、松手结束。每次最多 25 秒,录音中能看到经过的秒数和文字。停顿后继续说,前面的转写留在这一段里。
含否定、不确定位置、多个物品或者无法匹配位置的原话交给用户核对。可以改文字、选位置、手工记一件,或明确点「用 AI 整理」。这几步保存共用现有物品确认操作,重复提交只交付一次。
结束后可修改原话。见物先用规则生成物品和位置草稿,较长的描述可以点「用 AI 整理」。核对名称、数量和位置后,点「保存物品」。也可以直接点「手动添加物品」填写表单。录入页右上角的问号可以查看这两套操作。
## 家庭邀请

View File

@ -27,8 +27,9 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前
| TC-21 iOS 登录失败和重试 | R01 | 在原生表单提交错误密码,再断网提交。恢复网络,用正确账号密码继续。 | 表单分别提示凭据错误和网络失败,提交中禁止重复登录,恢复后显示当前账号空间。 |
| TC-22 原生会话与权限 | R01 | 新会话查空间与模型提供方,尝试管理 API。刷新后用旧令牌重试,再退出。 | 两个业务服务都接受有效会话。普通账号无法访问管理 API。刷新令牌只用一次,退出后不可续期。 |
| TC-23 搜索评分与空间 | R04 | 同一空间创建完整名称、别名、前缀和包含同一词的物品。另测查询位置、百分号及从其他账号查该空间。 | 结果按得分排序,位置可搜,百分号按字面匹配,跨空间读取被拒绝。 |
| TC-24 语音和自动保存 | R06 | 点麦克风说「我把两根转接线放在书房右抽屉」。分别关闭和开启自动保存,再测试「好像」和同名抽屉。 | 完整路径唯一时按设置确认或自动保存,成功才弹出回执。否定、模糊位置、只转写部分等情况保留手动核对。 |
| TC-24 录音草稿和保存 | R06 | 说「我把两根转接线放在书房右抽屉」。结束后先查物品列表,再回来修改位置并保存。另测「好像」和同名抽屉。 | 录音结束显示可编辑的文字和草稿。点击「保存物品」后才新增记录。含糊的描述可以改文字或用 AI 整理。 |
| TC-25 按账号邀请 | R01 | 所有者邀请查看者,另一个账号尝试读取和接受。被邀请者同时接受两次,并尝试写入。 | 只有本人看到邀请并加入,两次接受返回同一成员,查看者不能写入。 |
| TC-26 iOS 录音权限 | R06 | 在真机首次点「开始录音」,允许麦克风和语音识别。停止后再次录音。随后在设置关闭语音识别,回到录入页再点一次。 | 授权后可录音和重录。拒绝权限时保留录入页,提示开启权限或直接打字。 |
| TC-27 停顿与录音时长 | R06 | 点按开始,说一句后停两秒再说另一句。分别测试手动结束、录满 25 秒和按住说后松手。 | 两句都在转写中,录音进度显示用时。手动结束、松手或时长达到上限后结束采集。 |
[测试与演示计划](plan.md)