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
3 changes: 3 additions & 0 deletions apps/cli/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -373,6 +375,7 @@ int RunTranscribe(const std::vector<std::string>& 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");
Expand Down
5 changes: 4 additions & 1 deletion apps/mac/Packages/SillokKit/Sources/SillokEngine/Job.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
}
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"]!)
Expand All @@ -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 } } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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." }
Expand Down
3 changes: 2 additions & 1 deletion apps/mac/Sillok/NewJob/JobQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 13 additions & 5 deletions include/sillok/sillok.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ SILLOK_API void sillok_engine_destroy(sillok_engine* engine);

/* One recording. `options_json`: {"language": "auto" | "<code>",
* "diarize": false, "glossary": ["term", ...], "even_loudness": true,
* "checkpoint": "<path>"}
* "checkpoint": "<path>", "speech": "<path>"}
* "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
Expand All @@ -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. */
Expand Down
2 changes: 1 addition & 1 deletion src/capi/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/capi/json_io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string>(json, "language", "auto");
options.diarize = Get<bool>(json, "diarize", false);
options.glossary = Get<std::vector<std::string>>(json, "glossary", {});
job.even_loudness = Get<bool>(json, "even_loudness", true);
job.checkpoint = PathFromUtf8(Get<std::string>(json, "checkpoint", ""));
job.speech = PathFromUtf8(Get<std::string>(json, "speech", ""));
return job;
}

Expand Down
1 change: 1 addition & 0 deletions src/capi/json_io.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 7 additions & 1 deletion src/capi/sillok.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<sillok::EngineState> 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;
Expand Down Expand Up @@ -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<sillok::SpeechFile> 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) {
Expand All @@ -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;
Expand Down
70 changes: 70 additions & 0 deletions src/capi/speech_file.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include "capi/speech_file.hpp"

#include <bit>
#include <cstring>
#include <exception>
#include <fstream>
#include <sstream>
#include <system_error>
#include <utility>

#include <nlohmann/json.hpp>

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<DetectedSpeech> 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<std::string>();
} 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<std::streamsize>(line.size()));
out.write(reinterpret_cast<const char*>(speech.probabilities.data()),
static_cast<std::streamsize>(speech.probabilities.size() * sizeof(float)));
out.flush();
if (out) return;
}
std::error_code ignored;
std::filesystem::remove(path_, ignored);
}

} // namespace sillok
33 changes: 33 additions & 0 deletions src/capi/speech_file.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#ifndef SILLOK_CAPI_SPEECH_FILE_HPP_
#define SILLOK_CAPI_SPEECH_FILE_HPP_

#include <filesystem>
#include <optional>
#include <string>

#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<DetectedSpeech> Load() override;
void Save(const DetectedSpeech& speech) override;

private:
std::filesystem::path path_;
std::string library_;
};

} // namespace sillok

#endif // SILLOK_CAPI_SPEECH_FILE_HPP_
Loading
Loading