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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ transcription keeps source audio for retry. Local diarization also retains the
lossless source and sidecars while its stage remains unfinished.
The recordings window shows completed, pending and failed work.

In the meeting player, open **Transcription range**, set the start and end,
then choose **Apply and transcribe**. The new transcript uses the selected audio
and keeps timestamps on the original recording. Choose **Full recording** to
restore the whole range. When summaries are enabled, you can add an instruction
such as “Skip the conversation about the weekend.” You can also change the
instruction with **Create a new summary** using the existing transcript.

## Local macOS development

Use Xcode command line tools, Swift, Python 3, Node.js and CMake. Build from this
Expand Down
138 changes: 138 additions & 0 deletions Sources/verbemo/Audio/RecordingRangeAudio.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import AVFoundation
import Foundation

/// A bounded view of the original tracks for one recognition job. File offsets
/// in the returned metadata are relative to the selected fragment's start.
struct RecordingRangeAudio {
static let folderPrefix = ".transcription-range-"
let directory: URL
let meta: SessionMeta

static func prepare(_ range: RecordingRange, in session: URL, meta: SessionMeta) throws -> Self {
let fm = FileManager.default
let root = session.standardizedFileURL.resolvingSymlinksInPath()
var identities = ["pcm-v1", String(range.startMs), String(range.endMs)]
struct Source: Hashable {
let file: String
let offset: Int
}
var sources: [Source] = []
var tracks: [SessionMeta.Track] = []
for track in meta.tracks {
let url = root.appendingPathComponent(track.file)
guard track.file == url.lastPathComponent, !track.file.contains("\\"),
url.resolvingSymlinksInPath().standardizedFileURL.path == url.standardizedFileURL.path,
track.offsetMs >= 0 else { throw DiarizationAudioSource.SourceError.invalidPath }
let offset = track.channel == nil ? track.offsetMs : 0
identities += [track.speaker, String(track.channel ?? -1)]
let source = Source(file: track.file, offset: offset)
let index: Int
if let existing = sources.firstIndex(of: source) {
index = existing
} else {
index = sources.count
sources.append(source)
let info = try? url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey])
identities += [track.file, String(offset), String(info?.fileSize ?? -1),
String(info?.contentModificationDate?.timeIntervalSince1970 ?? 0)]
}
tracks.append(.init(file: "track-\(index).wav", speaker: track.speaker,
offsetMs: max(0, offset - range.startMs),
channel: track.channel, participant: track.participant))
}

// Keep provider job IDs and response caches in the same namespace on a
// retry. Different markers or source files can never pick up that job.
let digest = DiarizationArtifacts.sha256(Data(identities.joined(separator: "\u{1f}").utf8))
let directory = root.appendingPathComponent(folderPrefix + digest, isDirectory: true)
guard directory.resolvingSymlinksInPath().path == directory.path else {
throw DiarizationAudioSource.SourceError.invalidPath
}
try fm.createDirectory(at: directory, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
let projected = SessionMeta(tracks: tracks, title: meta.title, attendees: meta.attendees,
app: meta.app, callAudio: meta.callAudio)
let result = Self(directory: directory, meta: projected)
do {
for (index, source) in sources.enumerated() {
try Task.checkCancellation()
let input = root.appendingPathComponent(source.file)
let output = directory.appendingPathComponent("track-\(index).wav")
// A missing original remains missing: the existing input logic
// distinguishes an absent microphone from a lost participant.
guard (try? output.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) != true
else { throw DiarizationAudioSource.SourceError.invalidPath }
if fm.fileExists(atPath: output.path) { try fm.removeItem(at: output) }
guard fm.fileExists(atPath: input.path) else { continue }
if (try input.resourceValues(forKeys: [.fileSizeKey])).fileSize == 0 {
// Recorder placeholders are treated as silent by TranscriptionInputs.
try Data().write(to: output, options: .withoutOverwriting)
continue
}
try extract(input, offsetMs: source.offset, range: range, to: output)
// Offline echo cancellation derives its retry identity from the
// input's mtime as well as its bounded directory, channel and size.
if let date = try input.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate {
try fm.setAttributes([.modificationDate: date], ofItemAtPath: output.path)
}
}
} catch {
result.removeAudio()
throw error
}
return result
}

func removeAudio() {
let fm = FileManager.default
for name in Set(meta.tracks.map(\.file) + TranscriptionScratch.derivedAudio) {
try? fm.removeItem(at: directory.appendingPathComponent(name))
}
}

private static func extract(_ input: URL, offsetMs: Int, range: RecordingRange, to output: URL) throws {
let reader = try AVAudioFile(forReading: input)
let format = reader.processingFormat
let rate = format.sampleRate
guard rate.isFinite, rate > 0 else { throw DiarizationAudioSource.SourceError.invalidPCM }
func frame(at marker: Int) -> AVAudioFramePosition {
let value = ceil(Double(max(0, marker - offsetMs)) * rate / 1000)
return value >= Double(reader.length) ? reader.length : AVAudioFramePosition(value)
}
let start = frame(at: range.startMs)
let end = frame(at: range.endMs)
let writer = try AVAudioFile(forWriting: output, settings: [
AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: rate,
AVNumberOfChannelsKey: format.channelCount, AVLinearPCMBitDepthKey: 24,
AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsNonInterleaved: false
], commonFormat: format.commonFormat, interleaved: format.isInterleaved)
guard start < end else { return }
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 16_384)
else { throw DiarizationAudioSource.SourceError.invalidPCM }
reader.framePosition = start
while reader.framePosition < end {
try Task.checkCancellation()
try reader.read(into: buffer, frameCount: AVAudioFrameCount(min(16_384, end - reader.framePosition)))
guard buffer.frameLength > 0 else { throw DiarizationAudioSource.SourceError.invalidPCM }
try writer.write(from: buffer)
}
}
}

extension RecordingRange {
var diarizationSourcePrefix: String { "diarization-source-range-\(startMs)-\(endMs)-" }

/// Engines and the diarizer work on the fragment clock. Published text is
/// seekable on the full recording, including after a deferred speaker pass.
func onRecordingClock(_ segments: [Transcript.Segment]) -> [Transcript.Segment] {
let duration = endMs - startMs
return segments.compactMap { segment in
guard segment.start_ms < duration, segment.end_ms >= 0 else { return nil }
return .init(speaker: segment.speaker,
start_ms: startMs + max(0, segment.start_ms),
end_ms: startMs + min(duration, max(segment.start_ms, segment.end_ms)),
text: segment.text)
}
}
}
16 changes: 16 additions & 0 deletions Sources/verbemo/Audio/TrackCompressor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,27 @@ enum TrackCompressor {
}
}

// A request can retire before publishing its range. Retiring a recording
// and the archive-only path both call compress directly, bypassing settle.
private static func preservesSourceForRange(_ dir: URL) -> Bool {
if SessionState.value(dir, SessionState.Key.preserveAudioForRange) as? Bool == true { return true }
do {
if try TranscriptVersions.appliedRange(in: dir) != nil { return true }
return try TranscriptVersions.readRequest(dir)?.range != nil
} catch {
// The user's choice is unreadable. The complete source remains
// available for recovery along with the previous transcript.
return true
}
}

/// Delete the audio, leaving the transcript, the summary and the record of
/// what was recorded. meta.json keeps its `files` — it is the session's
/// account of itself, and "there was a mic track called mic.caf" stays
/// true after the file goes — and gains `audio_discarded`, which is what
/// stops the recordings window offering to transcribe it again.
static func discard(sessionDir dir: URL) {
guard !preservesSourceForRange(dir) else { return }
func log(_ message: String) { appendSessionLog(message, to: dir) }
let fm = FileManager.default

Expand Down Expand Up @@ -86,6 +101,7 @@ enum TrackCompressor {
/// replaced. A missing track becomes a silent channel; an existing track
/// that cannot be read aborts the operation and remains untouched.
static func compress(sessionDir dir: URL) {
guard !preservesSourceForRange(dir) else { return }
func log(_ message: String) { appendSessionLog(message, to: dir) }

let metaURL = dir.appendingPathComponent("meta.json")
Expand Down
2 changes: 2 additions & 0 deletions Sources/verbemo/SessionState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ enum SessionState {
/// Optional per-session choice made from Recordings' Re-transcribe
/// context menu. It survives another manual retry as the last choice.
static let transcriptionEngine = "transcription_engine"
/// The user needs the original timeline to move or remove saved range markers.
static let preserveAudioForRange = "preserve_audio_for_range"
/// `deferred` — every backend failed for a reason that will pass (no
/// network, spent allowance): retry later. `failed: <reason>` — it
/// won't work on a retry. Absent — nothing to do, either because the
Expand Down
2 changes: 1 addition & 1 deletion Sources/verbemo/Sessions/PostProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ enum PostProcessor {
appendSessionLog("can't replace unreadable saved diarization request", to: dir)
return false
}
let choice = request ?? .capture(engine: EngineResolver.configuredEngine(for: dir))
let choice = try request ?? .repeating(in: dir, engine: EngineResolver.configuredEngine(for: dir))
try choice.write(to: dir)
try SessionState.amend(dir, with: [
SessionState.Key.transcriptionFailed: nil,
Expand Down
63 changes: 61 additions & 2 deletions Sources/verbemo/Sessions/TranscriptVersions.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import Foundation
import CryptoKit

/// Milliseconds on the original meeting timeline. The end marker is exclusive.
struct RecordingRange: Codable, Equatable, Sendable {
let startMs: Int
let endMs: Int

enum CodingKeys: String, CodingKey {
case startMs = "start_ms"
case endMs = "end_ms"
}

func validate() throws {
guard startMs >= 0, endMs > startMs else { throw CocoaError(.coderInvalidValue) }
}
}

/// The latest result remains at the recording root for CLI and hook compatibility.
/// Previous results have their own transcript, names, summary and processing state.
enum TranscriptVersions {
Expand All @@ -11,14 +26,36 @@ enum TranscriptVersions {
let engine: String
// nil is an explicit opt-out, independent of subsequent settings changes.
let diarization: DiarizationState.Request?
let range: RecordingRange?
let summaryInstruction: String?

init(engine: String, diarization: DiarizationState.Request?, range: RecordingRange? = nil,
summaryInstruction: String? = nil) {
self.engine = engine
self.diarization = diarization
self.range = range
let instruction = summaryInstruction?.trimmingCharacters(in: .whitespacesAndNewlines)
self.summaryInstruction = instruction?.isEmpty == false ? instruction : nil
}

static func capture(engine: String) -> Self {
static func capture(engine: String, range: RecordingRange? = nil, summaryInstruction: String? = nil) -> Self {
Self(engine: engine, diarization: Config.localDiarizationEnabled() && !Config.cloudEngines.contains(engine)
? .init(engine: engine, threshold: Config.diarizationThreshold(),
explicit: true, model: Config.diarizationModel()) : nil)
explicit: true, model: Config.diarizationModel()) : nil, range: range,
summaryInstruction: summaryInstruction)
}

/// Reuse the meeting's selection when an entry point only changes the engine.
static func repeating(in dir: URL, engine: String) throws -> Self {
if let pending = try TranscriptVersions.readRequest(dir) {
return capture(engine: engine, range: pending.range, summaryInstruction: pending.summaryInstruction)
}
return try capture(engine: engine, range: TranscriptVersions.appliedRange(in: dir),
summaryInstruction: TranscriptVersions.appliedSummaryInstruction(in: dir))
}

func write(to dir: URL) throws {
try range?.validate()
try JSONEncoder().encode(self).write(
to: dir.appendingPathComponent(requestFile), options: .atomic)
}
Expand All @@ -32,13 +69,34 @@ enum TranscriptVersions {
return .capture(engine: text)
}
let request = try JSONDecoder().decode(Request.self, from: data)
try request.range?.validate()
guard EngineResolver.knownEngines.contains(request.engine),
request.diarization.map({ $0.engine == request.engine && $0.threshold.isFinite
&& (0.3...1.2).contains($0.threshold) }) ?? true else {
throw CocoaError(.coderReadCorrupt)
}
return request
}

/// The committed transcript owns its recording range, even while a replacement is queued.
static func appliedRange(in dir: URL) throws -> RecordingRange? {
guard let metadata = SessionState.read(dir) else {
throw SessionState.StateError.unreadable(dir.appendingPathComponent("meta.json"))
}
guard let request = metadata[requestKey] else { return nil }
guard let fields = request as? [String: Any] else { throw CocoaError(.coderReadCorrupt) }
guard let raw = fields["range"], !(raw is NSNull) else { return nil }
guard let object = raw as? [String: Any] else { throw CocoaError(.coderReadCorrupt) }
let range = try JSONDecoder().decode(RecordingRange.self, from: JSONSerialization.data(withJSONObject: object))
try range.validate()
return range
}

static func appliedSummaryInstruction(in dir: URL) -> String? {
let request = SessionState.value(dir, requestKey) as? [String: Any]
return request?["summaryInstruction"] as? String
}

static let journalDirectory = ".transcript-commit"
private static let transactionFiles: Set<String> = [
"transcript.json", "transcript.md", SpeakerNames.file, "meta.json",
Expand Down Expand Up @@ -232,6 +290,7 @@ enum TranscriptVersions {
if let request = try readRequest(dir) {
nextMeta[requestKey] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(request))
nextMeta[SessionState.Key.transcriptionEngine] = request.engine
if request.range != nil { nextMeta[SessionState.Key.preserveAudioForRange] = true }
}
if isRequested(dir) || oldJSON != nil {
let reset: [String: Any?] = [
Expand Down
17 changes: 12 additions & 5 deletions Sources/verbemo/Summary/Summarizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ enum Summarizer {
// Whatever we know about the meeting, above the transcript. Names in
// particular: given a participant list, the summarizer writes "Anna
// will send the contract" instead of "them will send the contract".
let instruction = request?.additionalInstruction ?? TranscriptVersions.appliedSummaryInstruction(in: dir) ?? ""
let header = context.isEmpty ? "" : context.joined(separator: "\n") + "\n"
for (index, backend) in backends.enumerated() {
guard !Task.isCancelled else { return nil }
Expand All @@ -73,7 +74,7 @@ enum Summarizer {
try Task.checkCancellation()
log("summarizing with \(backend.name)")
let markdown = try await produce(
body: body, header: header, settings: settings, backend: backend
body: body, header: header, instruction: instruction, settings: settings, backend: backend
)
try Task.checkCancellation()
let text = markdown.trimmingCharacters(in: .whitespacesAndNewlines)
Expand Down Expand Up @@ -175,28 +176,34 @@ enum Summarizer {
private static func produce(
body: String,
header: String,
instruction: String,
settings: Config.SummarySettings,
backend: LLMBackend
) async throws -> String {
let system = systemPrompt(language: settings.language)
var system = systemPrompt(language: settings.language)
var closingInstruction = ""
if !instruction.isEmpty {
system += "\nApply the user's final instructions to every section. They determine which facts belong in the summary, even if the template asks for all decisions or tasks. Silently omit excluded topics."
closingInstruction = "\n\n---\nUser instructions for this summary:\n" + instruction
}
let limit = min(maxCharsPerCall, backend.promptLimit ?? maxCharsPerCall)
if body.count <= limit {
return try await backend.call(system, singlePassPrompt(
body: body, header: header, template: settings.template))
body: body, header: header, template: settings.template) + closingInstruction)
}

let chunks = split(body, limit: limit)
var notes: [String] = []
for (index, chunk) in chunks.enumerated() {
notes.append(try await backend.call(
system,
"\(header)Part \(index + 1) of \(chunks.count).\n\(chunkInstructions)\n\n---\n\(chunk)"
"\(header)Part \(index + 1) of \(chunks.count).\n\(chunkInstructions)\n\n---\n\(chunk)" + closingInstruction
))
}
return try await backend.call(
system,
"\(header)\n\(mergeInstructions)\n\(settings.template)\n\n---\n"
+ notes.joined(separator: "\n\n---\n\n")
+ notes.joined(separator: "\n\n---\n\n") + closingInstruction
)
}

Expand Down
Loading
Loading