diff --git a/apps/cli/main.cpp b/apps/cli/main.cpp index 8f622f1..6660303 100644 --- a/apps/cli/main.cpp +++ b/apps/cli/main.cpp @@ -57,6 +57,8 @@ constexpr const char* kUsage = R"(usage: --models DIR model directory --checkpoint FILE record progress here; run again with the same file to go on after an interruption + --speech FILE keep the detected speech here; run again with + the same file to skip detecting it --as-recorded leave the loudness as it is, for audio evened out already --quiet no progress output @@ -373,6 +375,7 @@ int RunTranscribe(const std::vector& all_args) { {"diarize", args.Has("diarize")}, {"glossary", GlossaryTerms(args)}}; if (const auto checkpoint = args.Get("checkpoint")) options["checkpoint"] = *checkpoint; + if (const auto speech = args.Get("speech")) options["speech"] = *speech; if (args.Has("as-recorded")) options["even_loudness"] = false; sillok_job* raw_job = nullptr; Check(sillok_job_create(engine.get(), options.dump().c_str(), &raw_job), "job"); diff --git a/apps/mac/Packages/SillokKit/Sources/SillokEngine/Job.swift b/apps/mac/Packages/SillokKit/Sources/SillokEngine/Job.swift index e3766a6..44c18b0 100644 --- a/apps/mac/Packages/SillokKit/Sources/SillokEngine/Job.swift +++ b/apps/mac/Packages/SillokKit/Sources/SillokEngine/Job.swift @@ -47,11 +47,13 @@ public enum Transcription { copy: URL, options: JobOptions, checkpoint: URL, + speech: URL, events: @escaping @Sendable (TranscriptionEvent) -> Void ) async throws -> TranscriptionResult { let request = Job.Request( language: options.language, diarize: options.diarize, glossary: options.glossary, - evenLoudness: false, checkpoint: checkpoint.path(percentEncoded: false)) + evenLoudness: false, checkpoint: checkpoint.path(percentEncoded: false), + speech: speech.path(percentEncoded: false)) let job = try Job(engine: engine, request: request) return try await job.perform { try job.transcribe(input: copy, events: events) } } @@ -64,6 +66,7 @@ final class Job: @unchecked Sendable { var glossary: [String] = [] var evenLoudness = true var checkpoint: String? + var speech: String? } private let handle: OpaquePointer diff --git a/apps/mac/Packages/SillokKit/Sources/SillokStore/RecordingStore.swift b/apps/mac/Packages/SillokKit/Sources/SillokStore/RecordingStore.swift index 47dd77b..30ca120 100644 --- a/apps/mac/Packages/SillokKit/Sources/SillokStore/RecordingStore.swift +++ b/apps/mac/Packages/SillokKit/Sources/SillokStore/RecordingStore.swift @@ -31,6 +31,7 @@ public struct RecordingStore: Sendable { static let transcriptName = "transcript.json" static let metadataName = "meta.json" static let checkpointName = "checkpoint.jsonl" + static let speechName = "speech.bin" static let editsName = "edits.json" public let root: URL @@ -51,6 +52,10 @@ public struct RecordingStore: Sendable { folder(for: id).appending(path: Self.checkpointName) } + public func speech(for id: UUID) -> URL { + folder(for: id).appending(path: Self.speechName) + } + public func makeStaging() throws -> URL { let staging = root.appending(path: ".staging-\(UUID().uuidString)", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true) @@ -66,6 +71,7 @@ public struct RecordingStore: Sendable { let staging = try makeStaging() do { try FileManager.default.copyItem(at: audio(for: source), to: staging.appending(path: Self.audioName)) + try? FileManager.default.copyItem(at: speech(for: source), to: staging.appending(path: Self.speechName)) try add(staging: staging, recording: recording) } catch { discard(staging: staging) diff --git a/apps/mac/Packages/SillokKit/Tests/SillokEngineTests/TranscriptionTests.swift b/apps/mac/Packages/SillokKit/Tests/SillokEngineTests/TranscriptionTests.swift index 1a9c96d..ce1ca01 100644 --- a/apps/mac/Packages/SillokKit/Tests/SillokEngineTests/TranscriptionTests.swift +++ b/apps/mac/Packages/SillokKit/Tests/SillokEngineTests/TranscriptionTests.swift @@ -77,6 +77,7 @@ struct RealModels { let audio: URL let copy = temporaryCopy() let checkpoint = FileManager.default.temporaryDirectory.appending(path: "sillok-\(UUID().uuidString).jsonl") + let speech = FileManager.default.temporaryDirectory.appending(path: "sillok-\(UUID().uuidString).bin") init() throws { let models = URL(filePath: Self.environment["SILLOK_TEST_MODELS"]!) @@ -88,18 +89,23 @@ struct RealModels { @Test(.enabled(if: RealModels.available)) func transcribesACopyOfARecording() async throws { let real = try RealModels() - defer { try? FileManager.default.removeItem(at: real.copy) } + defer { + try? FileManager.default.removeItem(at: real.copy) + try? FileManager.default.removeItem(at: real.speech) + } try await Transcription.copy(input: real.audio, output: real.copy) { _ in } #expect(FileManager.default.fileExists(atPath: real.copy.path())) let events = Mutex<[TranscriptionEvent]>([]) let result = try await Transcription.run( - engine: real.engine, copy: real.copy, options: JobOptions(diarize: true), checkpoint: real.checkpoint + engine: real.engine, copy: real.copy, options: JobOptions(diarize: true), checkpoint: real.checkpoint, + speech: real.speech ) { event in events.withLock { $0.append(event) } } #expect(!result.transcript.segments.isEmpty) #expect(result.transcript.segments.allSatisfy { $0.speaker != nil }) #expect(!FileManager.default.fileExists(atPath: real.checkpoint.path())) + #expect(FileManager.default.fileExists(atPath: real.speech.path())) let stages = events.withLock { $0.compactMap { if case .stage(let stage, _) = $0 { stage } else { nil } } } #expect(Set(stages).isSuperset(of: [.analyze, .transcribe, .diarize])) let previews = events.withLock { $0.contains { if case .preview = $0 { true } else { false } } } diff --git a/apps/mac/Packages/SillokKit/Tests/SillokStoreTests/RecordingStoreTests.swift b/apps/mac/Packages/SillokKit/Tests/SillokStoreTests/RecordingStoreTests.swift index 31e1fdd..33365a7 100644 --- a/apps/mac/Packages/SillokKit/Tests/SillokStoreTests/RecordingStoreTests.swift +++ b/apps/mac/Packages/SillokKit/Tests/SillokStoreTests/RecordingStoreTests.swift @@ -48,6 +48,15 @@ struct RecordingStoreTests { #expect(try store.list().map(\.id) == [recording.id]) } + @Test func copiesTheDetectedSpeechWithTheRecording() throws { + let recording = try save("meeting", at: Date(timeIntervalSince1970: 1_000)) + try Data("speech".utf8).write(to: store.speech(for: recording.id)) + let copy = Recording(title: recording.title, sourceName: recording.sourceName, + options: JobOptions(language: "en"), transcriptionModel: "qwen") + try store.add(copyOf: recording.id, as: copy) + #expect(try Data(contentsOf: store.speech(for: copy.id)) == Data("speech".utf8)) + } + @Test func finishingARecordingClearsItsError() throws { let recording = try add("meeting", at: Date(timeIntervalSince1970: 1_000)) try store.update(recording.id) { $0.error = "The model failed." } diff --git a/apps/mac/Sillok/NewJob/JobQueue.swift b/apps/mac/Sillok/NewJob/JobQueue.swift index c8ee941..25e673d 100644 --- a/apps/mac/Sillok/NewJob/JobQueue.swift +++ b/apps/mac/Sillok/NewJob/JobQueue.swift @@ -231,7 +231,8 @@ final class JobQueue { let result = try await perform(item.id) { events in try await Transcription.run( engine: engine, copy: store.audio(for: item.id), options: item.options, - checkpoint: store.checkpoint(for: item.id), events: events) + checkpoint: store.checkpoint(for: item.id), speech: store.speech(for: item.id), + events: events) } guard self.item(item.id) != nil else { throw CancellationError() } try store.finish(item.id, transcriptJSON: result.json, durationMs: result.transcript.durationMs, diff --git a/include/sillok/sillok.h b/include/sillok/sillok.h index 0e56250..7f2735f 100644 --- a/include/sillok/sillok.h +++ b/include/sillok/sillok.h @@ -138,7 +138,7 @@ SILLOK_API void sillok_engine_destroy(sillok_engine* engine); /* One recording. `options_json`: {"language": "auto" | "", * "diarize": false, "glossary": ["term", ...], "even_loudness": true, - * "checkpoint": ""} + * "checkpoint": "", "speech": ""} * "language": "auto" tells the language of each piece the model hears at * once (speech joined up to 30 s, or less for a model that takes less), * among the model's "languages", so a recording may switch language between @@ -162,10 +162,18 @@ SILLOK_API void sillok_engine_destroy(sillok_engine* engine); * options and transcription model with the same file goes on after the * pieces it finds there, first passing them to the segment callback, and * gives the transcript one run would have given; otherwise it starts the - * file anew. Detecting speech and diarization run again in full, as they are - * quick. The file is removed when the job succeeds and kept when it fails or - * is cancelled: a new job with the same file then goes on, as after a crash. - * A file that cannot be written is dropped and the job carries on. + * file anew. Diarization runs again in full, as it is quick, and so does + * detecting speech without "speech". The file is removed when the job + * succeeds and kept when it fails or is cancelled: a new job with the same + * file then goes on, as after a crash. A file that cannot be written is + * dropped and the job carries on. + * With "speech", the job keeps in that file where the recording has speech + * (about 0.5 MB an hour), once it has detected it. A later job of the same + * recording with the same file, whatever its options, skips detecting + * speech, which takes some 15 s an hour of audio; a file of another + * recording, speech model or library version is written anew. The file is + * kept for the jobs to come; one that cannot be written is dropped and the + * job carries on. * With `engine` NULL, the job only reads audio and saves it * (sillok_job_save_audio), which needs no models: the language is not * checked, and sillok_job_run() returns SILLOK_INVALID_ARGUMENT. */ diff --git a/src/capi/CMakeLists.txt b/src/capi/CMakeLists.txt index dd5eb04..9ae502e 100644 --- a/src/capi/CMakeLists.txt +++ b/src/capi/CMakeLists.txt @@ -1,7 +1,7 @@ # The C ABI over the core. An object library, so that the shared library # keeps every exported function (cmake/library.cmake); the tests link the same # objects with fake models. -add_library(sillok_capi OBJECT checkpoint.cpp json_io.cpp sillok.cpp) +add_library(sillok_capi OBJECT checkpoint.cpp json_io.cpp sillok.cpp speech_file.cpp) target_include_directories(sillok_capi PUBLIC "${PROJECT_SOURCE_DIR}/include") target_link_libraries(sillok_capi PUBLIC sillok_core sillok_media diff --git a/src/capi/json_io.cpp b/src/capi/json_io.cpp index 45249a4..9a386ec 100644 --- a/src/capi/json_io.cpp +++ b/src/capi/json_io.cpp @@ -120,13 +120,14 @@ JobOptions ParseJobOptions(std::string_view text) { PipelineOptions& options = job.pipeline; const Json json = Parse(text, "job options"); RejectUnknownKeys(json, "job options", - {"language", "diarize", "glossary", "even_loudness", "checkpoint"}); + {"language", "diarize", "glossary", "even_loudness", "checkpoint", "speech"}); // Checked against the engine's model by sillok_job_create. options.language = Get(json, "language", "auto"); options.diarize = Get(json, "diarize", false); options.glossary = Get>(json, "glossary", {}); job.even_loudness = Get(json, "even_loudness", true); job.checkpoint = PathFromUtf8(Get(json, "checkpoint", "")); + job.speech = PathFromUtf8(Get(json, "speech", "")); return job; } diff --git a/src/capi/json_io.hpp b/src/capi/json_io.hpp index 186c64d..826e061 100644 --- a/src/capi/json_io.hpp +++ b/src/capi/json_io.hpp @@ -27,6 +27,7 @@ struct JobOptions { // already has, such as a job's copy for listening back. bool even_loudness = true; std::filesystem::path checkpoint; // empty for none + std::filesystem::path speech; // empty for none }; JobOptions ParseJobOptions(std::string_view json); diff --git a/src/capi/sillok.cpp b/src/capi/sillok.cpp index 25b22cb..2432887 100644 --- a/src/capi/sillok.cpp +++ b/src/capi/sillok.cpp @@ -26,6 +26,7 @@ #include "backends/models.hpp" #include "capi/checkpoint.hpp" #include "capi/json_io.hpp" +#include "capi/speech_file.hpp" #include "core/audio.hpp" #include "core/cancel.hpp" #include "core/files.hpp" @@ -101,12 +102,14 @@ struct sillok_job { : engine(std::move(engine_state)), options(std::move(job_options.pipeline)), checkpoint(std::move(job_options.checkpoint)), + speech(std::move(job_options.speech)), input(audio, job_options.even_loudness ? sillok::AudioInput::Loudness::kEvenedOut : sillok::AudioInput::Loudness::kAsRecorded) {} std::shared_ptr engine; sillok::PipelineOptions options; std::filesystem::path checkpoint; // empty for none + std::filesystem::path speech; // empty for none sillok::AudioBuffer audio; sillok::AudioInput input; // converts pushed audio into `audio` sillok::StopSource stop; @@ -466,6 +469,8 @@ sillok_status sillok_job_run(sillok_job* job, sillok_progress_fn progress, checkpoint.emplace(job->checkpoint, sillok_version(), job->engine->transcription_model); resume = checkpoint->Load(); } + std::optional speech; + if (!job->speech.empty()) speech.emplace(job->speech, sillok_version()); const sillok::Transcript transcript = sillok::RunPipeline( job->audio, job->options, models, [&](sillok::Stage stage, double fraction) { @@ -477,7 +482,8 @@ sillok_status sillok_job_run(sillok_job* job, sillok_progress_fn progress, const std::string json = sillok::PreviewToJson(preview); job->on_segments(job->segments_user_data, json.c_str()); }, - resume ? &*resume : nullptr, checkpoint ? &*checkpoint : nullptr); + resume ? &*resume : nullptr, checkpoint ? &*checkpoint : nullptr, + speech ? &*speech : nullptr); if (checkpoint) checkpoint->Remove(); *out_json = sillok::CopyString(sillok::TranscriptToJson(transcript)); return SILLOK_OK; diff --git a/src/capi/speech_file.cpp b/src/capi/speech_file.cpp new file mode 100644 index 0000000..2147f25 --- /dev/null +++ b/src/capi/speech_file.cpp @@ -0,0 +1,70 @@ +#include "capi/speech_file.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace sillok { +namespace { + +using Json = nlohmann::json; + +constexpr int kFormat = 1; + +static_assert(std::endian::native == std::endian::little); + +} // namespace + +SpeechFile::SpeechFile(std::filesystem::path path, std::string library) + : path_(std::move(path)), library_(std::move(library)) {} + +std::optional SpeechFile::Load() { + std::string text; + { + std::ifstream in(path_, std::ios::binary); + if (!in) return std::nullopt; + std::ostringstream content; + content << in.rdbuf(); + text = std::move(content).str(); + } + const std::size_t end = text.find('\n'); + if (end == std::string::npos) return std::nullopt; + DetectedSpeech speech; + try { + const Json header = Json::parse(text.substr(0, end)); + if (header.value("format", 0) != kFormat || header.value("library", "") != library_) { + return std::nullopt; + } + speech.key = header.at("key").get(); + } catch (const std::exception&) { + return std::nullopt; + } + const std::size_t bytes = text.size() - end - 1; + if (bytes % sizeof(float) != 0) return std::nullopt; + speech.probabilities.resize(bytes / sizeof(float)); + std::memcpy(speech.probabilities.data(), text.data() + end + 1, bytes); + return speech; +} + +void SpeechFile::Save(const DetectedSpeech& speech) { + const Json header = {{"format", kFormat}, {"library", library_}, {"key", speech.key}}; + const std::string line = header.dump() + "\n"; + { + std::ofstream out(path_, std::ios::binary | std::ios::trunc); + out.write(line.data(), static_cast(line.size())); + out.write(reinterpret_cast(speech.probabilities.data()), + static_cast(speech.probabilities.size() * sizeof(float))); + out.flush(); + if (out) return; + } + std::error_code ignored; + std::filesystem::remove(path_, ignored); +} + +} // namespace sillok diff --git a/src/capi/speech_file.hpp b/src/capi/speech_file.hpp new file mode 100644 index 0000000..4cd7513 --- /dev/null +++ b/src/capi/speech_file.hpp @@ -0,0 +1,33 @@ +#ifndef SILLOK_CAPI_SPEECH_FILE_HPP_ +#define SILLOK_CAPI_SPEECH_FILE_HPP_ + +#include +#include +#include + +#include "core/pipeline.hpp" + +namespace sillok { + +// A job's file of detected speech (the job option "speech"): a JSON header +// line with the format, the library and the key, then the probabilities as +// little-endian 32-bit floats. A file of another format or library, or cut +// short, is not used. Writing is best effort: when it fails the file is +// removed, and the job carries on without one. +class SpeechFile final : public SpeechStore { + public: + // `library` names the library version: a file written by another is not + // used. + SpeechFile(std::filesystem::path path, std::string library); + + std::optional Load() override; + void Save(const DetectedSpeech& speech) override; + + private: + std::filesystem::path path_; + std::string library_; +}; + +} // namespace sillok + +#endif // SILLOK_CAPI_SPEECH_FILE_HPP_ diff --git a/src/core/pipeline.cpp b/src/core/pipeline.cpp index fd5d582..108e0a5 100644 --- a/src/core/pipeline.cpp +++ b/src/core/pipeline.cpp @@ -34,42 +34,83 @@ struct Speech { int frame_samples = 1; }; -Speech DetectSpeech(const AudioBuffer& audio, const SegmenterOptions& options, - ModelProvider& models, const ProgressCallback& progress, - const StopToken& stop, Transcript& transcript) { - progress(Stage::kAnalyze, - 0.0); // before the model loads, which takes a while - ThrowIfStopped(stop); // perhaps from the call above - const auto detector = models.OpenVoiceDetector(); - Speech speech{.regions = {}, .probabilities = {}, .frame_samples = detector->FrameSamples()}; +void Add(Sha256& hash, std::string_view text) { + hash.Update(std::span(reinterpret_cast(text.data()), text.size())); + hash.Update(std::span(reinterpret_cast("\n"), 1)); +} + +// Identifies a recording, for the keys of what a run keeps. +std::string HashAudio(const AudioBuffer& audio) { + Sha256 hash; + constexpr SampleIndex kBlock = SampleIndex{kSampleRate} * 60; + for (SampleIndex begin = 0; begin < audio.size(); begin += kBlock) { + const std::vector part = audio.Read({begin, begin + kBlock}); + hash.Update(std::span(reinterpret_cast(part.data()), + part.size() * sizeof(float))); + } + return hash.HexDigest(); +} + +// Identifies the speech `detector` detects in the recording hashed as +// `recording`. Bump the first line when the same input gives other +// probabilities. +std::string SpeechKey(const std::string& recording, const VoiceDetector& detector) { + Sha256 hash; + Add(hash, "sillok speech 1"); + Add(hash, detector.Info().name); + Add(hash, recording); + return hash.HexDigest(); +} + +std::vector DetectProbabilities(const AudioBuffer& audio, VoiceDetector& detector, + const ProgressCallback& progress, const StopToken& stop) { + std::vector probabilities; // About 30 s per call, in whole frames so the detector state carries over. - const SampleIndex chunk = - std::max(1, SampleIndex{kSampleRate} * 30 / speech.frame_samples) * - speech.frame_samples; + const SampleIndex frame = detector.FrameSamples(); + const SampleIndex chunk = std::max(1, SampleIndex{kSampleRate} * 30 / frame) * frame; for (SampleIndex begin = 0; begin < audio.size(); begin += chunk) { ThrowIfStopped(stop); - const std::vector part = - detector->Detect(audio.Read({begin, begin + chunk})); - speech.probabilities.insert(speech.probabilities.end(), part.begin(), part.end()); + const std::vector part = detector.Detect(audio.Read({begin, begin + chunk})); + probabilities.insert(probabilities.end(), part.begin(), part.end()); progress(Stage::kAnalyze, static_cast(std::min(begin + chunk, audio.size())) / static_cast(audio.size())); } + return probabilities; +} + +// `store` (may be null) keeps the probabilities of the recording hashed as +// `recording`. +Speech DetectSpeech(const AudioBuffer& audio, const SegmenterOptions& options, + ModelProvider& models, const ProgressCallback& progress, + const StopToken& stop, SpeechStore* store, const std::string& recording, + Transcript& transcript) { + const auto detector = models.OpenVoiceDetector(); + Speech speech{.regions = {}, .probabilities = {}, .frame_samples = detector->FrameSamples()}; + const auto frames = static_cast((audio.size() + speech.frame_samples - 1) / + speech.frame_samples); + const std::string key = store != nullptr ? SpeechKey(recording, *detector) : ""; + std::optional saved = store != nullptr ? store->Load() : std::nullopt; + if (saved && saved->key == key && saved->probabilities.size() == frames) { + speech.probabilities = std::move(saved->probabilities); + progress(Stage::kAnalyze, 1.0); + } else { + speech.probabilities = DetectProbabilities(audio, *detector, progress, stop); + if (store != nullptr) store->Save({.key = key, .probabilities = speech.probabilities}); + } transcript.models["voice_detection"] = detector->Info(); speech.regions = FindSpeech(speech.probabilities, speech.frame_samples, audio.size(), options); return speech; } -// Identifies what a checkpoint was made of: the recording and the options -// that shape its chunks and their transcription. The models are the caller's -// to tell apart (CheckpointSink). Bump the first line when the same input -// gives other chunks or other results. -std::string CheckpointKey(const AudioBuffer& audio, const PipelineOptions& options) { +// Identifies what a checkpoint was made of: the recording (hashed as +// `recording`) and the options that shape its chunks and their +// transcription. The models are the caller's to tell apart +// (CheckpointSink). Bump the first line when the same input gives other +// chunks or other results. +std::string CheckpointKey(const std::string& recording, const PipelineOptions& options) { Sha256 hash; - const auto add = [&](std::string_view text) { - hash.Update(std::span(reinterpret_cast(text.data()), text.size())); - hash.Update(std::span(reinterpret_cast("\n"), 1)); - }; + const auto add = [&](std::string_view text) { Add(hash, text); }; add("sillok checkpoint 5"); add(options.language); for (const std::string& term : options.glossary) add(term); @@ -82,12 +123,7 @@ std::string CheckpointKey(const AudioBuffer& audio, const PipelineOptions& optio segmenter.after, segmenter.max_chunk}) { add(std::to_string(time.count())); } - constexpr SampleIndex kBlock = SampleIndex{kSampleRate} * 60; - for (SampleIndex begin = 0; begin < audio.size(); begin += kBlock) { - const std::vector part = audio.Read({begin, begin + kBlock}); - hash.Update(std::span(reinterpret_cast(part.data()), - part.size() * sizeof(float))); - } + add(recording); return hash.HexDigest(); } @@ -353,7 +389,8 @@ std::vector Diarize(const AudioBuffer& audio, Transcript RunPipeline(const AudioBuffer& audio, const PipelineOptions& options, ModelProvider& models, const ProgressCallback& progress, StopToken stop, const SegmentsCallback& on_segments, - const Checkpoint* resume, CheckpointSink* checkpoints) { + const Checkpoint* resume, CheckpointSink* checkpoints, + SpeechStore* speech_store) { if (!audio.finished()) throw std::logic_error("audio is not finished"); if (options.language != "auto") { const std::vector languages = models.Languages(); @@ -366,12 +403,18 @@ Transcript RunPipeline(const AudioBuffer& audio, const PipelineOptions& options, transcript.duration = ToMilliseconds(audio.size()); if (audio.size() == 0) return transcript; - const Speech speech = DetectSpeech( - audio, options.segmenter, models, progress, stop, transcript); + // Before hashing the recording and loading the model, which take a while. + progress(Stage::kAnalyze, 0.0); + ThrowIfStopped(stop); // perhaps from the call above + const bool checkpointed = resume != nullptr || checkpoints != nullptr; + const std::string recording = + checkpointed || speech_store != nullptr ? HashAudio(audio) : ""; + const Speech speech = DetectSpeech(audio, options.segmenter, models, progress, stop, + speech_store, recording, transcript); Resumption run{.resume = nullptr, .sink = checkpoints, .key = {}}; - if (resume != nullptr || checkpoints != nullptr) { - run.key = CheckpointKey(audio, options); + if (checkpointed) { + run.key = CheckpointKey(recording, options); if (resume != nullptr && resume->key == run.key) run.resume = resume; } diff --git a/src/core/pipeline.hpp b/src/core/pipeline.hpp index 3f637e8..eac1264 100644 --- a/src/core/pipeline.hpp +++ b/src/core/pipeline.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -60,8 +61,8 @@ struct ChunkResult { // What an earlier run of the same recording, options and models finished, // chunk by chunk, for a run stopped part way to go on from there. -// Transcription and alignment are kept; detecting speech, diarization and -// splitting segments are quick and run again. +// Transcription and alignment are kept; detected speech is kept apart +// (SpeechStore); diarization and splitting segments are quick and run again. struct Checkpoint { std::string key; // the recording, options and models it belongs to // The chunks' limit, set by the transcriber, so the same chunks follow @@ -85,6 +86,22 @@ class CheckpointSink { virtual void AddModel(const std::string& stage, const ModelInfo& info) = 0; }; +// Each frame's speech probability in a recording, as the voice detector told +// it, so that a later run of the recording need not detect speech again. +struct DetectedSpeech { + std::string key; // the recording and voice detector it belongs to + std::vector probabilities; +}; + +// Where a run keeps the speech it detected. +class SpeechStore { + public: + virtual ~SpeechStore() = default; + // What an earlier run kept, if anything. + virtual std::optional Load() = 0; + virtual void Save(const DetectedSpeech& speech) = 0; +}; + // Transcribes `audio` (finished). Models are opened one stage at a time and // freed before the next stage, so the transcription, alignment and // diarization models are never in memory together. Throws Cancelled once `stop` is requested. @@ -92,13 +109,16 @@ class CheckpointSink { // With `resume` of the same recording, options and models, the run skips the // chunks it holds, previewing them first, and gives the transcript one run // would have given; otherwise it starts anew. `checkpoints` (may be null) -// records the progress either way. +// records the progress either way. With `speech` (may be null), the run uses +// the speech an earlier run of the same recording and voice detector +// detected; otherwise it detects speech and saves it there. Transcript RunPipeline(const AudioBuffer& audio, const PipelineOptions& options, ModelProvider& models, const ProgressCallback& progress, StopToken stop, const SegmentsCallback& on_segments = {}, const Checkpoint* resume = nullptr, - CheckpointSink* checkpoints = nullptr); + CheckpointSink* checkpoints = nullptr, + SpeechStore* speech = nullptr); } // namespace sillok diff --git a/tests/fakes/fake_models.cpp b/tests/fakes/fake_models.cpp index 50b4e6e..6574dff 100644 --- a/tests/fakes/fake_models.cpp +++ b/tests/fakes/fake_models.cpp @@ -56,12 +56,15 @@ std::string LanguageOf(const FakeOptions& options, int id) { class FakeVoiceDetector : public VoiceDetector { public: - explicit FakeVoiceDetector(LiveModels& live) : live_(live) { ++live_.detectors; } + FakeVoiceDetector(const FakeOptions& options, LiveModels& live) : options_(options), live_(live) { + ++live_.detectors; + } ~FakeVoiceDetector() override { --live_.detectors; } ModelInfo Info() const override { return {"fake-vad", "CPU", false}; } int FrameSamples() const override { return 512; } std::vector Detect(std::span pcm) override { + if (options_.on_detect) options_.on_detect(); std::vector probabilities; for (std::size_t begin = 0; begin < pcm.size(); begin += 512) { float peak = 0.0f; @@ -74,6 +77,7 @@ class FakeVoiceDetector : public VoiceDetector { } private: + const FakeOptions& options_; LiveModels& live_; }; @@ -282,7 +286,7 @@ std::string WordText(int id, const std::string& language) { } std::unique_ptr FakeModels::OpenVoiceDetector() { - return std::make_unique(live_); + return std::make_unique(options_, live_); } std::unique_ptr FakeModels::OpenTranscriber() { diff --git a/tests/fakes/fake_models.hpp b/tests/fakes/fake_models.hpp index 4f27396..bc49858 100644 --- a/tests/fakes/fake_models.hpp +++ b/tests/fakes/fake_models.hpp @@ -52,6 +52,8 @@ struct FakeOptions { // The longest glossary the transcriber takes, in bytes of its terms joined // by ", " (a token each). std::size_t glossary_room = 1000; + // Called at the start of every Detect call. + std::function on_detect; // Called at the start of every Transcribe call with its request. std::function on_transcribe; // The transcriber hands over each request's text without word times, and diff --git a/tests/unit/capi_test.cpp b/tests/unit/capi_test.cpp index 65d9e30..5354f4d 100644 --- a/tests/unit/capi_test.cpp +++ b/tests/unit/capi_test.cpp @@ -247,6 +247,32 @@ TEST_F(CapiTest, StartsAnewFromACheckpointOfAnotherRecording) { EXPECT_FALSE(std::filesystem::exists(file)); } +TEST_F(CapiTest, KeepsTheDetectedSpeechInAFile) { + const std::vector pcm = ScriptPcm(10); + const std::filesystem::path file = models_dir_ / PathFromUtf8("음성 구간.bin"); + { + std::ofstream damaged(file, std::ios::binary); + damaged << "{\"format\": 1, \"library\": \"another\", \"key\": \"\"}\n"; + } + int detections = 0; + FakeBackendOptions().on_detect = [&detections] { ++detections; }; + const auto run = [&](const char* language) { + const Json options = {{"language", language}, {"speech", PathToUtf8(file)}}; + sillok_job* job = Job(Engine(), options.dump().c_str()); + Push(job, pcm); + char* out = nullptr; + EXPECT_EQ(sillok_job_run(job, nullptr, nullptr, &out), SILLOK_OK) << sillok_last_error(); + return Json::parse(Take(out))["segments"]; + }; + + const Json first = run("auto"); + EXPECT_GT(std::exchange(detections, 0), 0); + EXPECT_TRUE(std::filesystem::exists(file)); + EXPECT_EQ(run("en"), first); + EXPECT_EQ(detections, 0); + EXPECT_TRUE(std::filesystem::exists(file)); +} + TEST_F(CapiTest, DiarizesAndListsSpeakers) { FakeBackendOptions().speakers = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 1}, {6, 1}, {7, 1}, {8, 1}, {9, 1}}; diff --git a/tests/unit/pipeline_test.cpp b/tests/unit/pipeline_test.cpp index 7ba9d66..855add5 100644 --- a/tests/unit/pipeline_test.cpp +++ b/tests/unit/pipeline_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "core/cancel.hpp" @@ -628,5 +629,56 @@ TEST(PipelineTest, StartsAnewFromACheckpointOfOtherOptions) { EXPECT_NE(sink.saved.key, resume.key); } +// Keeps a run's detected speech in memory. +class MemorySpeech : public SpeechStore { + public: + std::optional Load() override { return saved; } + void Save(const DetectedSpeech& speech) override { + saved = speech; + ++saves; + } + + std::optional saved; + int saves = 0; +}; + +TEST(PipelineTest, DetectsSpeechOnceForEveryRunOfARecording) { + const auto script = TwoSpeakers(); + const AudioBuffer audio = RenderScript(script, Milliseconds{62000}); + FakeOptions fakes = OptionsFor(script); + int detections = 0; + fakes.on_detect = [&] { ++detections; }; + MemorySpeech speech; + FakeModels first(fakes); + const Transcript expected = + RunPipeline(audio, {}, first, [](Stage, double) {}, {}, {}, nullptr, nullptr, &speech); + EXPECT_GT(detections, 0); + EXPECT_EQ(speech.saves, 1); + + PipelineOptions english; + english.language = "en"; + std::vector> analyzed; + FakeModels second(fakes); + detections = 0; + const Transcript again = RunPipeline( + audio, english, second, + [&](Stage stage, double fraction) { + if (stage == Stage::kAnalyze) analyzed.emplace_back(stage, fraction); + }, + {}, {}, nullptr, nullptr, &speech); + EXPECT_EQ(detections, 0); + EXPECT_EQ(speech.saves, 1); + EXPECT_EQ(SaidIn(again), SaidIn(expected)); + EXPECT_EQ(again.models.at("voice_detection").name, "fake-vad"); + EXPECT_EQ(analyzed, (std::vector>{{Stage::kAnalyze, 0.0}, + {Stage::kAnalyze, 1.0}})); + + const AudioBuffer other = RenderScript(Speech(0, 10, Milliseconds{500}), Milliseconds{5000}); + FakeModels third(fakes); + RunPipeline(other, {}, third, [](Stage, double) {}, {}, {}, nullptr, nullptr, &speech); + EXPECT_GT(detections, 0); + EXPECT_EQ(speech.saves, 2); +} + } // namespace } // namespace sillok