|
| 1 | +#include <whisper.h> |
| 2 | +#include "inference_handler.h" |
| 3 | +#include "common.h" |
| 4 | +#include "whisper_params.h" |
| 5 | +#include "json.hpp" |
| 6 | + |
| 7 | +using json = nlohmann::json; |
| 8 | + |
| 9 | +struct whisper_print_user_data { |
| 10 | + const whisper_params *params; |
| 11 | + |
| 12 | + const std::vector<std::vector<float>> *pcmf32s; |
| 13 | + int progress_prev; |
| 14 | +}; |
| 15 | + |
| 16 | + |
| 17 | +// Terminal color map. 10 colors grouped in ranges [0.0, 0.1, ..., 0.9] |
| 18 | +// Lowest is red, middle is yellow, highest is green. |
| 19 | +const std::vector<std::string> k_colors = { |
| 20 | + "\033[38;5;196m", "\033[38;5;202m", "\033[38;5;208m", "\033[38;5;214m", "\033[38;5;220m", |
| 21 | + "\033[38;5;226m", "\033[38;5;190m", "\033[38;5;154m", "\033[38;5;118m", "\033[38;5;82m", |
| 22 | +}; |
| 23 | + |
| 24 | + |
| 25 | +// 500 -> 00:05.000 |
| 26 | +// 6000 -> 01:00.000 |
| 27 | +std::string to_timestamp(int64_t t, bool comma = false) { |
| 28 | + int64_t msec = t * 10; |
| 29 | + int64_t hr = msec / (1000 * 60 * 60); |
| 30 | + msec = msec - hr * (1000 * 60 * 60); |
| 31 | + int64_t min = msec / (1000 * 60); |
| 32 | + msec = msec - min * (1000 * 60); |
| 33 | + int64_t sec = msec / 1000; |
| 34 | + msec = msec - sec * 1000; |
| 35 | + |
| 36 | + char buf[32]; |
| 37 | + snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int) hr, (int) min, (int) sec, comma ? "," : ".", (int) msec); |
| 38 | + |
| 39 | + return std::string(buf); |
| 40 | +} |
| 41 | + |
| 42 | +int timestamp_to_sample(int64_t t, int n_samples) { |
| 43 | + return std::max(0, std::min((int) n_samples - 1, (int) ((t * WHISPER_SAMPLE_RATE) / 100))); |
| 44 | +} |
| 45 | + |
| 46 | +std::string |
| 47 | +estimate_diarization_speaker(std::vector<std::vector<float>> pcmf32s, int64_t t0, int64_t t1, bool id_only = false) { |
| 48 | + std::string speaker = ""; |
| 49 | + const int64_t n_samples = pcmf32s[0].size(); |
| 50 | + |
| 51 | + const int64_t is0 = timestamp_to_sample(t0, n_samples); |
| 52 | + const int64_t is1 = timestamp_to_sample(t1, n_samples); |
| 53 | + |
| 54 | + double energy0 = 0.0f; |
| 55 | + double energy1 = 0.0f; |
| 56 | + |
| 57 | + for (int64_t j = is0; j < is1; j++) { |
| 58 | + energy0 += fabs(pcmf32s[0][j]); |
| 59 | + energy1 += fabs(pcmf32s[1][j]); |
| 60 | + } |
| 61 | + |
| 62 | + if (energy0 > 1.1 * energy1) { |
| 63 | + speaker = "0"; |
| 64 | + } else if (energy1 > 1.1 * energy0) { |
| 65 | + speaker = "1"; |
| 66 | + } else { |
| 67 | + speaker = "?"; |
| 68 | + } |
| 69 | + |
| 70 | + //printf("is0 = %lld, is1 = %lld, energy0 = %f, energy1 = %f, speaker = %s\n", is0, is1, energy0, energy1, speaker.c_str()); |
| 71 | + |
| 72 | + if (!id_only) { |
| 73 | + speaker.insert(0, "(speaker "); |
| 74 | + speaker.append(")"); |
| 75 | + } |
| 76 | + |
| 77 | + return speaker; |
| 78 | +} |
| 79 | + |
| 80 | + |
| 81 | +void whisper_print_segment_callback(struct whisper_context *ctx, struct whisper_state * /*state*/, int n_new, |
| 82 | + void *user_data) { |
| 83 | + const auto ¶ms = *((whisper_print_user_data *) user_data)->params; |
| 84 | + const auto &pcmf32s = *((whisper_print_user_data *) user_data)->pcmf32s; |
| 85 | + |
| 86 | + const int n_segments = whisper_full_n_segments(ctx); |
| 87 | + |
| 88 | + std::string speaker = ""; |
| 89 | + |
| 90 | + int64_t t0 = 0; |
| 91 | + int64_t t1 = 0; |
| 92 | + |
| 93 | + // print the last n_new segments |
| 94 | + const int s0 = n_segments - n_new; |
| 95 | + |
| 96 | + if (s0 == 0) { |
| 97 | + printf("\n"); |
| 98 | + } |
| 99 | + |
| 100 | + for (int i = s0; i < n_segments; i++) { |
| 101 | + if (!params.no_timestamps || params.diarize) { |
| 102 | + t0 = whisper_full_get_segment_t0(ctx, i); |
| 103 | + t1 = whisper_full_get_segment_t1(ctx, i); |
| 104 | + } |
| 105 | + |
| 106 | + if (!params.no_timestamps) { |
| 107 | + printf("[%s --> %s] ", to_timestamp(t0).c_str(), to_timestamp(t1).c_str()); |
| 108 | + } |
| 109 | + |
| 110 | + if (params.diarize && pcmf32s.size() == 2) { |
| 111 | + speaker = estimate_diarization_speaker(pcmf32s, t0, t1); |
| 112 | + } |
| 113 | + |
| 114 | + if (params.print_colors) { |
| 115 | + for (int j = 0; j < whisper_full_n_tokens(ctx, i); ++j) { |
| 116 | + if (params.print_special == false) { |
| 117 | + const whisper_token id = whisper_full_get_token_id(ctx, i, j); |
| 118 | + if (id >= whisper_token_eot(ctx)) { |
| 119 | + continue; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + const char *text = whisper_full_get_token_text(ctx, i, j); |
| 124 | + const float p = whisper_full_get_token_p(ctx, i, j); |
| 125 | + |
| 126 | + const int col = std::max(0, std::min((int) k_colors.size() - 1, |
| 127 | + (int) (std::pow(p, 3) * float(k_colors.size())))); |
| 128 | + |
| 129 | + printf("%s%s%s%s", speaker.c_str(), k_colors[col].c_str(), text, "\033[0m"); |
| 130 | + } |
| 131 | + } else { |
| 132 | + const char *text = whisper_full_get_segment_text(ctx, i); |
| 133 | + |
| 134 | + printf("%s%s", speaker.c_str(), text); |
| 135 | + } |
| 136 | + |
| 137 | + if (params.tinydiarize) { |
| 138 | + if (whisper_full_get_segment_speaker_turn_next(ctx, i)) { |
| 139 | + printf("%s", params.tdrz_speaker_turn.c_str()); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + // with timestamps or speakers: each segment on new line |
| 144 | + if (!params.no_timestamps || params.diarize) { |
| 145 | + printf("\n"); |
| 146 | + } |
| 147 | + fflush(stdout); |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +std::string |
| 152 | +output_str(struct whisper_context *ctx, const whisper_params ¶ms, std::vector<std::vector<float>> pcmf32s) { |
| 153 | + std::stringstream result; |
| 154 | + const int n_segments = whisper_full_n_segments(ctx); |
| 155 | + for (int i = 0; i < n_segments; ++i) { |
| 156 | + const char *text = whisper_full_get_segment_text(ctx, i); |
| 157 | + std::string speaker = ""; |
| 158 | + |
| 159 | + if (params.diarize && pcmf32s.size() == 2) { |
| 160 | + const int64_t t0 = whisper_full_get_segment_t0(ctx, i); |
| 161 | + const int64_t t1 = whisper_full_get_segment_t1(ctx, i); |
| 162 | + speaker = estimate_diarization_speaker(pcmf32s, t0, t1); |
| 163 | + } |
| 164 | + |
| 165 | + result << speaker << text << "\n"; |
| 166 | + } |
| 167 | + return result.str(); |
| 168 | +} |
| 169 | + |
| 170 | + |
| 171 | +void whisper_print_progress_callback(struct whisper_context * /*ctx*/, struct whisper_state * /*state*/, int progress, |
| 172 | + void *user_data) { |
| 173 | + int progress_step = ((whisper_print_user_data *) user_data)->params->progress_step; |
| 174 | + int *progress_prev = &(((whisper_print_user_data *) user_data)->progress_prev); |
| 175 | + if (progress >= *progress_prev + progress_step) { |
| 176 | + *progress_prev += progress_step; |
| 177 | + fprintf(stderr, "%s: progress = %3d%%\n", __func__, progress); |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +void getReqParameters(const Request &req, whisper_params ¶ms) { |
| 182 | +// user model configu.has_fileion |
| 183 | + if (req.has_file("offset-t")) { |
| 184 | + params.offset_t_ms = std::stoi(req.get_file_value("offset-t").content); |
| 185 | + } |
| 186 | + if (req.has_file("offset-n")) { |
| 187 | + params.offset_n = std::stoi(req.get_file_value("offset-n").content); |
| 188 | + } |
| 189 | + if (req.has_file("duration")) { |
| 190 | + params.duration_ms = std::stoi(req.get_file_value("duration").content); |
| 191 | + } |
| 192 | + if (req.has_file("max-context")) { |
| 193 | + params.max_context = std::stoi(req.get_file_value("max-context").content); |
| 194 | + } |
| 195 | + if (req.has_file("prompt")) { |
| 196 | + params.prompt = req.get_file_value("prompt").content; |
| 197 | + } |
| 198 | + if (req.has_file("response-format")) { |
| 199 | + params.response_format = req.get_file_value("response-format").content; |
| 200 | + } |
| 201 | + if (req.has_file("temerature")) { |
| 202 | + params.userdef_temp = std::stof(req.get_file_value("temperature").content); |
| 203 | + } |
| 204 | +} |
| 205 | + |
| 206 | + |
| 207 | +void getReqParameters(const Request &request, whisper_params ¶ms); |
| 208 | + |
| 209 | +void handleInference(const Request &req, Response &res, std::mutex &whisper_mutex, whisper_params ¶ms, |
| 210 | + whisper_context *ctx, char *arg_audio_file) { |
| 211 | +// aquire whisper model mutex lock |
| 212 | + whisper_mutex.lock(); |
| 213 | + |
| 214 | + // first check user requested fields of the request |
| 215 | + if (!req.has_file("file")) { |
| 216 | + fprintf(stderr, "error: no 'file' field in the request\n"); |
| 217 | + const std::string error_resp = "{\"error\":\"no 'file' field in the request\"}"; |
| 218 | + res.set_content(error_resp, "application/json"); |
| 219 | + whisper_mutex.unlock(); |
| 220 | + return; |
| 221 | + } |
| 222 | + auto audio_file = req.get_file_value("file"); |
| 223 | + |
| 224 | + // check non-required fields |
| 225 | + getReqParameters(req, params); |
| 226 | + |
| 227 | + std::string filename{audio_file.filename}; |
| 228 | + printf("Received request: %s\n", filename.c_str()); |
| 229 | + |
| 230 | + // audio arrays |
| 231 | + std::vector<float> pcmf32; // mono-channel F32 PCM |
| 232 | + std::vector<std::vector<float>> pcmf32s; // stereo-channel F32 PCM |
| 233 | + |
| 234 | + // write file to temporary file |
| 235 | + std::ofstream temp_file{filename, std::ios::binary}; |
| 236 | + temp_file << audio_file.content; |
| 237 | + |
| 238 | + // read wav content into pcmf32 |
| 239 | + if (!::read_wav(filename, pcmf32, pcmf32s, params.diarize)) { |
| 240 | + fprintf(stderr, "error: failed to read WAV file '%s'\n", filename.c_str()); |
| 241 | + const std::string error_resp = "{\"error\":\"failed to read WAV file\"}"; |
| 242 | + res.set_content(error_resp, "application/json"); |
| 243 | + whisper_mutex.unlock(); |
| 244 | + return; |
| 245 | + } |
| 246 | + // remove temp file |
| 247 | + std::remove(filename.c_str()); |
| 248 | + |
| 249 | + printf("Successfully loaded %s\n", filename.c_str()); |
| 250 | + |
| 251 | + // print system information |
| 252 | + { |
| 253 | + fprintf(stderr, "\n"); |
| 254 | + fprintf(stderr, "system_info: n_threads = %d / %d | %s\n", |
| 255 | + params.n_threads * params.n_processors, std::thread::hardware_concurrency(), whisper_print_system_info()); |
| 256 | + } |
| 257 | + |
| 258 | + // print some info about the processing |
| 259 | + { |
| 260 | + fprintf(stderr, "\n"); |
| 261 | + if (!whisper_is_multilingual(ctx)) { |
| 262 | + if (params.language != "en" || params.translate) { |
| 263 | + params.language = "en"; |
| 264 | + params.translate = false; |
| 265 | + fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", |
| 266 | + __func__); |
| 267 | + } |
| 268 | + } |
| 269 | + if (params.detect_language) { |
| 270 | + params.language = "auto"; |
| 271 | + } |
| 272 | + fprintf(stderr, |
| 273 | + "%s: processing '%s' (%d samples, %.1f sec), %d threads, %d processors, lang = %s, task = %s, %stimestamps = %d ...\n", |
| 274 | + __func__, filename.c_str(), int(pcmf32.size()), float(pcmf32.size()) / WHISPER_SAMPLE_RATE, |
| 275 | + params.n_threads, params.n_processors, |
| 276 | + params.language.c_str(), |
| 277 | + params.translate ? "translate" : "transcribe", |
| 278 | + params.tinydiarize ? "tdrz = 1, " : "", |
| 279 | + params.no_timestamps ? 0 : 1); |
| 280 | + |
| 281 | + fprintf(stderr, "\n"); |
| 282 | + } |
| 283 | + |
| 284 | + // run the inference |
| 285 | + { |
| 286 | + |
| 287 | + printf("Running whisper.cpp inference on %s\n", filename.c_str()); |
| 288 | + whisper_full_params wparams = whisper_full_default_params(WHISPER_SAMPLING_GREEDY); |
| 289 | + |
| 290 | + wparams.strategy = params.beam_size > 1 ? WHISPER_SAMPLING_BEAM_SEARCH : WHISPER_SAMPLING_GREEDY; |
| 291 | + |
| 292 | + wparams.print_realtime = false; |
| 293 | + wparams.print_progress = params.print_progress; |
| 294 | + wparams.print_timestamps = !params.no_timestamps; |
| 295 | + wparams.print_special = params.print_special; |
| 296 | + wparams.translate = params.translate; |
| 297 | + wparams.language = params.language.c_str(); |
| 298 | + wparams.detect_language = params.detect_language; |
| 299 | + wparams.n_threads = params.n_threads; |
| 300 | + wparams.n_max_text_ctx = params.max_context >= 0 ? params.max_context : wparams.n_max_text_ctx; |
| 301 | + wparams.offset_ms = params.offset_t_ms; |
| 302 | + wparams.duration_ms = params.duration_ms; |
| 303 | + |
| 304 | + wparams.thold_pt = params.word_thold; |
| 305 | + wparams.split_on_word = params.split_on_word; |
| 306 | + |
| 307 | + wparams.speed_up = params.speed_up; |
| 308 | + wparams.debug_mode = params.debug_mode; |
| 309 | + |
| 310 | + wparams.tdrz_enable = params.tinydiarize; // [TDRZ] |
| 311 | + |
| 312 | + wparams.initial_prompt = params.prompt.c_str(); |
| 313 | + |
| 314 | + wparams.greedy.best_of = params.best_of; |
| 315 | + wparams.beam_search.beam_size = params.beam_size; |
| 316 | + |
| 317 | + wparams.temperature_inc = params.userdef_temp; |
| 318 | + wparams.entropy_thold = params.entropy_thold; |
| 319 | + wparams.logprob_thold = params.logprob_thold; |
| 320 | + |
| 321 | + whisper_print_user_data user_data = {¶ms, &pcmf32s, 0}; |
| 322 | + |
| 323 | + // this callback is called on each new segment |
| 324 | + if (!wparams.print_realtime) { |
| 325 | + wparams.new_segment_callback = whisper_print_segment_callback; |
| 326 | + wparams.new_segment_callback_user_data = &user_data; |
| 327 | + } |
| 328 | + |
| 329 | + if (wparams.print_progress) { |
| 330 | + wparams.progress_callback = whisper_print_progress_callback; |
| 331 | + wparams.progress_callback_user_data = &user_data; |
| 332 | + } |
| 333 | + |
| 334 | + // examples for abort mechanism |
| 335 | + // in examples below, we do not abort the processing, but we could if the flag is set to true |
| 336 | + |
| 337 | + // the callback is called before every encoder run - if it returns false, the processing is aborted |
| 338 | + { |
| 339 | + static bool is_aborted = false; // NOTE: this should be atomic to avoid data race |
| 340 | + |
| 341 | + wparams.encoder_begin_callback = [](struct whisper_context * /*ctx*/, struct whisper_state * /*state*/, |
| 342 | + void *user_data) { |
| 343 | + bool is_aborted = *(bool *) user_data; |
| 344 | + return !is_aborted; |
| 345 | + }; |
| 346 | + wparams.encoder_begin_callback_user_data = &is_aborted; |
| 347 | + } |
| 348 | + |
| 349 | + // the callback is called before every computation - if it returns true, the computation is aborted |
| 350 | + { |
| 351 | + static bool is_aborted = false; // NOTE: this should be atomic to avoid data race |
| 352 | + |
| 353 | + wparams.abort_callback = [](void *user_data) { |
| 354 | + bool is_aborted = *(bool *) user_data; |
| 355 | + return is_aborted; |
| 356 | + }; |
| 357 | + wparams.abort_callback_user_data = &is_aborted; |
| 358 | + } |
| 359 | + |
| 360 | + if (whisper_full_parallel(ctx, wparams, pcmf32.data(), pcmf32.size(), params.n_processors) != 0) { |
| 361 | + fprintf(stderr, "%s: failed to process audio\n", arg_audio_file); |
| 362 | + const std::string error_resp = "{\"error\":\"failed to process audio\"}"; |
| 363 | + res.set_content(error_resp, "application/json"); |
| 364 | + whisper_mutex.unlock(); |
| 365 | + return; |
| 366 | + } |
| 367 | + } |
| 368 | + |
| 369 | + // return results to user |
| 370 | + if (params.response_format == text_format) { |
| 371 | + std::string results = output_str(ctx, params, pcmf32s); |
| 372 | + res.set_content(results.c_str(), "text/html"); |
| 373 | + } |
| 374 | + // TODO add more output formats |
| 375 | + else { |
| 376 | + std::string results = output_str(ctx, params, pcmf32s); |
| 377 | + json jres = json{ |
| 378 | + {"text", results} |
| 379 | + }; |
| 380 | + res.set_content(jres.dump(-1, ' ', false, json::error_handler_t::replace), |
| 381 | + "application/json"); |
| 382 | + } |
| 383 | + |
| 384 | + // return whisper model mutex lock |
| 385 | + whisper_mutex.unlock(); |
| 386 | +} |
| 387 | + |
0 commit comments