Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

5.5 KB
Raw Blame
// parakeet-server: Parakeet TDT through whisper.cpp's own parakeet.h, kept loaded, behind the same small HTTP surface
// Yogurt uses on whisper-server (GET / answers when the model is in, POST /inference takes a 16 kHz WAV as "file").
// Built by scripts/native.sh and scripts/whisper-build.mjs inside the pinned whisper.cpp, as examples/parakeet-server.
//
//   parakeet-server -m MODEL --host 127.0.0.1 --port N -t THREADS [-ng]
//
// The answer is the model's tokens with their times and log-probabilities, as JSON:
//   {"duration": seconds, "text": "...", "tokens": [{"text": "▁Hello", "start": 0.08, "end": 0.24, "logprob": -0.01}, ...]}
// Words, sentences and the "is this a language Parakeet doesn't know" check are made from them in src/main/asr/parakeet.ts.
#include "common.h"
#include "common-whisper.h"
#include "parakeet.h"
#include "ggml-backend.h"
#include "../server/httplib.h"
#include "json.hpp"

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <mutex>
#include <string>
#include <vector>

using json = nlohmann::ordered_json;

int main(int argc, char ** argv) {
    std::string model, host = "127.0.0.1";
    int port = 8080, threads = 4;
    bool gpu = true;
    for (int i = 1; i < argc; i++) {
        const std::string a = argv[i];
        const bool more = i + 1 < argc;
        if ((a == "-m" || a == "--model") && more) model = argv[++i];
        else if (a == "--host" && more) host = argv[++i];
        else if (a == "--port" && more) port = std::atoi(argv[++i]);
        else if ((a == "-t" || a == "--threads") && more) threads = std::atoi(argv[++i]);
        else if (a == "-ng" || a == "--no-gpu") gpu = false;
        else if (a == "-h" || a == "--help") { ggml_backend_load_all(); fprintf(stderr, "usage: %s -m MODEL [--host H] [--port N] [-t THREADS] [-ng]\n", argv[0]); return 0; }
        else { fprintf(stderr, "unknown argument: %s\n", a.c_str()); return 2; }
    }
    if (model.empty()) { fprintf(stderr, "a model is needed (-m)\n"); return 2; }
    if (threads < 1) threads = 1;

    ggml_backend_load_all();

    struct parakeet_context_params cp = parakeet_context_default_params();
    cp.use_gpu = gpu;
    struct parakeet_context * ctx = parakeet_init_from_file_with_params(model.c_str(), cp);
    if (!ctx) { fprintf(stderr, "parakeet-server: could not load the model '%s'\n", model.c_str()); return 1; }

    std::mutex busy;
    httplib::Server svr;
    svr.set_default_headers({{"Server", "parakeet-server"}});

    svr.Get("/", [](const httplib::Request &, httplib::Response & res) { res.set_content("ok", "text/plain"); });

    svr.Post("/inference", [&](const httplib::Request & req, httplib::Response & res) {
        if (!req.has_file("file")) { res.status = 400; res.set_content("{\"error\":\"no 'file' field in the request\"}", "application/json"); return; }
        const auto file = req.get_file_value("file");
        std::vector<float> pcm;
        std::vector<std::vector<float>> pcms;
        if (!read_audio_data(file.content.data(), file.content.size(), pcm, pcms, false)) {
            res.status = 400; res.set_content("{\"error\":\"failed to read audio data\"}", "application/json"); return;
        }
        json out;
        out["duration"] = pcm.size() / (double) PARAKEET_SAMPLE_RATE;
        std::string text;
        json tokens = json::array();
        // under a tenth of a second there is nothing to read (and nothing for the mel spectrogram to work on)
        if (pcm.size() >= PARAKEET_SAMPLE_RATE / 10) {
            std::lock_guard<std::mutex> lock(busy);
            struct parakeet_full_params fp = parakeet_full_default_params(PARAKEET_SAMPLING_GREEDY);
            fp.n_threads = threads;
            fp.no_context = true;
            const int ret = parakeet_full(ctx, fp, pcm.data(), (int) pcm.size());
            if (ret != 0) {
                res.status = 500; res.set_content("{\"error\":\"failed to process audio\"}", "application/json"); return;
            }
            for (int i = 0; i < parakeet_full_n_segments(ctx); i++) {
                text += parakeet_full_get_segment_text(ctx, i);
                for (int j = 0; j < parakeet_full_n_tokens(ctx, i); j++) {
                    const parakeet_token_data d = parakeet_full_get_token_data(ctx, i, j);
                    const char * s = parakeet_token_to_str(ctx, d.id);
                    // times are in mel frames (10 ms)
                    tokens.push_back({{"text", s ? s : ""}, {"start", d.t0 / 100.0}, {"end", d.t1 / 100.0}, {"logprob", std::log(std::max(d.p, 1e-9f))}});
                }
            }
        }
        out["text"] = text;
        out["tokens"] = tokens;
        res.set_content(out.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
    });

    svr.set_exception_handler([](const httplib::Request &, httplib::Response & res, std::exception_ptr ep) {
        std::string what = "unknown";
        try { std::rethrow_exception(ep); } catch (const std::exception & e) { what = e.what(); } catch (...) {}
        res.status = 500;
        res.set_content(json{{"error", what}}.dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
    });
    svr.set_read_timeout(600);
    svr.set_write_timeout(600);

    if (!svr.bind_to_port(host, port)) { fprintf(stderr, "parakeet-server: couldn't bind to %s:%d\n", host.c_str(), port); parakeet_free(ctx); return 1; }
    fprintf(stderr, "parakeet-server: listening at http://%s:%d with %d threads\n", host.c_str(), port, threads);
    svr.listen_after_bind();
    parakeet_free(ctx);
    return 0;
}