fix: improve model setup and native workflows
This commit is contained in:
@@ -62,6 +62,7 @@ public final class DictationController {
|
||||
private var isBusy = false
|
||||
private var isRecording = false
|
||||
private var modelReady = false
|
||||
private var lastRequestedModelProfile: SpeechModelProfile?
|
||||
/// Идёт ли прогрев прямо сейчас. Отдельно от `modelReady`, потому что
|
||||
/// «грузится» и «нет вовсе» - разные состояния с разными последствиями.
|
||||
private var warmUpTask: Task<Void, Never>?
|
||||
@@ -88,6 +89,7 @@ public final class DictationController {
|
||||
private var powerLifecycle = AudioPowerLifecycle()
|
||||
/// Подмена таймаута распознавания — только тестами, чтобы не ждать живьём.
|
||||
private let transcriptionTimeoutOverride: Double?
|
||||
private let modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)?
|
||||
/// Счётчики доставки: их читает status.json (scripts/gate_app.sh).
|
||||
private let insertionStats: InsertionStats
|
||||
private var settingsObserver: NotificationObserver?
|
||||
@@ -95,6 +97,7 @@ public final class DictationController {
|
||||
public init() {
|
||||
self.settings = .shared
|
||||
self.transcriptionTimeoutOverride = nil
|
||||
self.modelLoader = nil
|
||||
self.insertionStats = InsertionStats()
|
||||
observeSettings()
|
||||
}
|
||||
@@ -102,9 +105,11 @@ public final class DictationController {
|
||||
/// Для тестов и будущих точек сборки.
|
||||
init(settings: DictationSettings,
|
||||
transcriptionTimeout: Double? = nil,
|
||||
insertionStats: InsertionStats = InsertionStats()) {
|
||||
insertionStats: InsertionStats = InsertionStats(),
|
||||
modelLoader: (@Sendable (SpeechModelProfile) async throws -> Void)? = nil) {
|
||||
self.settings = settings
|
||||
self.transcriptionTimeoutOverride = transcriptionTimeout
|
||||
self.modelLoader = modelLoader
|
||||
self.insertionStats = insertionStats
|
||||
observeSettings()
|
||||
}
|
||||
@@ -187,9 +192,17 @@ public final class DictationController {
|
||||
|
||||
public func stop() {
|
||||
if isRecording {
|
||||
// Sleep/выход отменяет клип: не запускаем распознавание и не
|
||||
// создаём raw/audio recovery-артефакт.
|
||||
handleCancel()
|
||||
if recordingPurpose == .meeting {
|
||||
// Уже записанная встреча переживает sleep/выход. ASR здесь
|
||||
// не запускаем: исходник можно разобрать после возвращения.
|
||||
isRecording = false
|
||||
recordingPurpose = .dictation
|
||||
let captured = audio.endRecording()
|
||||
finishMeetingRecording(samples: captured.samples, process: false)
|
||||
hotkeys.resetToggleState()
|
||||
} else {
|
||||
handleCancel()
|
||||
}
|
||||
}
|
||||
maxDurationTask?.cancel()
|
||||
maxDurationTask = nil
|
||||
@@ -223,9 +236,31 @@ public final class DictationController {
|
||||
start()
|
||||
}
|
||||
|
||||
/// Вызывается после явной установки. Греет выбранный движок, не повторяя
|
||||
/// start(), запросы разрешений и запуск записи; настройки не меняет.
|
||||
@discardableResult
|
||||
public func prepareAfterModelInstallation() -> Bool {
|
||||
guard !isBusy, !isRecording, warmUpTask == nil, !powerLifecycle.isSuspended else { return false }
|
||||
DownloadUtils.enforceOffline = true
|
||||
modelReady = false
|
||||
state = .warmingUp
|
||||
warmUpTask = Task { [weak self] in await self?.warmUpModel() }
|
||||
return true
|
||||
}
|
||||
|
||||
private func warmUpModel() async {
|
||||
let profile = settings.speechEngine
|
||||
lastRequestedModelProfile = profile
|
||||
defer {
|
||||
warmUpTask = nil
|
||||
if settings.speechEngine != profile { prepareChangedSpeechModelIfIdle() }
|
||||
}
|
||||
do {
|
||||
try await asr.load(profile: settings.speechEngine)
|
||||
if let modelLoader {
|
||||
try await modelLoader(profile)
|
||||
} else {
|
||||
try await asr.load(profile: profile)
|
||||
}
|
||||
// Рычаг под смешанную речь включен и в ЖИВОЙ диктовке, а не только в
|
||||
// CLI: без него термины внутри русской фразы ломаются ровно там, где
|
||||
// владелец диктует каждый день.
|
||||
@@ -233,6 +268,7 @@ public final class DictationController {
|
||||
modelReady = true
|
||||
if state == .warmingUp { state = .ready }
|
||||
} catch {
|
||||
modelReady = false
|
||||
log("ASR warmup failed: \(error.localizedDescription)")
|
||||
state = .unavailable(error.localizedDescription)
|
||||
}
|
||||
@@ -312,35 +348,123 @@ public final class DictationController {
|
||||
/// Файл пишется ДО разбора и остаётся на диске, даже если разбор упадёт:
|
||||
/// запись заседания дороже протокола, её нельзя терять из-за отказа
|
||||
/// распознавателя.
|
||||
private func finishMeetingRecording(samples: [Float]) {
|
||||
private func finishMeetingRecording(samples: [Float], process: Bool = true) {
|
||||
state = .ready
|
||||
guard !samples.isEmpty else {
|
||||
log("meeting: пустая запись, сохранять нечего")
|
||||
if process {
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = L("meeting.emptyRecording", "Звук не записался")
|
||||
alert.informativeText = L("meeting.emptyRecording.help", "Проверь микрофон и повтори запись встречи.")
|
||||
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||
_ = runMeetingAlert(alert)
|
||||
}
|
||||
return
|
||||
}
|
||||
do {
|
||||
let url = try meetingRecordingScratchURL()
|
||||
let recording = try writeMeetingWAV(samples: samples,
|
||||
sampleRate: SAMPLE_RATE,
|
||||
to: url)
|
||||
log("meeting: записано \(Int(recording.seconds)) с в \(url.lastPathComponent)")
|
||||
Task { @MainActor in
|
||||
let pipeline = MeetingPipeline()
|
||||
let title = "Встреча " + meetingDateFormatter().string(from: Date())
|
||||
do {
|
||||
let result = try await pipeline.run(audio: recording.url, title: title)
|
||||
log("meeting: протокол готов, реплик \(result.turns.count)")
|
||||
} catch {
|
||||
// Разбор упал, но звук уже на диске - его можно принести в
|
||||
// окно встреч руками и разобрать ещё раз.
|
||||
log("meeting: разбор отказал (\(error)), звук остался в \(recording.url.path)")
|
||||
let date = Date()
|
||||
isBusy = true
|
||||
state = .transcribing
|
||||
let recording = saveMeetingRecording(samples: samples, at: date)
|
||||
isBusy = false
|
||||
state = .ready
|
||||
guard let recording else { return }
|
||||
log("meeting: записано \(Int(recording.seconds)) с в \(recording.url.lastPathComponent)")
|
||||
guard process else { return }
|
||||
processMeetingRecording(recording, at: date)
|
||||
}
|
||||
|
||||
private func saveMeetingRecording(samples: [Float], at date: Date) -> MeetingRecording? {
|
||||
while true {
|
||||
do {
|
||||
return try writeMeetingWAV(samples: samples, sampleRate: SAMPLE_RATE,
|
||||
to: meetingRecordingScratchURL(at: date))
|
||||
} catch {
|
||||
log("meeting: не удалось сохранить звук (\(error))")
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = L("meeting.saveFailed", "Не удалось сохранить запись встречи")
|
||||
alert.informativeText = L("meeting.saveFailed.help", "Звук ещё в памяти. Освободи место на диске и повтори сохранение. Если удалить запись, восстановить её будет нельзя.")
|
||||
+ "\n\n" + error.localizedDescription
|
||||
alert.addButton(withTitle: L("meeting.retrySave", "Повторить сохранение"))
|
||||
alert.addButton(withTitle: L("meeting.discardUnsaved", "Удалить несохранённую запись"))
|
||||
guard runMeetingAlert(alert) == .alertFirstButtonReturn else { return nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Тот же барьер, что у диктовки: пока встреча разбирается, второй
|
||||
/// распознаватель не запускается ни хоткеем, ни повтором из сообщения.
|
||||
func beginMeetingProcessing() -> UInt64? {
|
||||
guard !isBusy, !isRecording else { return nil }
|
||||
transcriptionGeneration &+= 1
|
||||
isBusy = true
|
||||
state = .transcribing
|
||||
return transcriptionGeneration
|
||||
}
|
||||
|
||||
private func processMeetingRecording(_ recording: MeetingRecording, at date: Date) {
|
||||
guard let generation = beginMeetingProcessing() else { return }
|
||||
let title = L("meeting.title", "Встреча") + " " + meetingDateFormatter().string(from: date)
|
||||
let pipeline = MeetingPipeline(transcriber: AudioFileTranscriber(engine: settings.speechEngine,
|
||||
initialPrompt: whisperDefaultInitialPrompt))
|
||||
pipelineTask = Task { [weak self] in
|
||||
guard let self else { return }
|
||||
defer { self.finishTranscription(generation: generation) }
|
||||
do {
|
||||
let result = try await pipeline.run(audio: recording.url, title: title, at: date)
|
||||
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
|
||||
self.finishTranscription(generation: generation)
|
||||
let alert = NSAlert()
|
||||
alert.messageText = L("meeting.protocolReady", "Протокол встречи готов")
|
||||
alert.informativeText = result.artifacts.transcript.path
|
||||
if !result.speakersResolved {
|
||||
alert.informativeText += "\n\n" + L("meeting.speakersUnresolved", "Не удалось разделить говорящих. Текст сохранён одной репликой.")
|
||||
}
|
||||
alert.addButton(withTitle: L("meeting.openProtocol", "Открыть протокол"))
|
||||
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
|
||||
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||
switch self.runMeetingAlert(alert) {
|
||||
case .alertFirstButtonReturn:
|
||||
if !NSWorkspace.shared.open(result.artifacts.transcript) {
|
||||
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.transcript])
|
||||
}
|
||||
case .alertSecondButtonReturn:
|
||||
NSWorkspace.shared.activateFileViewerSelecting([result.artifacts.audio])
|
||||
default: break
|
||||
}
|
||||
} catch {
|
||||
guard !Task.isCancelled, self.transcriptionGeneration == generation else { return }
|
||||
self.finishTranscription(generation: generation)
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = L("meeting.processingFailed", "Не удалось разобрать встречу")
|
||||
let reason = (error as? MeetingPipelineFailure)?.rawValue ?? error.localizedDescription
|
||||
alert.informativeText = reason + "\n\n"
|
||||
+ L("meeting.recordingSaved", "Запись сохранена. Можно повторить разбор или открыть её в Finder.")
|
||||
+ "\n" + recording.url.path
|
||||
alert.addButton(withTitle: L("meeting.retryProcessing", "Повторить разбор"))
|
||||
alert.addButton(withTitle: L("meeting.showRecording", "Показать запись"))
|
||||
alert.addButton(withTitle: L("meeting.close", "Закрыть"))
|
||||
switch self.runMeetingAlert(alert) {
|
||||
case .alertFirstButtonReturn:
|
||||
self.processMeetingRecording(recording, at: date)
|
||||
case .alertSecondButtonReturn:
|
||||
NSWorkspace.shared.activateFileViewerSelecting([recording.url])
|
||||
default: break
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
log("meeting: не удалось сохранить звук (\(error))")
|
||||
}
|
||||
}
|
||||
|
||||
private func runMeetingAlert(_ alert: NSAlert) -> NSApplication.ModalResponse {
|
||||
// LSUIElement не имеет обычного главного окна; alert должен оказаться
|
||||
// над постоянной floating-плашкой, иначе вопрос останется под ней.
|
||||
alert.window.level = .floating
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
return alert.runModal()
|
||||
}
|
||||
|
||||
/// Кого звать, когда с плашки просят настройки. Ставит приложение: у
|
||||
/// модуля диктовки окна настроек нет и быть не должно.
|
||||
public var onOpenSettings: (() -> Void)?
|
||||
@@ -361,6 +485,12 @@ public final class DictationController {
|
||||
hotkeys.setTranslationHotkeyEnabled(settings.translationModeEnabled)
|
||||
hotkeys.setAlternateCompletionEnabled(settings.alternateCompletionEnabled)
|
||||
hotkeys.setTriggerMode(settings.triggerMode)
|
||||
prepareChangedSpeechModelIfIdle()
|
||||
}
|
||||
|
||||
private func prepareChangedSpeechModelIfIdle() {
|
||||
guard let previous = lastRequestedModelProfile, previous != settings.speechEngine else { return }
|
||||
_ = prepareAfterModelInstallation()
|
||||
}
|
||||
|
||||
private func observeSettings() {
|
||||
@@ -556,7 +686,15 @@ public final class DictationController {
|
||||
}
|
||||
|
||||
public func toggleDictationFromUI() {
|
||||
handlePress(purpose: .dictation)
|
||||
if isRecording {
|
||||
// Кнопка HUD уже показывает «Закончить запись». Завершаем текущий
|
||||
// purpose тем же путём, что хоткей, не меняя встречу на диктовку.
|
||||
hotkeys.resetToggleState()
|
||||
handleRelease(shortcut: .standard,
|
||||
hotkeyDetectedAt: ProcessInfo.processInfo.systemUptime)
|
||||
} else {
|
||||
handlePress(purpose: .dictation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Начать запись для промпта прямо из интерфейса. Тот же вход, что и у
|
||||
@@ -571,6 +709,7 @@ public final class DictationController {
|
||||
}
|
||||
|
||||
private func handlePress(purpose: DictationRecordingPurpose) {
|
||||
prepareChangedSpeechModelIfIdle()
|
||||
if let refusal = startRefusal() {
|
||||
log("dictation: press refused — \(refusal.rawValue)")
|
||||
hud?.startRefused(refusal)
|
||||
@@ -1249,6 +1388,7 @@ public final class DictationController {
|
||||
default:
|
||||
break
|
||||
}
|
||||
prepareChangedSpeechModelIfIdle()
|
||||
}
|
||||
|
||||
private func handleCancel() {
|
||||
@@ -1268,8 +1408,9 @@ public final class DictationController {
|
||||
|
||||
private func scheduleMaxDurationAutoRelease() {
|
||||
maxDurationTask?.cancel()
|
||||
let limit = Self.recordingLimitSeconds(for: recordingPurpose)
|
||||
maxDurationTask = Task { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: UInt64(MAX_RECORDING_SECONDS) * 1_000_000_000)
|
||||
try? await Task.sleep(nanoseconds: UInt64(limit) * 1_000_000_000)
|
||||
guard !Task.isCancelled, let self, self.isRecording else { return }
|
||||
log("dictation: max recording duration reached — auto release")
|
||||
self.hotkeys.resetToggleState()
|
||||
@@ -1278,6 +1419,10 @@ public final class DictationController {
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated static func recordingLimitSeconds(for purpose: DictationRecordingPurpose) -> TimeInterval {
|
||||
purpose == .meeting ? meetingRecordingLimitSeconds : MAX_RECORDING_SECONDS
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
func simulateActiveRecordingForTesting() {
|
||||
audio.beginRecording()
|
||||
|
||||
@@ -122,7 +122,12 @@ public func dictationHUDNextLanguage(after current: DictationLanguage) -> Dictat
|
||||
/// значком без кнопки.
|
||||
final class DictationHUDActionButton: NSView {
|
||||
var action: DictationHUDAction {
|
||||
didSet { if action != oldValue { needsDisplay = true } }
|
||||
didSet {
|
||||
guard action != oldValue else { return }
|
||||
setAccessibilityLabel(action.title)
|
||||
toolTip = action.title
|
||||
needsDisplay = true
|
||||
}
|
||||
}
|
||||
var onPress: ((DictationHUDActionID) -> Void)?
|
||||
/// Кого звать, когда мышь пришла на кнопку или ушла с неё. Владелец
|
||||
@@ -132,6 +137,8 @@ final class DictationHUDActionButton: NSView {
|
||||
var onHover: ((DictationHUDAction?) -> Void)?
|
||||
|
||||
private var pressed = false
|
||||
private let reduceMotion: () -> Bool
|
||||
private var displayOptionsObserver: DictationHUDNotificationObserver?
|
||||
private var hovered = false {
|
||||
didSet {
|
||||
guard hovered != oldValue else { return }
|
||||
@@ -148,6 +155,14 @@ final class DictationHUDActionButton: NSView {
|
||||
guard let layer else { return }
|
||||
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
|
||||
layer.position = CGPoint(x: frame.midX, y: frame.midY)
|
||||
guard !reduceMotion() else {
|
||||
layer.removeAnimation(forKey: "irizHoverLift")
|
||||
CATransaction.begin()
|
||||
CATransaction.setDisableActions(true)
|
||||
layer.transform = CATransform3DIdentity
|
||||
CATransaction.commit()
|
||||
return
|
||||
}
|
||||
let scale: CGFloat = hovered ? 1.18 : 1
|
||||
let lift = CABasicAnimation(keyPath: "transform.scale")
|
||||
lift.fromValue = layer.value(forKeyPath: "transform.scale") ?? 1
|
||||
@@ -168,12 +183,22 @@ final class DictationHUDActionButton: NSView {
|
||||
}
|
||||
private var tracking: NSTrackingArea?
|
||||
|
||||
init(action: DictationHUDAction) {
|
||||
init(action: DictationHUDAction,
|
||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter) {
|
||||
self.action = action
|
||||
self.reduceMotion = reduceMotion
|
||||
super.init(frame: .zero)
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityRole(.button)
|
||||
setAccessibilityLabel(action.title)
|
||||
toolTip = action.title
|
||||
displayOptionsObserver = DictationHUDNotificationObserver(displayOptionsCenter.addObserver(
|
||||
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
|
||||
object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.applyHoverLift() }
|
||||
}, center: displayOptionsCenter)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
@@ -181,6 +206,12 @@ final class DictationHUDActionButton: NSView {
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
override func accessibilityPerformPress() -> Bool {
|
||||
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||
onPress(action.id)
|
||||
return true
|
||||
}
|
||||
|
||||
override func updateTrackingAreas() {
|
||||
if let tracking { removeTrackingArea(tracking) }
|
||||
let area = NSTrackingArea(rect: .zero,
|
||||
@@ -214,7 +245,7 @@ final class DictationHUDActionButton: NSView {
|
||||
pressed = false
|
||||
needsDisplay = true
|
||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||
onPress?(action.id)
|
||||
_ = accessibilityPerformPress()
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// Порядок показа плашки «идёт голос»: что и когда попадает на экран.
|
||||
//
|
||||
// Здесь нет ни AppKit, ни решений — решения в DictationHUD.swift, рисование в
|
||||
// Решения в DictationHUD.swift, рисование в
|
||||
// DictationHUDWindow.swift. Такое разделение позволяет проверить тестом всё
|
||||
// поведение (что показали, что погасили, крутится ли опрос уровня), ни разу не
|
||||
// поднимая живое окно: под `swift test` его и не поднять.
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
/// Поверхность, на которой плашка рисуется. Единственная реализация в продукте —
|
||||
/// `DictationHUDPanelSurface` (NSPanel). В тестах подставляется запоминающая
|
||||
@@ -112,6 +113,7 @@ final class DictationHUDPresenter {
|
||||
|
||||
private var surface: DictationHUDSurface?
|
||||
private var dismissTimer: Timer?
|
||||
private var displayOptionsObserver: DictationHUDNotificationObserver?
|
||||
private var smoothedLevel: Float = 0
|
||||
private var lastLevelSequence: UInt64?
|
||||
private var sameLevelSequenceTicks = 0
|
||||
@@ -131,6 +133,7 @@ final class DictationHUDPresenter {
|
||||
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
||||
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
|
||||
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
||||
self.levelSnapshot = levelSnapshot
|
||||
self.staleGuardEnabled = true
|
||||
@@ -145,6 +148,7 @@ final class DictationHUDPresenter {
|
||||
self.pump = pump
|
||||
self.makeSurface = surface
|
||||
pump.onTick = { [weak self] in self?.render() }
|
||||
observeDisplayOptions(in: displayOptionsCenter)
|
||||
}
|
||||
|
||||
/// Совместимость тестов и простых поверхностей без sequence. Живой продукт
|
||||
@@ -155,6 +159,7 @@ final class DictationHUDPresenter {
|
||||
recordingPurpose: @escaping () -> DictationRecordingPurpose = { .dictation },
|
||||
reduceMotion: @escaping () -> Bool = { dictationHUDReduceMotionEnabled() },
|
||||
pump: DictationHUDLevelPump = DictationHUDLevelPump(),
|
||||
displayOptionsCenter: NotificationCenter = NSWorkspace.shared.notificationCenter,
|
||||
surface: @escaping () -> DictationHUDSurface = { DictationHUDPanelSurface() }) {
|
||||
self.levelSnapshot = { (level(), 0) }
|
||||
self.staleGuardEnabled = false
|
||||
@@ -169,6 +174,18 @@ final class DictationHUDPresenter {
|
||||
self.pump = pump
|
||||
self.makeSurface = surface
|
||||
pump.onTick = { [weak self] in self?.render() }
|
||||
observeDisplayOptions(in: displayOptionsCenter)
|
||||
}
|
||||
|
||||
private func observeDisplayOptions(in center: NotificationCenter) {
|
||||
displayOptionsObserver = DictationHUDNotificationObserver(center.addObserver(
|
||||
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification,
|
||||
object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
// Ожидание и покой не опрашивают уровень: без уведомления уже
|
||||
// открытая плашка не узнаёт, что владелец изменил Reduce Motion.
|
||||
MainActor.assumeIsolated { self?.render() }
|
||||
}, center: center)
|
||||
}
|
||||
|
||||
// MARK: - Входы конвейера
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
// у неё нет подписей, она говорит цветом и формой. Панель - другое: её работа
|
||||
// и есть показать текст.
|
||||
import AppKit
|
||||
import IrizCore
|
||||
|
||||
/// Сколько строк займёт текст на самом деле.
|
||||
///
|
||||
@@ -298,14 +299,33 @@ final class DictationHUDTranscriptView: NSView {
|
||||
/// на любом фоне.
|
||||
final class DictationHUDCopyPill: NSView {
|
||||
var title: String = "" {
|
||||
didSet { if title != oldValue { needsDisplay = true } }
|
||||
didSet {
|
||||
guard title != oldValue else { return }
|
||||
setAccessibilityLabel(title)
|
||||
needsDisplay = true
|
||||
}
|
||||
}
|
||||
var onPress: (() -> Void)?
|
||||
|
||||
private var pressed = false
|
||||
|
||||
override init(frame frameRect: NSRect) {
|
||||
super.init(frame: frameRect)
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityRole(.button)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
override func accessibilityPerformPress() -> Bool {
|
||||
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||
onPress()
|
||||
return true
|
||||
}
|
||||
|
||||
var fittingWidth: CGFloat {
|
||||
(title as NSString).size(withAttributes: [.font: Self.font]).width + 26
|
||||
}
|
||||
@@ -321,7 +341,7 @@ final class DictationHUDCopyPill: NSView {
|
||||
pressed = false
|
||||
needsDisplay = true
|
||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||
onPress?()
|
||||
_ = accessibilityPerformPress()
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
@@ -359,8 +379,24 @@ final class DictationHUDCloseRing: NSView {
|
||||
|
||||
private var pressed = false
|
||||
|
||||
override init(frame frameRect: NSRect) {
|
||||
super.init(frame: frameRect)
|
||||
setAccessibilityElement(true)
|
||||
setAccessibilityRole(.button)
|
||||
setAccessibilityLabel(L("common.close", "Закрыть"))
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) не поддерживается") }
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
override func accessibilityPerformPress() -> Bool {
|
||||
guard !isHiddenOrHasHiddenAncestor, let onPress else { return false }
|
||||
onPress()
|
||||
return true
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
pressed = true
|
||||
needsDisplay = true
|
||||
@@ -370,7 +406,7 @@ final class DictationHUDCloseRing: NSView {
|
||||
pressed = false
|
||||
needsDisplay = true
|
||||
guard bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
|
||||
onPress?()
|
||||
_ = accessibilityPerformPress()
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
|
||||
@@ -4,12 +4,17 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
import QuartzCore
|
||||
import IrizCore
|
||||
|
||||
private final class DictationHUDNotificationObserver: @unchecked Sendable {
|
||||
final class DictationHUDNotificationObserver: @unchecked Sendable {
|
||||
let token: NSObjectProtocol
|
||||
private let center: NotificationCenter
|
||||
|
||||
init(_ token: NSObjectProtocol) { self.token = token }
|
||||
deinit { NotificationCenter.default.removeObserver(token) }
|
||||
init(_ token: NSObjectProtocol, center: NotificationCenter = .default) {
|
||||
self.token = token
|
||||
self.center = center
|
||||
}
|
||||
deinit { center.removeObserver(token) }
|
||||
}
|
||||
|
||||
private final class DictationHUDDisplayLinkStorage: @unchecked Sendable {
|
||||
@@ -941,6 +946,13 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
|
||||
container.delegate = self
|
||||
container.setAccessibilityElement(true)
|
||||
container.setAccessibilityRole(.group)
|
||||
container.setAccessibilityCustomActions([
|
||||
NSAccessibilityCustomAction(name: L("hud.toggleExpanded", "Развернуть или свернуть плашку")) { [weak self] in
|
||||
guard let handler = self?.openToggledHandler else { return false }
|
||||
handler()
|
||||
return true
|
||||
}
|
||||
])
|
||||
let capsule = DictationHUDCapsuleView(frame: CGRect(origin: .zero,
|
||||
size: DICTATION_HUD_BASE_SIZE))
|
||||
let hint = DictationHUDHintView(frame: .zero)
|
||||
@@ -1292,9 +1304,16 @@ final class DictationHUDPanelSurface: NSObject, DictationHUDSurface, DictationHU
|
||||
}
|
||||
if reduceMotionEnabled() {
|
||||
stopMotion()
|
||||
hoverProgress = hoverAnimation?.to ?? hoverProgress
|
||||
hoverAnimation = nil
|
||||
hint?.appearanceProgress = hoverProgress
|
||||
// Уже начатый морф тоже завершается при смене настройки.
|
||||
transcriptProgress = transcriptTarget
|
||||
advanceTranscript(dt: 0)
|
||||
revealAnimation = nil
|
||||
revealProgress = 1
|
||||
capsule?.revealProgress = 1
|
||||
layoutPanel(display: true)
|
||||
} else {
|
||||
startMotionIfNeeded()
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import IrizCore
|
||||
/// сортировки и то, что показывается владельцу. Ключ именно имя, а не mtime:
|
||||
/// после импорта из старого приложения mtime врёт (см. PromptEnvelope.swift,
|
||||
/// `latestDictation`) — папки пишутся на диск в обратном порядку номеров.
|
||||
public struct DictationHistoryEntry: Equatable, Identifiable {
|
||||
public struct DictationHistoryEntry: Equatable, Identifiable, Sendable {
|
||||
let directory: URL
|
||||
public let label: String
|
||||
/// Сырьё — ответ ASR байт в байт. Есть всегда, иначе записи нет.
|
||||
@@ -66,11 +66,16 @@ public let DICTATION_HISTORY_KEEP_LIMIT = 500
|
||||
/// никогда.
|
||||
public func dictationHistoryDirectories(in dictationsRoot: URL,
|
||||
fileManager: FileManager = .default) -> [URL] {
|
||||
let urls = (try? fileManager.contentsOfDirectory(
|
||||
(try? readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)) ?? []
|
||||
}
|
||||
|
||||
private func readDictationHistoryDirectories(in dictationsRoot: URL,
|
||||
fileManager: FileManager) throws -> [URL] {
|
||||
let urls = try fileManager.contentsOfDirectory(
|
||||
at: dictationsRoot,
|
||||
includingPropertiesForKeys: [.isDirectoryKey],
|
||||
options: [.skipsHiddenFiles]
|
||||
)) ?? []
|
||||
)
|
||||
return urls
|
||||
.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
|
||||
.sorted { $0.lastPathComponent > $1.lastPathComponent }
|
||||
@@ -79,7 +84,14 @@ public func dictationHistoryDirectories(in dictationsRoot: URL,
|
||||
public func dictationHistoryEntries(in dictationsRoot: URL,
|
||||
limit: Int? = nil,
|
||||
fileManager: FileManager = .default) -> [DictationHistoryEntry] {
|
||||
var directories = dictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
|
||||
(try? readDictationHistoryEntries(in: dictationsRoot, limit: limit, fileManager: fileManager)) ?? []
|
||||
}
|
||||
|
||||
/// Для интерфейса: недоступный каталог — ошибка, а не пустая история.
|
||||
public func readDictationHistoryEntries(in dictationsRoot: URL,
|
||||
limit: Int? = nil,
|
||||
fileManager: FileManager = .default) throws -> [DictationHistoryEntry] {
|
||||
var directories = try readDictationHistoryDirectories(in: dictationsRoot, fileManager: fileManager)
|
||||
// Обрезаем ДО чтения содержимого: смысл потолка в том, чтобы не открывать
|
||||
// тысячи файлов, а не в том, чтобы открыть их и показать сотню.
|
||||
if let limit, directories.count > limit { directories = Array(directories.prefix(limit)) }
|
||||
@@ -199,7 +211,8 @@ enum DictationHistoryKeyAction: Equatable {
|
||||
|
||||
func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
||||
charactersIgnoringModifiers: String?,
|
||||
hasCommand: Bool) -> DictationHistoryKeyAction {
|
||||
hasCommand: Bool,
|
||||
hasTextSelection: Bool = false) -> DictationHistoryKeyAction {
|
||||
if hasCommand {
|
||||
// ⌘⌫ здесь СОЗНАТЕЛЬНО не занят. Это документированный системный
|
||||
// шорткат текстового поля («удалить от курсора до начала строки»), а
|
||||
@@ -208,7 +221,7 @@ func dictationHistoryKeyAction(keyCode: CGKeyCode,
|
||||
// расшифровку речи клиента. Удаление живёт в контекстном меню, где его
|
||||
// нельзя нажать не глядя.
|
||||
switch charactersIgnoringModifiers?.lowercased() {
|
||||
case "c": return .copySelected
|
||||
case "c": return hasTextSelection ? .passThrough : .copySelected
|
||||
default: return .passThrough
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,9 +59,14 @@ func pasteboardRestoreDecision(transientChangeCount: Int?,
|
||||
}
|
||||
|
||||
@MainActor
|
||||
enum DictationHistoryClipboard {
|
||||
public enum DictationHistoryClipboard {
|
||||
private static var pending: HistoryClipboardTransaction?
|
||||
|
||||
/// Общий путь копирования для настроек и плавающего окна.
|
||||
public static func copy(_ text: String) -> Bool {
|
||||
copy(text, pasteboard: .general)
|
||||
}
|
||||
|
||||
/// Кладёт текст в буфер. `false` — буфер отказал, вызывающий обязан сказать
|
||||
/// владельцу, что копирование не состоялось.
|
||||
///
|
||||
@@ -69,7 +74,7 @@ enum DictationHistoryClipboard {
|
||||
/// дописывает в живой лог владельца.
|
||||
@discardableResult
|
||||
static func copy(_ text: String,
|
||||
pasteboard: NSPasteboard = .general,
|
||||
pasteboard: NSPasteboard,
|
||||
hold: TimeInterval = HISTORY_CLIPBOARD_HOLD_SECONDS,
|
||||
logLine: @escaping (String) -> Void = { log($0) }) -> Bool {
|
||||
quench(reason: "вытеснено следующим копированием")
|
||||
|
||||
@@ -35,6 +35,7 @@ final class DictationHistoryPresenter {
|
||||
/// Поднят лист подтверждения «очистить всё». Пока он висит, клавиши окна
|
||||
/// не работают: Escape обязан закрывать вопрос, а не всё окно под ним.
|
||||
private var isConfirming = false
|
||||
private var presentationGeneration = 0
|
||||
private let dictationsRoot: () throws -> URL
|
||||
|
||||
init(dictationsRoot: @escaping () throws -> URL = { try DictationStore.dictationsDirectory() }) {
|
||||
@@ -59,6 +60,7 @@ final class DictationHistoryPresenter {
|
||||
// MARK: - Показ
|
||||
|
||||
private func present(rescue: DictationRescue?) {
|
||||
presentationGeneration += 1
|
||||
let entries: [DictationHistoryEntry]
|
||||
if rescue == nil {
|
||||
// Список читается ПОСЛЕ показа окна, в фоне. Владелец: «открываю
|
||||
@@ -116,12 +118,7 @@ final class DictationHistoryPresenter {
|
||||
model.focusSearchField = rescue == nil
|
||||
installKeyMonitor()
|
||||
if rescue == nil {
|
||||
model.didLoadAll = false
|
||||
model.onSearchStarted = { [weak self, weak model] in
|
||||
guard let self, let model else { return }
|
||||
self.loadAllForSearch(into: model)
|
||||
}
|
||||
loadEntriesInBackground(into: model)
|
||||
model.reload(from: dictationsRoot)
|
||||
}
|
||||
if let rescue {
|
||||
// Ни имени приложения, ни самого текста в логе: лог живёт на диске
|
||||
@@ -133,55 +130,6 @@ final class DictationHistoryPresenter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Прочитать надиктовки с диска и отдать их окну, когда прочитаются.
|
||||
///
|
||||
/// Отдельным ходом, а не внутри показа: чтение занимает секунды на большом
|
||||
/// каталоге, а окно обязано открыться мгновенно. Пока список едет, в окне
|
||||
/// стоит честная строка «Читаю надиктовки…», а не пустота, которую легко
|
||||
/// прочитать как «ничего нет».
|
||||
private func loadEntriesInBackground(into model: DictationHistoryModel) {
|
||||
model.isLoading = true
|
||||
let root = try? dictationsRoot()
|
||||
guard let root else {
|
||||
model.isLoading = false
|
||||
log("history: cannot reach dictations directory")
|
||||
return
|
||||
}
|
||||
Task.detached(priority: .userInitiated) {
|
||||
let startedAt = ProcessInfo.processInfo.systemUptime
|
||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT)
|
||||
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
|
||||
await MainActor.run {
|
||||
model.load(found)
|
||||
model.isLoading = false
|
||||
log(String(format: "history: %d записей прочитано за %.0f мс (в фоне)",
|
||||
found.count, spent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Догрузить остальное хранимое - по первому же поиску.
|
||||
///
|
||||
/// Окно открывается сотней свежих: их хватает, чтобы забрать вчерашнее.
|
||||
/// Но поиск по сотне врал бы молча - человек ищет фразу, которая лежит
|
||||
/// двухсотой, и получает «ничего не нашлось». Поэтому первый ввод в поле
|
||||
/// поиска дочитывает всё, что хранится, и делает это один раз за показ.
|
||||
private func loadAllForSearch(into model: DictationHistoryModel) {
|
||||
guard !model.didLoadAll else { return }
|
||||
model.didLoadAll = true
|
||||
guard let root = try? dictationsRoot() else { return }
|
||||
Task.detached(priority: .userInitiated) {
|
||||
let startedAt = ProcessInfo.processInfo.systemUptime
|
||||
let found = dictationHistoryEntries(in: root, limit: DICTATION_HISTORY_KEEP_LIMIT)
|
||||
let spent = (ProcessInfo.processInfo.systemUptime - startedAt) * 1000
|
||||
await MainActor.run {
|
||||
model.load(found)
|
||||
log(String(format: "history: поиск дочитал %d записей за %.0f мс",
|
||||
found.count, spent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func makePanel(model: DictationHistoryModel) -> DictationHistoryPanel {
|
||||
let panel = DictationHistoryPanel(
|
||||
contentRect: historyPanelFrame(),
|
||||
@@ -241,7 +189,10 @@ final class DictationHistoryPresenter {
|
||||
// MARK: - Закрытие и возврат фокуса
|
||||
|
||||
private func close(returningFocus: Bool) {
|
||||
presentationGeneration += 1
|
||||
removeKeyMonitor()
|
||||
model?.cancelLoading()
|
||||
model?.isClearing = false
|
||||
model?.focusSearchField = false
|
||||
// Спасённый текст живёт ровно столько, сколько висит окно. Иначе
|
||||
// следующее открытие истории по хоткею подняло бы чужую позавчерашнюю
|
||||
@@ -400,6 +351,7 @@ final class DictationHistoryPresenter {
|
||||
|
||||
private func copy(text: String) {
|
||||
guard DictationHistoryClipboard.copy(text) else {
|
||||
model?.showError(L("history.copyFailed", "Не удалось скопировать. Попробуй ещё раз."))
|
||||
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
||||
return
|
||||
}
|
||||
@@ -407,21 +359,49 @@ final class DictationHistoryPresenter {
|
||||
}
|
||||
|
||||
private func delete(_ entry: DictationHistoryEntry) {
|
||||
guard model?.isClearing != true else { return }
|
||||
do {
|
||||
try removeDictationHistoryEntry(entry)
|
||||
log("history: entry \(entry.label) moved to Trash with its directory")
|
||||
reload()
|
||||
} catch {
|
||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||
model?.showError(L("history.deleteFailed", "Не удалось переместить запись в Корзину. Попробуй ещё раз."))
|
||||
if DictationSettings.shared.playFeedbackSounds { Sounds.playError() }
|
||||
}
|
||||
reload()
|
||||
}
|
||||
|
||||
private func clearAll() {
|
||||
guard let model, let panel, !model.entries.isEmpty, !isConfirming else { return }
|
||||
guard let model, let panel, !model.entries.isEmpty, !isConfirming, !model.isClearing else { return }
|
||||
let generation = presentationGeneration
|
||||
model.isClearing = true
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
do {
|
||||
let root = try self.dictationsRoot()
|
||||
let doomed = try await Task.detached(priority: .userInitiated) {
|
||||
try readDictationHistoryEntries(in: root)
|
||||
}.value
|
||||
guard self.presentationGeneration == generation, panel.isVisible else { return }
|
||||
guard !doomed.isEmpty else {
|
||||
model.isClearing = false
|
||||
self.reload()
|
||||
return
|
||||
}
|
||||
self.confirmClearAll(doomed, model: model, panel: panel)
|
||||
} catch {
|
||||
guard self.presentationGeneration == generation else { return }
|
||||
model.isClearing = false
|
||||
model.showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func confirmClearAll(_ doomed: [DictationHistoryEntry],
|
||||
model: DictationHistoryModel,
|
||||
panel: DictationHistoryPanel) {
|
||||
// Число записей — ДО удаления и в самом вопросе: иначе владелец
|
||||
// подтверждает вслепую.
|
||||
let doomed = model.entries
|
||||
// подтверждает вслепую. Снимок включает весь архив, а не видимую сотню.
|
||||
let alert = NSAlert()
|
||||
alert.alertStyle = .warning
|
||||
alert.messageText = dictationHistoryClearConfirmation(count: doomed.count)
|
||||
@@ -438,31 +418,37 @@ final class DictationHistoryPresenter {
|
||||
guard let self else { return }
|
||||
self.isConfirming = false
|
||||
guard response == .alertFirstButtonReturn else {
|
||||
model.isClearing = false
|
||||
log("history: clear all cancelled (\(doomed.count) entries kept)")
|
||||
return
|
||||
}
|
||||
var deleted = 0
|
||||
for entry in doomed {
|
||||
do {
|
||||
try removeDictationHistoryEntry(entry)
|
||||
deleted += 1
|
||||
} catch {
|
||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||
Task { @MainActor in
|
||||
let deleted = await Task.detached(priority: .userInitiated) {
|
||||
var deleted = 0
|
||||
for entry in doomed {
|
||||
do {
|
||||
try removeDictationHistoryEntry(entry)
|
||||
deleted += 1
|
||||
} catch {
|
||||
log("history: cannot delete \(entry.label): \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
return deleted
|
||||
}.value
|
||||
model.isClearing = false
|
||||
log("history: cleared \(deleted) of \(doomed.count) entries")
|
||||
self.reload()
|
||||
if deleted != doomed.count {
|
||||
model.showError(Lf("history.clearFailed", "Не удалось переместить в Корзину: %d из %d. Остальные записи уже в Корзине.", doomed.count - deleted, doomed.count))
|
||||
}
|
||||
}
|
||||
log("history: cleared \(deleted) of \(doomed.count) entries")
|
||||
self.reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func reload() {
|
||||
guard let model else { return }
|
||||
do {
|
||||
model.load(dictationHistoryEntries(in: try dictationsRoot()))
|
||||
} catch {
|
||||
log("history: cannot reach dictations directory: \(error.localizedDescription)")
|
||||
}
|
||||
model.reload(from: dictationsRoot)
|
||||
}
|
||||
|
||||
// MARK: - Клавиши
|
||||
@@ -488,10 +474,14 @@ final class DictationHistoryPresenter {
|
||||
/// `true` — нажатие съедено окном, в поле поиска не уходит.
|
||||
private func handle(_ event: NSEvent) -> Bool {
|
||||
guard let model, !isConfirming else { return false }
|
||||
// Выделенный текст принадлежит редактору поиска/спасения: ⌘C должен
|
||||
// копировать именно выделение, не выбранную запись и не закрывать окно.
|
||||
let editor = panel?.firstResponder as? NSTextView
|
||||
let action = dictationHistoryKeyAction(
|
||||
keyCode: CGKeyCode(event.keyCode),
|
||||
charactersIgnoringModifiers: event.charactersIgnoringModifiers,
|
||||
hasCommand: event.modifierFlags.contains(.command)
|
||||
hasCommand: event.modifierFlags.contains(.command),
|
||||
hasTextSelection: (editor?.selectedRange().length ?? 0) > 0
|
||||
)
|
||||
// В режиме спасения списка на экране нет, и те же клавиши обязаны
|
||||
// относиться к спасённому тексту, а не к невидимой выделенной записи.
|
||||
@@ -549,15 +539,18 @@ private final class DictationHistoryPanel: NSPanel {
|
||||
// MARK: - Модель списка
|
||||
|
||||
@MainActor
|
||||
final class DictationHistoryModel: ObservableObject {
|
||||
@Published private(set) var entries: [DictationHistoryEntry] = []
|
||||
@Published var query: String = "" {
|
||||
public final class DictationHistoryModel: ObservableObject {
|
||||
@Published public private(set) var entries: [DictationHistoryEntry] = []
|
||||
@Published public var query: String = "" {
|
||||
didSet {
|
||||
guard query != oldValue else { return }
|
||||
clampSelection()
|
||||
// Первый же символ запроса дочитывает всё хранимое: искать по
|
||||
// видимой сотне значит молча врать «ничего не нашлось».
|
||||
if !query.isEmpty { onSearchStarted?() }
|
||||
if !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
!didLoadAll, !isLoadingAll, let root {
|
||||
loadInBackground(from: root, all: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@Published private(set) var selection: Int = 0
|
||||
@@ -565,12 +558,21 @@ final class DictationHistoryModel: ObservableObject {
|
||||
/// Список ещё читается с диска. Отдельный признак, а не пустой список:
|
||||
/// «пока ничего нет» и «ещё не прочитал» - разные вещи, и путать их значит
|
||||
/// врать владельцу, у которого две тысячи надиктовок.
|
||||
@Published var isLoading = false
|
||||
@Published public private(set) var isLoading = false
|
||||
@Published public var notice: String?
|
||||
@Published public var noticeIsError = false
|
||||
@Published var isClearing = false
|
||||
/// Дочитано ли всё хранимое. Показ начинается с сотни свежих; поиск
|
||||
/// дочитывает остальное один раз.
|
||||
var didLoadAll = false
|
||||
/// Кого звать, когда владелец начал искать.
|
||||
var onSearchStarted: (() -> Void)?
|
||||
private(set) var didLoadAll = false
|
||||
private var isLoadingAll = false
|
||||
private var loadGeneration = 0
|
||||
private var root: URL?
|
||||
private let isPreview: Bool
|
||||
|
||||
public init(preview: Bool = false) {
|
||||
isPreview = preview
|
||||
}
|
||||
/// Не `nil` — окно показывает не список, а текст, который не доехал до поля.
|
||||
@Published private(set) var rescue: DictationRescue?
|
||||
/// Почему не сработал повтор вставки. Звука тут мало: владелец должен
|
||||
@@ -587,8 +589,77 @@ final class DictationHistoryModel: ObservableObject {
|
||||
var onInsertRescue: (() -> Void)?
|
||||
var onCopyRescue: (() -> Void)?
|
||||
|
||||
var visible: [DictationHistoryEntry] {
|
||||
filteredDictationHistory(entries, query: query)
|
||||
public var visible: [DictationHistoryEntry] {
|
||||
query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? Array(entries.prefix(DICTATION_HISTORY_VISIBLE_LIMIT))
|
||||
: filteredDictationHistory(entries, query: query)
|
||||
}
|
||||
|
||||
/// Превью проверяется ДО получения корня: даже путь к живому store не нужен.
|
||||
public func reload(from rootProvider: () throws -> URL) {
|
||||
cancelLoading()
|
||||
didLoadAll = false
|
||||
guard !isPreview else {
|
||||
load([])
|
||||
return
|
||||
}
|
||||
do {
|
||||
let root = try rootProvider()
|
||||
self.root = root
|
||||
loadInBackground(from: root,
|
||||
all: !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
} catch {
|
||||
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||
}
|
||||
}
|
||||
|
||||
public func cancelLoading() {
|
||||
loadGeneration += 1
|
||||
isLoading = false
|
||||
isLoadingAll = false
|
||||
root = nil
|
||||
}
|
||||
|
||||
func showError(_ message: String) {
|
||||
notice = message
|
||||
noticeIsError = true
|
||||
}
|
||||
|
||||
private func loadInBackground(from root: URL, all: Bool) {
|
||||
let generation = beginLoading(all: all)
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
let result = Result {
|
||||
// ponytail: весь архив читается лишь при поиске; индекс нужен,
|
||||
// если измеренное время чтения станет мешать поиску.
|
||||
try readDictationHistoryEntries(in: root,
|
||||
limit: all ? nil : DICTATION_HISTORY_VISIBLE_LIMIT)
|
||||
}
|
||||
await self?.completeLoading(result, generation: generation, all: all)
|
||||
}
|
||||
}
|
||||
|
||||
/// Поколение общее для краткого списка, поиска и повторного открытия.
|
||||
func beginLoading(all: Bool) -> Int {
|
||||
loadGeneration += 1
|
||||
isLoading = true
|
||||
isLoadingAll = all
|
||||
notice = nil
|
||||
noticeIsError = false
|
||||
return loadGeneration
|
||||
}
|
||||
|
||||
func completeLoading(_ result: Result<[DictationHistoryEntry], Error>,
|
||||
generation: Int, all: Bool) {
|
||||
guard generation == loadGeneration else { return }
|
||||
isLoading = false
|
||||
isLoadingAll = false
|
||||
switch result {
|
||||
case .success(let found):
|
||||
load(found)
|
||||
didLoadAll = all
|
||||
case .failure:
|
||||
showError(L("history.readFailed", "Не удалось прочитать историю. Попробуй открыть её снова."))
|
||||
}
|
||||
}
|
||||
|
||||
var selectedEntry: DictationHistoryEntry? {
|
||||
@@ -661,7 +732,13 @@ struct DictationHistoryView: View {
|
||||
|
||||
Group {
|
||||
if model.visible.isEmpty {
|
||||
emptyState
|
||||
if let notice = model.notice, model.noticeIsError {
|
||||
Label(notice, systemImage: "exclamationmark.circle")
|
||||
.foregroundStyle(.red)
|
||||
.padding(24)
|
||||
} else {
|
||||
emptyState
|
||||
}
|
||||
} else {
|
||||
list
|
||||
}
|
||||
@@ -669,6 +746,17 @@ struct DictationHistoryView: View {
|
||||
.frame(maxHeight: .infinity)
|
||||
.background(IrizFloatingPlate())
|
||||
|
||||
if model.isLoading, !model.entries.isEmpty {
|
||||
ProgressView(L("history.loading", "Читаю надиктовки…"))
|
||||
.controlSize(.small)
|
||||
}
|
||||
if let notice = model.notice, !model.entries.isEmpty {
|
||||
Label(notice, systemImage: model.noticeIsError ? "exclamationmark.circle" : "checkmark.circle")
|
||||
.foregroundStyle(model.noticeIsError ? Color.red : Color.primary)
|
||||
.font(.system(size: 12))
|
||||
.padding(.horizontal, 12)
|
||||
}
|
||||
|
||||
footer
|
||||
.background(IrizFloatingPlate())
|
||||
}
|
||||
@@ -739,6 +827,11 @@ struct DictationHistoryView: View {
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.accessibilityLabel(notice)
|
||||
}
|
||||
if let notice = model.notice {
|
||||
Label(notice, systemImage: "exclamationmark.circle")
|
||||
.foregroundStyle(.red)
|
||||
.font(.system(size: 12))
|
||||
}
|
||||
|
||||
HStack(spacing: 12) {
|
||||
hint("⏎", L("history.legendInsert", "вставить"))
|
||||
@@ -796,6 +889,7 @@ struct DictationHistoryView: View {
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(L("history.searchClear", "Очистить поиск"))
|
||||
.accessibilityLabel(L("history.searchClear", "Очистить поиск"))
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
@@ -835,10 +929,16 @@ struct DictationHistoryView: View {
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 2) {
|
||||
ForEach(Array(model.visible.enumerated()), id: \.element.id) { index, entry in
|
||||
row(entry, isSelected: index == model.selection)
|
||||
.id(entry.id)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { model.select(entry) }
|
||||
Button { model.select(entry) } label: {
|
||||
row(entry, isSelected: index == model.selection)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityAddTraits(index == model.selection ? .isSelected : [])
|
||||
.accessibilityAction(named: Text(L("history.insert", "Вставить"))) { model.onInsert?(entry) }
|
||||
.accessibilityAction(named: Text(L("history.copyButton", "Копировать"))) { model.onCopy?(entry) }
|
||||
.id(entry.id)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 6)
|
||||
@@ -888,6 +988,7 @@ struct DictationHistoryView: View {
|
||||
Button(L("history.copyButton", "Копировать")) { model.onCopy?(entry) }
|
||||
Divider()
|
||||
Button(L("history.trashOne", "Переместить в Корзину"), role: .destructive) { model.onDelete?(entry) }
|
||||
.disabled(model.isClearing)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -900,6 +1001,10 @@ struct DictationHistoryView: View {
|
||||
/// место под строкой.
|
||||
private var footer: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
if model.isClearing {
|
||||
ProgressView(L("history.clearing", "Подготовка и очистка истории…"))
|
||||
.controlSize(.small)
|
||||
}
|
||||
HStack(spacing: 12) {
|
||||
hint("⏎", L("history.legendInsert", "вставить"))
|
||||
hint("⌘C", L("history.legendCopy", "копировать"))
|
||||
@@ -922,6 +1027,11 @@ struct DictationHistoryView: View {
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
.accessibilityLabel(L("history.clipboardNoteVoice", "Скопированное держится в буфере две минуты, потом буфер чистится"))
|
||||
if model.query.isEmpty, model.entries.count >= DICTATION_HISTORY_VISIBLE_LIMIT {
|
||||
Text(L("history.loadingBody", "Показываю последние сто. Остальные найдёт поиск."))
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(IRIZ_SUBTLE)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
@@ -936,11 +1046,11 @@ struct DictationHistoryView: View {
|
||||
if #available(macOS 26.0, *) {
|
||||
Button(action: { model.onClearAll?() }) { label }
|
||||
.buttonStyle(.glass)
|
||||
.disabled(model.entries.isEmpty)
|
||||
.disabled(model.entries.isEmpty || model.isClearing)
|
||||
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
||||
} else {
|
||||
Button(action: { model.onClearAll?() }) { label }
|
||||
.disabled(model.entries.isEmpty)
|
||||
.disabled(model.entries.isEmpty || model.isClearing)
|
||||
.help(L("history.clearAllHint", "Переместить все надиктовки в Корзину"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,20 @@ public enum MeetingPipelineFailure: String, Error, Equatable {
|
||||
case storeFailed = "не удалось сохранить встречу на диск"
|
||||
}
|
||||
|
||||
/// Whisper может вернуть текст без времён слов. Успешная диаризация сама по
|
||||
/// себе ещё не связывает слова с людьми: весь исходный текст должен сохраниться.
|
||||
func meetingSpeakerTurns(transcript: AudioFileTranscript, spans: [SpeakerSpan],
|
||||
names: SpeakerNames = SpeakerNames())
|
||||
-> (turns: [SpeakerTurn], speakersResolved: Bool) {
|
||||
let turns = speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans), names: names)
|
||||
guard !spans.isEmpty,
|
||||
turns.contains(where: { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else {
|
||||
return ([SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||
start: 0, end: transcript.audioSeconds)], false)
|
||||
}
|
||||
return (turns, true)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public final class MeetingPipeline {
|
||||
private let transcriber: AudioFileTranscriber
|
||||
@@ -52,20 +66,33 @@ public final class MeetingPipeline {
|
||||
public func run(audio url: URL, title: String, names: SpeakerNames = SpeakerNames(),
|
||||
at date: Date = Date(),
|
||||
progress: @escaping (String) -> Void = { _ in }) async throws -> MeetingResult {
|
||||
try Task.checkCancellation()
|
||||
progress("Читаю запись")
|
||||
guard let decoded = try? await AudioFileDecoder.decode(url) else {
|
||||
let decoded: DecodedAudio
|
||||
do {
|
||||
decoded = try await AudioFileDecoder.decode(url)
|
||||
} catch is CancellationError {
|
||||
throw CancellationError()
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
throw MeetingPipelineFailure.audioUnreadable
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
|
||||
progress("Расшифровываю")
|
||||
_ = try? await transcriber.prepare()
|
||||
let transcript: AudioFileTranscript
|
||||
do {
|
||||
_ = try await transcriber.prepare()
|
||||
try Task.checkCancellation()
|
||||
transcript = try await transcriber.transcribe(decoded, language: .russian)
|
||||
} catch is CancellationError {
|
||||
throw CancellationError()
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
log("meeting: расшифровка отказала (\(error))")
|
||||
throw MeetingPipelineFailure.transcriptionFailed
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
guard !transcript.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw MeetingPipelineFailure.nothingRecognized
|
||||
}
|
||||
@@ -73,22 +100,28 @@ public final class MeetingPipeline {
|
||||
progress("Разбираю говорящих")
|
||||
// Отказ диаризатора конвейер не роняет: протокол без разделения хуже
|
||||
// полного, но лучше отсутствующего.
|
||||
let spans = (try? await diarizer.spans(of: url)) ?? []
|
||||
let turns = spans.isEmpty
|
||||
? [SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||
start: 0, end: transcript.audioSeconds)]
|
||||
: speakerTurnsNamed(speakerTurns(tokens: transcript.tokenTimings, spans: spans),
|
||||
names: names)
|
||||
let spans: [SpeakerSpan]
|
||||
do {
|
||||
spans = try await diarizer.spans(of: url)
|
||||
} catch is CancellationError {
|
||||
throw CancellationError()
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
spans = []
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans, names: names)
|
||||
|
||||
progress("Сохраняю")
|
||||
let document = MeetingProtocolDocument(title: title, recordedAt: date,
|
||||
audioSeconds: transcript.audioSeconds,
|
||||
turns: turns)
|
||||
turns: resolved.turns)
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
let artifacts = try MeetingStore.save(audio: url, protocolText: document.text(),
|
||||
at: date, title: title, in: storeRoot)
|
||||
return MeetingResult(artifacts: artifacts, turns: turns,
|
||||
speakersResolved: !spans.isEmpty,
|
||||
return MeetingResult(artifacts: artifacts, turns: resolved.turns,
|
||||
speakersResolved: resolved.speakersResolved,
|
||||
audioSeconds: transcript.audioSeconds)
|
||||
} catch {
|
||||
log("meeting: запись на диск отказала (\(error))")
|
||||
|
||||
@@ -88,5 +88,5 @@ public func meetingRecordingScratchURL(at date: Date = Date()) throws -> URL {
|
||||
.appendingPathComponent("_recording", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
return root.appendingPathComponent("meeting-\(formatter.string(from: date)).wav")
|
||||
return root.appendingPathComponent("meeting-\(formatter.string(from: date))-\(UUID().uuidString.lowercased()).wav")
|
||||
}
|
||||
|
||||
@@ -45,21 +45,31 @@ public enum MeetingStore {
|
||||
@discardableResult
|
||||
public static func save(audio: URL, protocolText: String, at date: Date = Date(),
|
||||
title: String, in root: URL? = nil) throws -> MeetingArtifacts {
|
||||
let directory = try meetingDirectory(at: date, title: title, in: root)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
let audioCopy = directory.appendingPathComponent("audio." + audio.pathExtension)
|
||||
if FileManager.default.fileExists(atPath: audioCopy.path) {
|
||||
try FileManager.default.removeItem(at: audioCopy)
|
||||
}
|
||||
try FileManager.default.copyItem(at: audio, to: audioCopy)
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
|
||||
let manager = FileManager.default
|
||||
let base = try meetingDirectory(at: date, title: title, in: root)
|
||||
let identifier = UUID().uuidString.lowercased()
|
||||
let directory = base.deletingLastPathComponent()
|
||||
.appendingPathComponent(base.lastPathComponent + "-" + identifier, isDirectory: true)
|
||||
let staging = base.deletingLastPathComponent()
|
||||
.appendingPathComponent(".saving-" + identifier, isDirectory: true)
|
||||
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
// Новый архив появляется только целиком. Старые записи, в том числе с
|
||||
// тем же названием и временем, никогда не служат временным каталогом.
|
||||
defer { try? manager.removeItem(at: staging) }
|
||||
let audioName = "audio." + audio.pathExtension
|
||||
let audioCopy = staging.appendingPathComponent(audioName)
|
||||
try manager.copyItem(at: audio, to: audioCopy)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: audioCopy.path)
|
||||
|
||||
let transcript = directory.appendingPathComponent("protocol.md")
|
||||
let transcript = staging.appendingPathComponent("protocol.md")
|
||||
try protocolText.write(to: transcript, atomically: true, encoding: .utf8)
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: transcript.path)
|
||||
try manager.moveItem(at: staging, to: directory)
|
||||
|
||||
return MeetingArtifacts(directory: directory, audio: audioCopy, transcript: transcript)
|
||||
return MeetingArtifacts(directory: directory,
|
||||
audio: directory.appendingPathComponent(audioName),
|
||||
transcript: directory.appendingPathComponent("protocol.md"))
|
||||
}
|
||||
|
||||
/// Имя папки из названия встречи: латиница и цифры, остальное в дефис.
|
||||
|
||||
@@ -6,19 +6,21 @@
|
||||
// приложение, а модель приезжает после установки - с показанным ходом и
|
||||
// понятной ценой.
|
||||
//
|
||||
// Правило «сеть в диктовке запрещена» при этом остаётся. `enforceOffline`
|
||||
// снимается ТОЛЬКО на время явной установки, которую начал человек, и
|
||||
// возвращается назад в `defer` - в том числе на ошибке и на отмене. Пока идёт
|
||||
// диктовка, установка не начинается вовсе: снятый рубильник при работающем
|
||||
// конвейере означал бы, что распознавание может молча полезть в сеть.
|
||||
import FluidAudio
|
||||
// Явная установка получает закреплённые файлы через URLSession. Рубильник
|
||||
// офлайна распознавателя не меняется даже на время скачивания. Новая копия
|
||||
// проверяется отдельно; существующий кэш сохраняется при любом отказе.
|
||||
import Foundation
|
||||
import IrizCore
|
||||
|
||||
public let speechModelDidInstallNotification = Notification.Name("iriz.speechModelDidInstall")
|
||||
// Сумма 21 файла закреплённого commit: официальный HF tree API, 12.09.2026.
|
||||
public let speechModelDownloadBytes: Int64 = 483_105_645
|
||||
|
||||
/// Что происходит с установкой прямо сейчас.
|
||||
public enum SpeechModelInstallPhase: Equatable, Sendable {
|
||||
/// Идёт скачивание, 0…1.
|
||||
case downloading(Double)
|
||||
/// Файлы получены, CoreML собирает модель под это железо.
|
||||
/// Файлы получены, проверяется их целостность перед использованием.
|
||||
case compiling
|
||||
case finished
|
||||
case failed(String)
|
||||
@@ -29,7 +31,7 @@ public enum SpeechModelInstallRefusal: String, Equatable, Sendable {
|
||||
case alreadyInstalled
|
||||
/// Установка уже идёт.
|
||||
case alreadyRunning
|
||||
/// Идёт диктовка: рубильник сети при работающем конвейере не снимаем.
|
||||
/// Идёт диктовка: установку не начинаем посреди активного сценария.
|
||||
case dictationBusy
|
||||
}
|
||||
|
||||
@@ -47,28 +49,45 @@ public func speechModelInstallRefusal(installed: Bool,
|
||||
/// Ход установки, как его показывает окно: доля и подпись.
|
||||
public func speechModelInstallTitle(_ phase: SpeechModelInstallPhase) -> String {
|
||||
switch phase {
|
||||
case .downloading: return "Качаю модель распознавания"
|
||||
case .compiling: return "Готовлю модель под твой Мак"
|
||||
case .finished: return "Модель на месте"
|
||||
case .failed: return "Скачать не вышло"
|
||||
case .downloading: return L("speechModel.downloading", "Качаю модель распознавания")
|
||||
case .compiling: return L("speechModel.verifying", "Проверяю скачанную модель")
|
||||
case .finished: return L("speechModel.ready", "Модель на месте")
|
||||
case .failed: return L("speechModel.failed", "Скачать не вышло")
|
||||
}
|
||||
}
|
||||
|
||||
public func speechModelInstallFraction(_ phase: SpeechModelInstallPhase) -> Double {
|
||||
switch phase {
|
||||
case .downloading(let value): return min(1, max(0, value))
|
||||
// Сборка идёт без хода: показываем почти полную полосу, а не откат назад.
|
||||
case .compiling: return 0.97
|
||||
// Все байты получены; проверка не откатывает полосу скачивания назад.
|
||||
case .compiling: return 1
|
||||
case .finished: return 1
|
||||
case .failed: return 0
|
||||
}
|
||||
}
|
||||
|
||||
public func speechModelInstallFailureMessage(for error: Error) -> String {
|
||||
if error is CancellationError || (error as? URLError)?.code == .cancelled {
|
||||
return L("speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
|
||||
}
|
||||
switch (error as? URLError)?.code {
|
||||
case .notConnectedToInternet:
|
||||
return L("speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание.")
|
||||
case .networkConnectionLost:
|
||||
return L("speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание.")
|
||||
case .timedOut:
|
||||
return L("speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже.")
|
||||
default:
|
||||
return error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public final class SpeechModelInstaller {
|
||||
public static let shared = SpeechModelInstaller()
|
||||
|
||||
private(set) public var isRunning = false
|
||||
private var downloadingFile: UUID?
|
||||
|
||||
private init() {}
|
||||
|
||||
@@ -78,33 +97,119 @@ public final class SpeechModelInstaller {
|
||||
public func install(dictating: Bool,
|
||||
progress: @escaping @MainActor (SpeechModelInstallPhase) -> Void)
|
||||
async -> SpeechModelInstallRefusal? {
|
||||
let installed = speechModelCacheExists(for: .multilingualV3)
|
||||
if let refusal = speechModelInstallRefusal(installed: installed,
|
||||
if let refusal = speechModelInstallRefusal(installed: false,
|
||||
running: isRunning,
|
||||
dictating: dictating) {
|
||||
if refusal == .alreadyInstalled { progress(.finished) }
|
||||
return refusal
|
||||
}
|
||||
isRunning = true
|
||||
DownloadUtils.enforceOffline = false
|
||||
defer {
|
||||
DownloadUtils.enforceOffline = true
|
||||
isRunning = false
|
||||
downloadingFile = nil
|
||||
}
|
||||
let directory = speechModelCacheDirectory(for: .multilingualV3)
|
||||
do {
|
||||
_ = try await AsrModels.download(version: .v3) { snapshot in
|
||||
Task { @MainActor in
|
||||
switch snapshot.phase {
|
||||
case .compiling: progress(.compiling)
|
||||
default: progress(.downloading(snapshot.fractionCompleted))
|
||||
let verified = await Task.detached(priority: .userInitiated) {
|
||||
(try? ModelIntegrity.verifyParakeetV3Model(at: directory)) != nil
|
||||
}.value
|
||||
try Task.checkCancellation()
|
||||
if verified {
|
||||
progress(.finished)
|
||||
return .alreadyInstalled
|
||||
}
|
||||
|
||||
let manager = FileManager.default
|
||||
let staging = directory.deletingLastPathComponent()
|
||||
.appendingPathComponent(".iriz-model-download-" + UUID().uuidString, isDirectory: true)
|
||||
try manager.createDirectory(at: staging, withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
defer { try? manager.removeItem(at: staging) }
|
||||
let files = ModelIntegrity.parakeetV3DownloadFiles
|
||||
var receivedBytes: Int64 = 0
|
||||
for file in files {
|
||||
try Task.checkCancellation()
|
||||
let completedBytes = receivedBytes
|
||||
let token = UUID()
|
||||
downloadingFile = token
|
||||
progress(.downloading(Double(completedBytes) / Double(speechModelDownloadBytes)))
|
||||
let delegate = SpeechModelDownloadProgress { [weak self] currentBytes in
|
||||
Task { @MainActor in
|
||||
guard self?.downloadingFile == token else { return }
|
||||
progress(.downloading(min(1, Double(completedBytes + currentBytes) / Double(speechModelDownloadBytes))))
|
||||
}
|
||||
}
|
||||
let (temporary, response) = try await URLSession.shared.download(
|
||||
from: speechModelDownloadURL(for: file), delegate: delegate)
|
||||
downloadingFile = nil
|
||||
defer { try? manager.removeItem(at: temporary) }
|
||||
try Task.checkCancellation()
|
||||
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
|
||||
throw URLError(.badServerResponse)
|
||||
}
|
||||
let target = staging.appendingPathComponent(file.relativePath)
|
||||
try manager.createDirectory(at: target.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700])
|
||||
try manager.moveItem(at: temporary, to: target)
|
||||
try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path)
|
||||
receivedBytes += Int64(try target.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0)
|
||||
}
|
||||
progress(.compiling)
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
try ModelIntegrity.verifyParakeetV3Model(at: staging)
|
||||
}.value
|
||||
try Task.checkCancellation()
|
||||
try publishSpeechModelCache(from: staging, to: directory)
|
||||
progress(.finished)
|
||||
return nil
|
||||
} catch {
|
||||
progress(.failed(error.localizedDescription))
|
||||
progress(.failed(speechModelInstallFailureMessage(for: error)))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class SpeechModelDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
|
||||
private let received: @Sendable (Int64) -> Void
|
||||
|
||||
init(received: @escaping @Sendable (Int64) -> Void) { self.received = received }
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
|
||||
totalBytesExpectedToWrite: Int64) {
|
||||
received(totalBytesWritten)
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||
didFinishDownloadingTo location: URL) {}
|
||||
}
|
||||
|
||||
/// Источник зафиксирован тем же commit, что и SHA-256 в загрузчике; ни main,
|
||||
/// ни переменные окружения с подменённым реестром сюда не попадают.
|
||||
func speechModelDownloadURL(for file: ModelFileDigest) throws -> URL {
|
||||
guard ModelIntegrity.parakeetV3DownloadFiles.contains(file),
|
||||
let url = URL(string: "https://huggingface.co/\(ModelIntegrity.parakeetV3Repository)/resolve/\(ModelIntegrity.parakeetV3RepositoryCommit)/\(file.relativePath)"),
|
||||
url.scheme == "https", url.host == "huggingface.co" else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
/// Замена только после проверки новой копии. Предыдущая остаётся рядом;
|
||||
/// если публикация не удалась, возвращаем её на прежнее место.
|
||||
func publishSpeechModelCache(from staging: URL, to directory: URL) throws {
|
||||
let manager = FileManager.default
|
||||
var backup: URL?
|
||||
if manager.fileExists(atPath: directory.path) {
|
||||
let saved = directory.deletingLastPathComponent()
|
||||
.appendingPathComponent(".iriz-model-backup-" + UUID().uuidString, isDirectory: true)
|
||||
try manager.moveItem(at: directory, to: saved)
|
||||
backup = saved
|
||||
}
|
||||
do {
|
||||
try manager.moveItem(at: staging, to: directory)
|
||||
} catch {
|
||||
if let backup { try manager.moveItem(at: backup, to: directory) }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,13 +163,20 @@ func speechModelCacheDirectory(for profile: SpeechModelProfile) -> URL {
|
||||
}
|
||||
|
||||
public func speechModelCacheExists(for profile: SpeechModelProfile) -> Bool {
|
||||
speechModelCacheIsComplete(for: profile, at: speechModelCacheDirectory(for: profile))
|
||||
}
|
||||
|
||||
/// Быстрый probe для интерфейса: состав файлов, не SHA-256 сотен мегабайт.
|
||||
/// Полная проверка по закреплённому манифесту остаётся перед загрузкой модели.
|
||||
func speechModelCacheIsComplete(for profile: SpeechModelProfile, at directory: URL) -> Bool {
|
||||
switch profile {
|
||||
case .multilingualV3:
|
||||
return FileManager.default.fileExists(atPath: speechModelCacheDirectory(for: profile).path)
|
||||
return ModelIntegrity.parakeetV3CacheIsComplete(at: directory)
|
||||
case .whisperLargeV3, .whisperTurbo:
|
||||
// У whisper модель - ОДИН файл, и каталог без него бесполезен: проверяем файл.
|
||||
guard let file = profile.whisperModelFile else { return false }
|
||||
return FileManager.default.fileExists(atPath: whisperModelURL(file).path)
|
||||
let values = try? directory.appendingPathComponent(file)
|
||||
.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
return values?.isRegularFile == true && (values?.fileSize ?? 0) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +248,25 @@ public enum ModelIntegrity {
|
||||
// END GENERATED PARAKEET_V3_MODEL_MANIFEST
|
||||
]
|
||||
|
||||
static var parakeetV3DownloadFiles: [ModelFileDigest] { parakeetV3Files }
|
||||
|
||||
static func parakeetV3CacheIsComplete(at directory: URL) -> Bool {
|
||||
do {
|
||||
let directories = Set(parakeetV3Files.flatMap { parentDirectories(of: $0.relativePath) })
|
||||
for name in directories {
|
||||
try requireDirectory(directory.appendingPathComponent(name), relativePath: name)
|
||||
}
|
||||
for file in parakeetV3Files {
|
||||
let url = directory.appendingPathComponent(file.relativePath)
|
||||
try requireRegularFile(url, relativePath: file.relativePath)
|
||||
guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) > 0 else { return false }
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public static func verifyParakeetV3Model(at directory: URL) throws {
|
||||
try verifyFiles(root: directory,
|
||||
expectedFiles: parakeetV3Files,
|
||||
|
||||
Reference in New Issue
Block a user