Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 36 additions & 16 deletions Sources/verbemo/Sessions/PostProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,12 @@ enum PostProcessor {
/// say which steps it is exercising instead of inheriting whatever the
/// machine owner has turned on this week.
@discardableResult
static func finish(_ dir: URL, policy: Policy = .configured, retryFailed: Bool = false) async -> Work {
static func finish(_ dir: URL, policy: Policy = .configured, retryFailed: Bool = false,
stopHook: StopHook.Command? = nil) async -> Work {
do {
let root = try validatedSessionRoot(for: dir)
return try await ProcessingOperations.shared.run(session: root, kind: .postProcessing) {
try await finishWork(dir, policy: policy, retryFailed: retryFailed)
try await finishWork(dir, policy: policy, retryFailed: retryFailed, stopHook: stopHook)
}
} catch is CancellationError {
return Work()
Expand Down Expand Up @@ -224,11 +225,12 @@ enum PostProcessor {
}

/// The button and command share the explicit retry and its outcome; the sweep uses finish.
static func finishManually(_ dir: URL, policy: Policy = .configured) async -> Completion {
static func finishManually(_ dir: URL, policy: Policy = .configured,
stopHook: StopHook.Command? = nil) async -> Completion {
do {
let root = try validatedSessionRoot(for: dir)
return try await ProcessingOperations.shared.run(session: root, kind: .postProcessing) {
let result = try await finishManuallyWork(dir, policy: policy)
let result = try await finishManuallyWork(dir, policy: policy, stopHook: stopHook)
if !result.succeeded { ProcessingOperations.shared.reportFailure(result.described) }
return result
}
Expand All @@ -244,8 +246,9 @@ enum PostProcessor {
}
}

private static func finishManuallyWork(_ dir: URL, policy: Policy) async throws -> Completion {
let work = try await finishWork(dir, policy: policy, retryFailed: true)
private static func finishManuallyWork(_ dir: URL, policy: Policy,
stopHook: StopHook.Command?) async throws -> Completion {
let work = try await finishWork(dir, policy: policy, retryFailed: true, stopHook: stopHook)
if let refusal = manualSummaryRefusal(dir) { return refusal }
guard !work.isEmpty else { return .nothingToDo }
let meta = SessionState.read(dir) ?? [:]
Expand All @@ -270,7 +273,8 @@ enum PostProcessor {
return .deferred
}

private static func finishWork(_ dir: URL, policy: Policy, retryFailed: Bool) async throws -> Work {
private static func finishWork(_ dir: URL, policy: Policy, retryFailed: Bool,
stopHook: StopHook.Command?) async throws -> Work {
ProcessingOperations.shared.stage(.postProcessing, artifactDirectory: dir)
try Task.checkCancellation()
if let reason = Config.unreadableReason { throw Refusal.configUnreadable(reason) }
Expand All @@ -280,10 +284,29 @@ enum PostProcessor {
if let reason = Config.unreadableReason { throw Refusal.configUnreadable(reason) }
guard !TranscriptVersions.isRequested(root), !TranscriptVersions.isRequested(dir),
!FileManager.default.fileExists(atPath: root.appendingPathComponent(".recording.json").path),
DiarizationState.persisted(in: dir).isFinal else {
!FileManager.default.fileExists(atPath: dir.appendingPathComponent(TranscriptVersions.journalDirectory).path)
else {
throw SummaryRegenerationError.unavailable("A finished transcript is required before post-processing.")
}
let diarization = DiarizationState.persisted(in: dir)
guard diarization.isFinal else {
// A disabled, deferred or failed speaker pass cannot advance to naming
// and summary today. It can still deliver its current transcript.
if let stopHook, case .valid(let state) = diarization, !state.blocksStopHook {
await StopHook.fireWhileClaimedIfOwed(dir, command: stopHook)
}
throw SummaryRegenerationError.unavailable("A finished transcript is required before post-processing.")
}

let work = try await finishClaimed(dir, policy: policy, retryFailed: retryFailed)
if let stopHook {
await StopHook.fireWhileClaimedIfOwed(dir, command: stopHook)
try Task.checkCancellation()
}
return work
}

private static func finishClaimed(_ dir: URL, policy: Policy, retryFailed: Bool) async throws -> Work {
let work = outstanding(dir, policy: policy, retryFailed: retryFailed)
guard !work.isEmpty else { return work }

Expand Down Expand Up @@ -358,14 +381,11 @@ enum PostProcessor {
var finished = 0
for dir in SessionInventory.sessionFolders(in: root) {
guard !Task.isCancelled else { break }
let work = try? await ProcessingOperations.shared.run(session: dir, kind: .postProcessing) {
let work = await finish(dir)
try Task.checkCancellation()
await StopHook.fireIfOwed(dir)
try Task.checkCancellation()
return work
}
if let work, !work.isEmpty { finished += 1 }
// Leave a first automatic speaker attempt to the transcription queue.
// Recheck under the claim in finishWork before the hook can run.
if DiarizationState.read(dir)?.blocksStopHook == true { continue }
let work = await finish(dir, stopHook: { Config.onStop() })
if !work.isEmpty { finished += 1 }
}
return finished
}
Expand Down
5 changes: 3 additions & 2 deletions Sources/verbemo/Sessions/SessionCommands.swift
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,9 @@ struct ProcessSession: ParsableCommand {
}

case .finish:
let result = try runBlocking { await PostProcessor.finishManually(dir) }
_ = try runBlocking { await StopHook.fireIfOwed(dir) }
let result = try runBlocking {
await PostProcessor.finishManually(dir, stopHook: { Config.onStop() })
}
print("\n" + result.description)
if !result.succeeded { throw ExitCode(1) }

Expand Down
13 changes: 13 additions & 0 deletions Sources/verbemo/Transcription/DiarizationState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ struct DiarizationState: Codable, Equatable {
var confirmedSpeakers = 0
var hasUnknown = false

var isPendingFirstAttempt: Bool { status == .pending && attempts == 0 }

var isFirstAttemptUnfinished: Bool {
isPendingFirstAttempt || (status == .running && attempts == 1)
}

var blocksStopHook: Bool {
// The claim covers live attempts. The saved state protects a first
// attempt that the automatic queue can start or resume.
isFirstAttemptUnfinished && Config.transcriptionEnabled()
&& (request.explicit || Config.localDiarizationEnabled())
}

var hasFailedAttempt: Bool {
status == .failed || (status == .pending && attempts > 0 && reason?.isEmpty == false)
}
Expand Down
38 changes: 20 additions & 18 deletions Sources/verbemo/Transcription/StopHook.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,11 @@ import Foundation
///
/// The contract, which is the whole of this type:
///
/// - It fires **once per transcript**, when the session's post-processing has
/// had its pass: names and summary written, or turned off, or given up on,
/// or deferred for want of a model. A summary that arrives on a later sweep
/// does not fire it a second time — a Mac with no model to reach would
/// otherwise never run the hook at all.
/// - It never fires while any verbemo — this one or another — is still naming
/// or summarizing the session. Whichever finishes that work fires it: the
/// transcription queue, the sweep at launch and on the network's return,
/// `verbemo process`.
/// - It fires **once per transcript**, after immediate diarization and the
/// current naming and summary pass. Disabled, failed or deferred work can
/// leave partial results. A later retry does not fire the hook again.
/// - The transcription queue, a sweep, or `verbemo process` holds the session
/// claim through the end of post-processing and the hook itself.
/// - With transcription off it fires once the recording has been archived.
/// - A session retired without a transcript does not fire it.
/// - Transcribing a session again owes the hook again.
Expand All @@ -30,6 +26,8 @@ import Foundation
/// what keeps the first sweep after an update from running the hook over
/// every recording on the disk.
enum StopHook {
typealias Command = @Sendable () -> String?

static let key = "on_stop_hook"
static let owed = "owed"
static let fired = "fired"
Expand All @@ -50,23 +48,27 @@ enum StopHook {
@discardableResult
static func fireIfOwed(_ dir: URL, command: @autoclosure @Sendable () -> String? = Config.onStop()) async -> Bool {
guard !Task.isCancelled, SessionState.value(dir, key) as? String == owed else { return false }
if let reason = Config.unreadableReason {
appendSessionLog(
"on_stop hook waits — config.json can't be read (\(reason))", to: dir)
return false
}
// Taken, not just looked at: two processes finishing the same folder
// at the same moment must not both decide the hook is theirs. A
// session somebody else holds is theirs to fire when they let go.
do {
try SessionClaim.acquire(dir, stage: .finish)
} catch {
return false
}
defer { SessionClaim.release(dir) }
return await fireWhileClaimedIfOwed(dir, command: command)
}

/// The caller holds the session claim from post-processing through hook exit.
@discardableResult
static func fireWhileClaimedIfOwed(_ dir: URL, command: Command) async -> Bool {
guard !Task.isCancelled, SessionState.value(dir, key) as? String == owed else { return false }
let configuredCommand = command()
if let reason = Config.unreadableReason {
appendSessionLog(
"on_stop hook waits — config.json can't be read (\(reason))", to: dir)
return false
}
SessionState.update(dir, with: [key: fired])
guard let command = command() else { return false }
guard let command = configuredCommand else { return false }
await run(command, in: dir)
return true
}
Expand Down
107 changes: 62 additions & 45 deletions Sources/verbemo/Transcription/TranscriptionCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -505,21 +505,14 @@ actor TranscriptionCoordinator {
!TranscriptVersions.isRequested(dir),
let state = DiarizationState.read(dir), state.isOutstanding {
guard Config.localDiarizationEnabled() || state.request.explicit else {
throw AlreadyTranscribed()
}
do {
if try await runDiarization(dir, explicit: state.request.explicit) {
await PostProcessor.finish(dir)
try Task.checkCancellation()
notifyUser(
title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"),
body: dir.lastPathComponent, opening: dir)
}
} catch is CancellationError { throw CancellationError() }
catch {
operations.reportFailure(String(describing: error))
log(dir, "diarization remains unfinished: \(error)")
await PostProcessor.finish(dir, stopHook: onStop)
try Task.checkCancellation()
return
}
let updated = try await attemptDiarization(dir, state: state)
await PostProcessor.finish(dir, stopHook: onStop)
try Task.checkCancellation()
if updated { notifySpeakersUpdated(dir) }
return
}
var fallbackUsed = false
Expand Down Expand Up @@ -567,40 +560,46 @@ actor TranscriptionCoordinator {
engine: engine.name, provenance: engine.model)),
.fallbackUsed: .flag(fallbackUsed),
])
if DiarizationState.read(dir)?.isFinal == false {
var updatedSpeakers = false
let state = DiarizationState.read(dir)
if let state, !state.isFinal {
notifyUser(
title: localised("verbemo — transcript ready; speakers pending",
"verbemo — расшифровка готова; говорящие определяются"),
body: dir.lastPathComponent, opening: dir)
await StopHook.fireIfOwed(dir, command: onStop())
try Task.checkCancellation()
if let state = DiarizationState.read(dir),
state.status == .pending && state.attempts == 0 {
do {
if try await runDiarization(dir, explicit: state.request.explicit) {
await PostProcessor.finish(dir)
try Task.checkCancellation()
notifyUser(
title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"),
body: dir.lastPathComponent, opening: dir)
}
} catch is CancellationError { throw CancellationError() }
catch {
operations.reportFailure(String(describing: error))
log(dir, "diarization remains unfinished: \(error)")
}
if state.isPendingFirstAttempt {
updatedSpeakers = try await attemptDiarization(dir, state: state)
}
} else {
await PostProcessor.finish(dir)
try Task.checkCancellation()
}

await PostProcessor.finish(dir, stopHook: onStop)
try Task.checkCancellation()
if updatedSpeakers {
notifySpeakersUpdated(dir)
} else if state?.isFinal != false {
notifyUser(
title: localised("verbemo — transcript ready", "verbemo — расшифровка готова"),
body: dir.lastPathComponent, opening: dir)
await StopHook.fireIfOwed(dir, command: onStop())
try Task.checkCancellation()
}
}

private func attemptDiarization(_ dir: URL, state: DiarizationState) async throws -> Bool {
do {
return try await runDiarization(dir, explicit: state.request.explicit)
} catch is CancellationError {
throw CancellationError()
} catch {
operations.reportFailure(String(describing: error))
log(dir, "diarization remains unfinished: \(error)")
return false
}
}

private func notifySpeakersUpdated(_ dir: URL) {
notifyUser(title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"),
body: dir.lastPathComponent, opening: dir)
}

private func releaseEngine() async {
await engines.release()
}
Expand Down Expand Up @@ -664,7 +663,7 @@ actor TranscriptionCoordinator {
do {
let updated = try await runDiarization(dir, explicit: true, expectedRequest: request)
if updated {
await PostProcessor.finish(dir)
await PostProcessor.finish(dir, stopHook: onStop)
try Task.checkCancellation()
}
await releaseEngine()
Expand Down Expand Up @@ -739,10 +738,9 @@ actor TranscriptionCoordinator {
}
let updated = try await runDiarization(dir, explicit: true)
if updated {
await PostProcessor.finish(dir)
await PostProcessor.finish(dir, stopHook: onStop)
try Task.checkCancellation()
notifyUser(title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"),
body: dir.lastPathComponent, opening: dir)
notifySpeakersUpdated(dir)
}
}

Expand Down Expand Up @@ -876,9 +874,7 @@ actor TranscriptionCoordinator {
SessionClaim.release(dir)
throw error
}
await PostProcessor.finish(dir)
try Task.checkCancellation()
await StopHook.fireIfOwed(dir, command: onStop())
await PostProcessor.finish(dir, stopHook: onStop)
try Task.checkCancellation()
}

Expand All @@ -893,7 +889,7 @@ actor TranscriptionCoordinator {
throw DiarizationUnavailable(reason: "a replacement transcript is already queued")
}
TranscriptionScratch.remove(in: dir)
guard var state = DiarizationState.read(dir),
guard let state = DiarizationState.read(dir),
let provisional = PostProcessor.readTranscript(dir) else { return false }
if let expectedRequest, state.request != expectedRequest {
throw DiarizationUnavailable(reason: "the waiting speaker request changed")
Expand All @@ -902,6 +898,27 @@ actor TranscriptionCoordinator {
return false
}
if !explicit && !Config.localDiarizationEnabled() { return false }
do {
return try await completeDiarization(dir, explicit: explicit, state: state, provisional: provisional)
} catch is CancellationError {
throw CancellationError()
} catch {
try Task.checkCancellation()
// Validation or staging can fail before the inference path records an
// outcome. Persist it while still holding the claim so a failed first
// pass cannot leave the hook waiting for work that has already ended.
if var current = DiarizationState.read(dir), current.isFirstAttemptUnfinished {
current.status = .partial
current.reason = "speaker pass failed: \(error)"
try current.write(to: dir)
}
throw error
}
}

private func completeDiarization(_ dir: URL, explicit: Bool, state initialState: DiarizationState,
provisional: Transcript) async throws -> Bool {
var state = initialState
let currentMeta = try SessionMeta.read(from: dir)
let range = try TranscriptVersions.appliedRange(in: dir)
guard let track = currentMeta.tracks.first(where: {
Expand Down
Loading
Loading