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: 3 additions & 4 deletions apps/mac/Packages/SillokKit/Sources/SillokEngine/Job.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,11 @@ public struct TranscriptionResult: Sendable {

public enum Transcription {
public static func copy(
engine: Engine,
input: URL,
output: URL,
events: @escaping @Sendable (TranscriptionEvent) -> Void
) async throws {
let job = try Job(engine: engine, request: Job.Request())
let job = try Job(engine: nil, request: Job.Request())
try await job.perform { try job.copy(input: input, output: output, events: events) }
}

Expand Down Expand Up @@ -69,9 +68,9 @@ final class Job: @unchecked Sendable {

private let handle: OpaquePointer

init(engine: Engine, request: Request) throws {
init(engine: Engine?, request: Request) throws {
var job: OpaquePointer?
try check(sillok_job_create(engine.handle, try encodeJSON(request), &job))
try check(sillok_job_create(engine?.handle, try encodeJSON(request), &job))
guard let job else { throw SillokError(code: .internalError, message: "no job") }
handle = job
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,38 @@ import Testing
#expect(previews.pieces.allSatisfy { !$0.draft })
}

let tone = URL(filePath: #filePath).appending(path: "../../../../../../../tests/data/media/tone.flac").standardized

func temporaryCopy() -> URL {
FileManager.default.temporaryDirectory.appending(path: "sillok-\(UUID().uuidString).m4a")
}

@Test func copiesARecordingWithoutModels() async throws {
let copy = temporaryCopy()
defer { try? FileManager.default.removeItem(at: copy) }
let events = Mutex<[TranscriptionEvent]>([])
try await Transcription.copy(input: tone, output: copy) { event in events.withLock { $0.append(event) } }
#expect(FileManager.default.fileExists(atPath: copy.path()))
#expect(events.withLock { $0.contains(.reading(1)) && $0.last == .saving(1) })
}

@Test func cancellingStopsTheCopy() async throws {
let copy = temporaryCopy()
let task = Task {
withUnsafeCurrentTask { $0?.cancel() }
try await Transcription.copy(input: tone, output: copy) { _ in }
}
await #expect(throws: CancellationError.self) { try await task.value }
#expect(!FileManager.default.fileExists(atPath: copy.path()))
}

struct RealModels {
static let environment = ProcessInfo.processInfo.environment
static let available = environment["SILLOK_TEST_MODELS"] != nil && environment["SILLOK_TEST_AUDIO"] != nil

let engine: Engine
let audio: URL
let copy = FileManager.default.temporaryDirectory.appending(path: "sillok-\(UUID().uuidString).m4a")
let copy = temporaryCopy()
let checkpoint = FileManager.default.temporaryDirectory.appending(path: "sillok-\(UUID().uuidString).jsonl")

init() throws {
Expand All @@ -64,7 +89,7 @@ struct RealModels {
func transcribesACopyOfARecording() async throws {
let real = try RealModels()
defer { try? FileManager.default.removeItem(at: real.copy) }
try await Transcription.copy(engine: real.engine, input: real.audio, output: real.copy) { _ in }
try await Transcription.copy(input: real.audio, output: real.copy) { _ in }
#expect(FileManager.default.fileExists(atPath: real.copy.path()))

let events = Mutex<[TranscriptionEvent]>([])
Expand All @@ -81,14 +106,3 @@ func transcribesACopyOfARecording() async throws {
#expect(previews)
print("TRANSCRIPT", result.transcript.segments.map { "[\($0.speaker ?? -1)] \($0.text)" })
}

@Test(.enabled(if: RealModels.available))
func cancellingStopsTheCopy() async throws {
let real = try RealModels()
let task = Task {
try await Transcription.copy(engine: real.engine, input: real.audio, output: real.copy) { _ in }
}
task.cancel()
await #expect(throws: CancellationError.self) { try await task.value }
#expect(!FileManager.default.fileExists(atPath: real.copy.path()))
}
7 changes: 1 addition & 6 deletions apps/mac/Sillok/NewJob/JobQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ final class JobQueue {
private(set) var completed: UUID?
private let models: ModelManager
private let library: Library
private var copier: (config: EngineConfig, engine: Engine)?
private var transcriber: (config: EngineConfig, engine: Engine)?
private var adder: Task<Void, Never>?
private var worker: Task<Void, Never>?
Expand Down Expand Up @@ -194,15 +193,11 @@ final class JobQueue {
}
let store = library.store
do {
let config = EngineSettings.config(
modelsDirectory: models.directory, transcriptionModel: models.transcriptionModel?.id ?? item.modelID)
let engine = try cached(&copier, config)
let staging = try store.makeStaging()
do {
try await perform(item.id) { events in
try await Transcription.copy(
engine: engine, input: source, output: staging.appending(path: RecordingStore.audioName),
events: events)
input: source, output: staging.appending(path: RecordingStore.audioName), events: events)
}
var recording = Recording(id: item.id, title: item.title, sourceName: item.sourceName,
options: item.options, transcriptionModel: item.modelID)
Expand Down
5 changes: 4 additions & 1 deletion include/sillok/sillok.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ SILLOK_API void sillok_engine_destroy(sillok_engine* engine);
* 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. */
* A file 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. */
SILLOK_API sillok_status sillok_job_create(sillok_engine* engine,
const char* options_json,
sillok_job** out_job);
Expand Down
19 changes: 11 additions & 8 deletions src/capi/sillok.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -354,16 +354,18 @@ void sillok_engine_destroy(sillok_engine* engine) { delete engine; }
sillok_status sillok_job_create(sillok_engine* engine, const char* options_json,
sillok_job** out_job) {
return Guard([&] {
RequireArgument(engine != nullptr && out_job != nullptr,
"engine and out_job are required");
RequireArgument(out_job != nullptr, "out_job is required");
*out_job = nullptr;
sillok::JobOptions options = sillok::ParseJobOptions(options_json ? options_json : "");
const std::string& language = options.pipeline.language;
const std::vector<std::string> languages = engine->state->models->Languages();
RequireArgument(language == "auto" ||
std::find(languages.begin(), languages.end(), language) != languages.end(),
"\"language\" must be \"auto\" or a language the transcription model knows");
auto job = std::make_unique<sillok_job>(engine->state, std::move(options));
if (engine != nullptr) {
const std::string& language = options.pipeline.language;
const std::vector<std::string> languages = engine->state->models->Languages();
RequireArgument(language == "auto" ||
std::find(languages.begin(), languages.end(), language) != languages.end(),
"\"language\" must be \"auto\" or a language the transcription model knows");
}
auto job = std::make_unique<sillok_job>(engine != nullptr ? engine->state : nullptr,
std::move(options));
*out_job = job.release();
return SILLOK_OK;
});
Expand Down Expand Up @@ -446,6 +448,7 @@ sillok_status sillok_job_run(sillok_job* job, sillok_progress_fn progress,
"job and out_json are required");
*out_json = nullptr;
RequireArgument(!job->ran, "a job runs only once");
RequireArgument(job->engine != nullptr, "a job without an engine cannot run");
bool idle = false;
if (!job->engine->busy.compare_exchange_strong(idle, true)) {
return sillok::Fail(SILLOK_BUSY, "the engine is running another job");
Expand Down
18 changes: 17 additions & 1 deletion tests/unit/capi_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ TEST_F(CapiTest, RejectsBadInput) {
sillok_job* job = nullptr;
EXPECT_EQ(sillok_job_create(Engine(), R"({"language": "fr"})", &job),
SILLOK_INVALID_ARGUMENT);
EXPECT_EQ(sillok_job_create(nullptr, nullptr, &job), SILLOK_INVALID_ARGUMENT);
EXPECT_EQ(sillok_job_create(Engine(), nullptr, nullptr), SILLOK_INVALID_ARGUMENT);
}

TEST_F(CapiTest, JobRunsOnceAndTakesNoAudioAfterwards) {
Expand Down Expand Up @@ -560,6 +560,22 @@ TEST_F(CapiTest, SavesTheRecordingForListeningBack) {
SILLOK_MEDIA_ERROR);
}

TEST_F(CapiTest, SavesTheRecordingWithoutAnEngine) {
sillok_job* job = Job(nullptr, R"({"language": "xx"})");
ASSERT_EQ(sillok_job_push_file(job, PathToUtf8(MediaFile("tone.flac")).c_str(), nullptr,
nullptr),
SILLOK_OK)
<< sillok_last_error();
ASSERT_EQ(sillok_job_end_audio(job), SILLOK_OK);
const auto copy = models_dir_ / "copy.m4a";
ASSERT_EQ(sillok_job_save_audio(job, PathToUtf8(copy).c_str(), nullptr, nullptr), SILLOK_OK)
<< sillok_last_error();
EXPECT_TRUE(std::filesystem::exists(copy));
char* out = nullptr;
EXPECT_EQ(sillok_job_run(job, nullptr, nullptr, &out), SILLOK_INVALID_ARGUMENT);
EXPECT_EQ(out, nullptr);
}

TEST_F(CapiTest, CancelStopsReadingAFile) {
sillok_job* job = Job(Engine());
sillok_job_cancel(job);
Expand Down
Loading