Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AppleSpeech.test.ts

178 lines6.7 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11​
12import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
13import * as AppleSpeech from "./AppleSpeech.ts";
14​
15const encoder = new TextEncoder();
16const text = (value: string) => (value ? Stream.make(encoder.encode(value)) : Stream.empty);
17​
18type HelperOutput = {
19 stdout?: string;
20 stderr?: string;
21 exitCode: number;
22 exit?: Deferred.Deferred<void>;
23};
24​
25function makeProcess(result: HelperOutput) {
26 const exitCode = (result.exit ? Deferred.await(result.exit) : Effect.void).pipe(
27 Effect.as(ChildProcessSpawner.ExitCode(result.exitCode)),
28 );
29 return ChildProcessSpawner.makeHandle({
30 pid: ChildProcessSpawner.ProcessId(1),
31 stdout: text(result.stdout ?? ""),
32 stderr: text(result.stderr ?? ""),
33 all: Stream.empty,
34 exitCode,
35 exitStatus: Effect.map(exitCode, (code) => ({ _tag: "Exited", code })),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 stdin: Sink.drain,
39 getInputFd: () => Sink.drain,
40 getOutputFd: () => Stream.empty,
41 unref: Effect.succeed(Effect.void),
42 });
44​
45function setup(result: HelperOutput, kernelRelease = "25.0.0") {
46 const commands: Array<ReadonlyArray<string>> = [];
47 const written: Uint8Array[] = [];
48 const layer = AppleSpeech.layer.pipe(
49 Layer.provide(
50 Layer.mergeAll(
51 Layer.succeed(HostProcess.KernelRelease, kernelRelease),
52 Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
53 platform: "darwin",
54 isPackaged: true,
55 resourcesPath: "/app/Resources",
56 path: { join: (...parts: string[]) => parts.join("/") },
57 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]),
58 FileSystem.layerNoop({
59 exists: () => Effect.succeed(true),
60 makeTempFileScoped: () => Effect.succeed("/tmp/recording.wav"),
61 writeFile: (_path, data) => Effect.sync(() => void written.push(data)),
62 }),
63 Layer.succeed(
64 ChildProcessSpawner.ChildProcessSpawner,
65 ChildProcessSpawner.make((command) => {
66 const { command: executable, args } = command as unknown as {
67 command: string;
68 args: ReadonlyArray<string>;
69 };
70 commands.push([executable, ...args]);
71 return Effect.succeed(makeProcess(result));
72 }),
73 ),
74 ),
75 ),
76 );
77 return { commands, written, layer };
79​
80describe("AppleSpeech", () => {
81 it.effect.each([
82 [
83 { stdout: '{"value":"en-US"}', exitCode: 0 },
84 { ok: true, value: "en-US" },
85 ],
86 [
87 { stderr: "Locale not supported: xx\n", exitCode: 2 },
88 { ok: false, code: "unsupported-locale" },
89 ],
90 [{ exitCode: 3 }, { ok: false, code: "unavailable" }],
91 [
92 { stderr: "boom", exitCode: 1 },
93 { ok: false, code: "failed" },
94 ],
95 ] as const)("maps helper output %j to %j", ([output, expected]) => {
96 const { layer, commands } = setup(output);
97 return Effect.gen(function* () {
98 const speech = yield* AppleSpeech.AppleSpeech;
99 assert.deepEqual(yield* speech.prepare("en-US"), expected);
100 assert.deepEqual(commands, [
101 ["/app/Resources/apple-speech/t3-apple-speech", "prepare", "en-US"],
102 ]);
103 }).pipe(Effect.provide(layer));
104 });
105​
106 it.effect("shares one helper between prepares that start while the first is running", () =>
107 Effect.gen(function* () {
108 const exit = yield* Deferred.make<void>();
109 const { layer, commands } = setup({ stdout: '{"value":"en-US"}', exitCode: 0, exit });
110 return yield* Effect.gen(function* () {
111 const speech = yield* AppleSpeech.AppleSpeech;
112 const first = yield* speech
113 .prepare("en-US")
114 .pipe(Effect.forkChild({ startImmediately: true }));
115 const second = yield* speech
116 .prepare("en-US")
117 .pipe(Effect.forkChild({ startImmediately: true }));
118 yield* Deferred.succeed(exit, undefined);
119 assert.deepEqual(yield* Fiber.join(first), { ok: true, value: "en-US" });
120 assert.deepEqual(yield* Fiber.join(second), { ok: true, value: "en-US" });
121 assert.lengthOf(commands, 1);
122 }).pipe(Effect.provide(layer));
123 }),
124 );
125​
126 it.effect.each([
127 ["25.0.0", 0, ["en-US", "fr-FR"], 1],
128 ["25.0.0", 3, [], 1],
129 ["25.0.0", 1, [], 2],
130 ["24.6.0", 0, [], 0],
131 ] as const)(
132 "on Darwin %s resolves locales on helper exit %i to %j with %i probe(s) across two calls",
133 ([release, exitCode, expected, probes]) => {
134 const { layer, commands } = setup({ stdout: '{"value":"en-US,fr-FR"}', exitCode }, release);
135 return Effect.gen(function* () {
136 const speech = yield* AppleSpeech.AppleSpeech;
137 assert.deepEqual(yield* speech.supportedLocales, expected);
138 assert.deepEqual(yield* speech.supportedLocales, expected);
139 assert.lengthOf(commands, probes);
140 }).pipe(Effect.provide(layer));
141 },
142 );
143​
144 it.effect("transcribes Float32 PCM through a 16-bit WAV file", () => {
145 const { layer, commands, written } = setup({ stdout: '{"value":"hello"}', exitCode: 0 });
146 // An unaligned Buffer view: Buffer.slice and subarray do not copy.
147 const pcm = new Uint8Array(17);
148 new DataView(pcm.buffer).setFloat32(1, 0, true);
149 new DataView(pcm.buffer).setFloat32(5, 1, true);
150 new DataView(pcm.buffer).setFloat32(9, -1, true);
151 new DataView(pcm.buffer).setFloat32(13, 2, true);
152 return Effect.gen(function* () {
153 const result = yield* (yield* AppleSpeech.AppleSpeech).transcribe(
154 "en-US",
155 Buffer.from(pcm.buffer).subarray(1),
156 );
157 assert.deepEqual(result, { ok: true, value: "hello" });
158 assert.deepEqual(commands, [
159 [
160 "/app/Resources/apple-speech/t3-apple-speech",
161 "transcribe",
162 "en-US",
163 "/tmp/recording.wav",
164 ],
165 ]);
166 const wav = new DataView(written[0]!.buffer);
167 assert.equal(new TextDecoder().decode(written[0]!.subarray(0, 4)), "RIFF");
168 assert.equal(wav.getUint16(20, true), 1);
169 assert.equal(wav.getUint32(24, true), 16_000);
170 assert.equal(wav.getUint16(34, true), 16);
171 assert.equal(wav.getUint32(40, true), 8);
172 assert.deepEqual(
173 [0, 1, 2, 3].map((index) => wav.getInt16(44 + index * 2, true)),
174 [0, 32767, -32767, 32767],
175 );
176 }).pipe(Effect.provide(layer));
177 });
178});