- overlay.zig: frameless translucent panel (fixed bg + rounded corners, only bubbles scroll), drag handle, hover-to-full-opacity, top-right spawn - chat layout: per-message QLabel bubbles (user purple / agent green / tool steps grey mono), transcript retained across turns, End-conversation resets - agent reply streams into its own growing bubble (re-render per chunk) - basic markdown in all messages: **bold**, *italic*, `code`, HTML-escaped - tool steps truncated to 90 chars, click to expand/collapse - polite autoscroll: pins to bottom unless user scrolled up - letta.zig: streamInfer() — --output-format stream-json, per-event callback (tool calls, returns, reply chunks), full reply still returned for TTS - whisper: --language auto (no more hardcoded English) - fix: stderr_log leak crashing Quit via debug allocator 👾 Generated with [Letta Code](https://letta.com) Co-Authored-By: Letta Code <noreply@letta.com>
179 lines
6.6 KiB
Zig
179 lines
6.6 KiB
Zig
//! whisper-server lifecycle + HTTP client.
|
|
//!
|
|
//! inferon owns the whisper-server process: spawns it on startup, kills it on
|
|
//! exit. Model load takes a few seconds; `waitReady` polls until the server
|
|
//! answers. Transcription is a multipart POST over a raw localhost socket.
|
|
|
|
const std = @import("std");
|
|
const Io = std.Io;
|
|
|
|
// ------------------------------------------------------------- constants ---
|
|
|
|
pub const WHISPER_BIN = "/home/pierre/Projects/whisper.cpp/build/bin/whisper-server";
|
|
pub const WHISPER_MODEL = "/home/pierre/Projects/whisper.cpp/models/ggml-large-v3-turbo-q5_0.bin";
|
|
pub const WHISPER_PORT: u16 = 50153;
|
|
const HOST_IP4 = Io.net.Ip4Address.loopback(WHISPER_PORT);
|
|
pub const READY_TIMEOUT_S: u64 = 120; // large-v3-turbo q5_0 load can be slow
|
|
const READY_POLL_INTERVAL_MS: u64 = 500;
|
|
|
|
// -------------------------------------------------------------- process ---
|
|
|
|
var child: ?std.process.Child = null;
|
|
var io_ctx: ?Io = null;
|
|
|
|
/// Spawn whisper-server as a child. stderr -> <log_dir>/whisper-server.log
|
|
pub fn start(alloc: std.mem.Allocator, io: Io, log_dir: []const u8) !void {
|
|
io_ctx = io;
|
|
|
|
const log_path = try std.fmt.allocPrint(alloc, "{s}/whisper-server.log", .{log_dir});
|
|
defer alloc.free(log_path);
|
|
const port_str = try std.fmt.allocPrint(alloc, "{d}", .{WHISPER_PORT});
|
|
defer alloc.free(port_str);
|
|
|
|
const stderr_file: Io.File = Io.Dir.createFileAbsolute(io, log_path, .{ .truncate = true }) catch |e| {
|
|
std.debug.print("inferon/whisper: cannot open log {s}: {s}\n", .{ log_path, @errorName(e) });
|
|
return e;
|
|
};
|
|
|
|
child = try std.process.spawn(io, .{
|
|
.argv = &.{
|
|
WHISPER_BIN,
|
|
"-m",
|
|
WHISPER_MODEL,
|
|
"--port",
|
|
port_str,
|
|
"--convert",
|
|
"--language", "auto",
|
|
},
|
|
.stdin = .ignore,
|
|
.stdout = .ignore,
|
|
.stderr = .{ .file = stderr_file },
|
|
});
|
|
|
|
if (child) |*c| std.debug.print("inferon/whisper: spawned pid {?d}\n", .{c.id});
|
|
}
|
|
|
|
/// PID of the whisper-server child, or null. For signal handlers that must
|
|
/// only use async-signal-safe calls.
|
|
pub fn pid() ?std.process.Child.Id {
|
|
return if (child) |c| c.id else null;
|
|
}
|
|
|
|
/// Kill the whisper-server child (called on quit paths).
|
|
pub fn stop() void {
|
|
const io = io_ctx orelse return;
|
|
if (child) |*c| {
|
|
c.kill(io); // SIGTERM
|
|
child = null;
|
|
}
|
|
}
|
|
|
|
/// Poll until the HTTP server answers. Model load takes seconds.
|
|
pub fn waitReady(io: Io) bool {
|
|
var waited: u64 = 0;
|
|
while (waited < READY_TIMEOUT_S * 1000) : (waited += READY_POLL_INTERVAL_MS) {
|
|
io.sleep(.{ .nanoseconds = READY_POLL_INTERVAL_MS * std.time.ns_per_ms }, .real) catch {};
|
|
if (probeAlive(io)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
fn probeAlive(io: Io) bool {
|
|
const addr = Io.net.IpAddress{ .ip4 = HOST_IP4 };
|
|
const stream = addr.connect(io, .{ .mode = .stream, .timeout = .none }) catch return false;
|
|
stream.close(io);
|
|
return true;
|
|
}
|
|
|
|
// ----------------------------------------------------------------- http ---
|
|
|
|
const boundary = "inferonboundary7381a5f2";
|
|
|
|
fn buildMultipart(alloc: std.mem.Allocator, wav: []const u8) !std.ArrayList(u8) {
|
|
var body: std.ArrayList(u8) = .empty;
|
|
errdefer body.deinit(alloc);
|
|
try body.print(alloc, "--{s}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"u.wav\"\r\nContent-Type: audio/wav\r\n\r\n", .{boundary});
|
|
try body.appendSlice(alloc, wav);
|
|
try body.print(alloc, "\r\n--{s}\r\nContent-Disposition: form-data; name=\"response_format\"\r\n\r\njson\r\n", .{boundary});
|
|
try body.print(alloc, "--{s}\r\nContent-Disposition: form-data; name=\"temperature\"\r\n\r\n0.0\r\n", .{boundary});
|
|
try body.print(alloc, "--{s}--\r\n", .{boundary});
|
|
return body;
|
|
}
|
|
|
|
/// POST a WAV file to /inference, return the transcript text (allocated).
|
|
/// Caller frees. Minimal HTTP/1.1 over a blocking localhost socket.
|
|
pub fn transcribe(alloc: std.mem.Allocator, io: Io, wav_path: []const u8) ![]u8 {
|
|
var wav_file = try Io.Dir.openFileAbsolute(io, wav_path, .{});
|
|
defer wav_file.close(io);
|
|
const stat = try wav_file.stat(io);
|
|
if (stat.size > 64 * 1024 * 1024) return error.FileTooBig;
|
|
var file_rbuf: [64 * 1024]u8 = undefined;
|
|
var wav_reader = wav_file.reader(io, &file_rbuf);
|
|
const wav = try wav_reader.interface.readAlloc(alloc, @intCast(stat.size));
|
|
defer alloc.free(wav);
|
|
|
|
var body = try buildMultipart(alloc, wav);
|
|
defer body.deinit(alloc);
|
|
|
|
const addr = Io.net.IpAddress{ .ip4 = HOST_IP4 };
|
|
const stream = try addr.connect(io, .{ .mode = .stream, .timeout = .none });
|
|
defer stream.close(io);
|
|
|
|
var wbuf: [4096]u8 = undefined;
|
|
var writer = Io.net.Stream.writer(stream, io, &wbuf);
|
|
try writer.interface.print(
|
|
"POST /inference HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: multipart/form-data; boundary={s}\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n",
|
|
.{ boundary, body.items.len },
|
|
);
|
|
try writer.interface.writeAll(body.items);
|
|
try writer.interface.flush();
|
|
|
|
var rbuf: [8192]u8 = undefined;
|
|
var reader = Io.net.Stream.reader(stream, io, &rbuf);
|
|
|
|
var resp: std.ArrayList(u8) = .empty;
|
|
defer resp.deinit(alloc);
|
|
// Read loop: stream until EOF (Connection: close).
|
|
while (true) {
|
|
var tmp: [8192]u8 = undefined;
|
|
const n = reader.interface.readSliceShort(&tmp) catch break;
|
|
if (n == 0) break;
|
|
try resp.appendSlice(alloc, tmp[0..n]);
|
|
}
|
|
|
|
return parseTranscript(resp.items, alloc);
|
|
}
|
|
|
|
/// Extract "text" field from the JSON response body. Handles both plain and
|
|
/// chunked responses by simply scanning for the key.
|
|
fn parseTranscript(raw: []const u8, alloc: std.mem.Allocator) ![]u8 {
|
|
const body_start = std.mem.indexOf(u8, raw, "\r\n\r\n") orelse return error.BadResponse;
|
|
const json_part = raw[body_start + 4 ..];
|
|
|
|
const key = "\"text\"";
|
|
const idx = std.mem.indexOf(u8, json_part, key) orelse return error.BadResponse;
|
|
var it = json_part[idx + key.len ..];
|
|
while (it.len > 0 and it[0] != '"') it = it[1..];
|
|
if (it.len == 0) return error.BadResponse;
|
|
it = it[1..]; // skip opening quote
|
|
|
|
var out: std.ArrayList(u8) = .empty;
|
|
errdefer out.deinit(alloc);
|
|
while (it.len > 0 and it[0] != '"') {
|
|
if (it[0] == '\\' and it.len > 1) {
|
|
const esc: u8 = switch (it[1]) {
|
|
'n' => '\n',
|
|
't' => '\t',
|
|
'"', '\\' => it[1],
|
|
else => it[1],
|
|
};
|
|
try out.append(alloc, esc);
|
|
it = it[2..];
|
|
} else {
|
|
try out.append(alloc, it[0]);
|
|
it = it[1..];
|
|
}
|
|
}
|
|
return out.toOwnedSlice(alloc);
|
|
}
|