yum-archive/TaSTT-Whisper

High-performance GPGPU inference of OpenAI's Whisper automatic speech recognition (ASR) model

git clone https://git.yummers.dev/yum-archive/TaSTT-Whisper

KonstantinSource codes8c4603c

master
13.6 KiB330 linesraw
1#ifndef WHISPER_H
2#define WHISPER_H
3
4#include <stdint.h>
5#include <stdbool.h>
6
7#ifdef WHISPER_SHARED
8#    ifdef _WIN32
9#        ifdef WHISPER_BUILD
10#            define WHISPER_API __declspec(dllexport)
11#        else
12#            define WHISPER_API __declspec(dllimport)
13#        endif
14#    else
15#        define WHISPER_API __attribute__ ((visibility ("default")))
16#    endif
17#else
18#    define WHISPER_API
19#endif
20
21#define WHISPER_SAMPLE_RATE 16000
22#define WHISPER_N_FFT       400
23#define WHISPER_N_MEL       80
24#define WHISPER_HOP_LENGTH  160
25#define WHISPER_CHUNK_SIZE  30
26
27#ifdef __cplusplus
28extern "C" {
29#endif
30
31    //
32    // C interface
33    //
34    // The following interface is thread-safe as long as the sample whisper_context is not used by multiple threads
35    // concurrently.
36    //
37    // Basic usage:
38    //
39    //     #include "whisper.h"
40    //
41    //     ...
42    //
43    //     struct whisper_context * ctx = whisper_init("/path/to/ggml-base.en.bin");
44    //
45    //     if (whisper_full(ctx, wparams, pcmf32.data(), pcmf32.size()) != 0) {
46    //         fprintf(stderr, "failed to process audio\n");
47    //         return 7;
48    //     }
49    //
50    //     const int n_segments = whisper_full_n_segments(ctx);
51    //     for (int i = 0; i < n_segments; ++i) {
52    //         const char * text = whisper_full_get_segment_text(ctx, i);
53    //         printf("%s", text);
54    //     }
55    //
56    //     whisper_free(ctx);
57    //
58    //     ...
59    //
60    // This is a demonstration of the most straightforward usage of the library.
61    // "pcmf32" contains the RAW audio data in 32-bit floating point format.
62    //
63    // The interface also allows for more fine-grained control over the computation, but it requires a deeper
64    // understanding of how the model works.
65    //
66
67    struct whisper_context;
68
69    typedef int whisper_token;
70
71    typedef struct whisper_token_data {
72        whisper_token id;  // token id
73        whisper_token tid; // forced timestamp token id
74
75        float p;           // probability of the token
76        float pt;          // probability of the timestamp token
77        float ptsum;       // sum of probabilities of all timestamp tokens
78
79        // token-level timestamp data
80        // do not use if you haven't computed token-level timestamps
81        int64_t t0;        // start time of the token
82        int64_t t1;        //   end time of the token
83
84        float vlen;        // voice length of the token
85    } whisper_token_data;
86
87    // Allocates all memory needed for the model and loads the model from the given file.
88    // Returns NULL on failure.
89    WHISPER_API struct whisper_context * whisper_init(const char * path_model);
90
91    // Frees all memory allocated by the model.
92    WHISPER_API void whisper_free(struct whisper_context * ctx);
93
94    // Convert RAW PCM audio to log mel spectrogram.
95    // The resulting spectrogram is stored inside the provided whisper context.
96    // Returns 0 on success
97    WHISPER_API int whisper_pcm_to_mel(
98            struct whisper_context * ctx,
99                       const float * samples,
100                               int   n_samples,
101                               int   n_threads);
102
103    // This can be used to set a custom log mel spectrogram inside the provided whisper context.
104    // Use this instead of whisper_pcm_to_mel() if you want to provide your own log mel spectrogram.
105    // n_mel must be 80
106    // Returns 0 on success
107    WHISPER_API int whisper_set_mel(
108            struct whisper_context * ctx,
109                       const float * data,
110                               int   n_len,
111                               int   n_mel);
112
113    // Run the Whisper encoder on the log mel spectrogram stored inside the provided whisper context.
114    // Make sure to call whisper_pcm_to_mel() or whisper_set_mel() first.
115    // offset can be used to specify the offset of the first frame in the spectrogram.
116    // Returns 0 on success
117    WHISPER_API int whisper_encode(
118            struct whisper_context * ctx,
119                               int   offset,
120                               int   n_threads);
121
122    // Run the Whisper decoder to obtain the logits and probabilities for the next token.
123    // Make sure to call whisper_encode() first.
124    // tokens + n_tokens is the provided context for the decoder.
125    // n_past is the number of tokens to use from previous decoder calls.
126    // Returns 0 on success
127    WHISPER_API int whisper_decode(
128            struct whisper_context * ctx,
129               const whisper_token * tokens,
130                               int   n_tokens,
131                               int   n_past,
132                               int   n_threads);
133
134    // Token sampling methods.
135    // These are provided for convenience and can be used after each call to whisper_decode().
136    // You can also implement your own sampling method using the whisper_get_probs() function.
137    // whisper_sample_best() returns the token with the highest probability
138    // whisper_sample_timestamp() returns the most probable timestamp token
139    WHISPER_API whisper_token_data whisper_sample_best(struct whisper_context * ctx);
140    WHISPER_API whisper_token_data whisper_sample_timestamp(struct whisper_context * ctx, bool is_initial);
141
142    // Convert the provided text into tokens.
143    // The tokens pointer must be large enough to hold the resulting tokens.
144    // Returns the number of tokens on success, no more than n_max_tokens
145    // Returns -1 on failure
146    // TODO: not sure if correct
147    WHISPER_API int whisper_tokenize(
148            struct whisper_context * ctx,
149                        const char * text,
150                     whisper_token * tokens,
151	                           int   n_max_tokens);
152
153    // Largest language id (i.e. number of available languages - 1)
154    WHISPER_API int whisper_lang_max_id();
155
156    // Return the id of the specified language, returns -1 if not found
157    // Examples:
158    //   "de" -> 2
159    //   "german" -> 2
160    WHISPER_API int whisper_lang_id(const char * lang);
161
162    // Return the short string of the specified language id (e.g. 2 -> "de"), returns nullptr if not found
163    WHISPER_API const char * whisper_lang_str(int id);
164
165    // Use mel data at offset_ms to try and auto-detect the spoken language
166    // Make sure to call whisper_pcm_to_mel() or whisper_set_mel() first
167    // Returns the top language id or negative on failure
168    // If not null, fills the lang_probs array with the probabilities of all languages
169    // The array must be whispe_lang_max_id() + 1 in size
170    // ref: https://github.com/openai/whisper/blob/main/whisper/decoding.py#L18-L69
171    WHISPER_API int whisper_lang_auto_detect(
172            struct whisper_context * ctx,
173                               int   offset_ms,
174                               int   n_threads,
175                             float * lang_probs);
176
177    WHISPER_API int whisper_n_len          (struct whisper_context * ctx); // mel length
178    WHISPER_API int whisper_n_vocab        (struct whisper_context * ctx);
179    WHISPER_API int whisper_n_text_ctx     (struct whisper_context * ctx);
180    WHISPER_API int whisper_is_multilingual(struct whisper_context * ctx);
181
182    // The probabilities for the next token
183    WHISPER_API float * whisper_get_probs(struct whisper_context * ctx);
184
185    // Token Id -> String. Uses the vocabulary in the provided context
186    WHISPER_API const char * whisper_token_to_str(struct whisper_context * ctx, whisper_token token);
187
188    // Special tokens
189    WHISPER_API whisper_token whisper_token_eot (struct whisper_context * ctx);
190    WHISPER_API whisper_token whisper_token_sot (struct whisper_context * ctx);
191    WHISPER_API whisper_token whisper_token_prev(struct whisper_context * ctx);
192    WHISPER_API whisper_token whisper_token_solm(struct whisper_context * ctx);
193    WHISPER_API whisper_token whisper_token_not (struct whisper_context * ctx);
194    WHISPER_API whisper_token whisper_token_beg (struct whisper_context * ctx);
195    WHISPER_API whisper_token whisper_token_lang(struct whisper_context * ctx, int lang_id);
196
197    // Task tokens
198    WHISPER_API whisper_token whisper_token_translate (void);
199    WHISPER_API whisper_token whisper_token_transcribe(void);
200
201    // Performance information
202    WHISPER_API void whisper_print_timings(struct whisper_context * ctx);
203    WHISPER_API void whisper_reset_timings(struct whisper_context * ctx);
204
205    // Print system information
206    WHISPER_API const char * whisper_print_system_info(void);
207
208    ////////////////////////////////////////////////////////////////////////////
209
210    // Available sampling strategies
211    enum whisper_sampling_strategy {
212        WHISPER_SAMPLING_GREEDY,      // Always select the most probable token
213        WHISPER_SAMPLING_BEAM_SEARCH, // TODO: not implemented yet!
214    };
215
216    // Text segment callback
217    // Called on every newly generated text segment
218    // Use the whisper_full_...() functions to obtain the text segments
219    typedef void (*whisper_new_segment_callback)(struct whisper_context * ctx, int n_new, void * user_data);
220
221    // Encoder begin callback
222    // If not NULL, called before the encoder starts
223    // If it returns false, the computation is aborted
224    typedef bool (*whisper_encoder_begin_callback)(struct whisper_context * ctx, void * user_data);
225
226    // Parameters for the whisper_full() function
227    // If you chnage the order or add new parameters, make sure to update the default values in whisper.cpp:
228    // whisper_full_default_params()
229    struct whisper_full_params {
230        enum whisper_sampling_strategy strategy;
231
232        int n_threads;
233        int n_max_text_ctx;
234        int offset_ms;          // start offset in ms
235        int duration_ms;        // audio duration to process in ms
236
237        bool translate;
238        bool no_context;
239        bool single_segment;    // force single segment output (useful for streaming)
240        bool print_special;
241        bool print_progress;
242        bool print_realtime;
243        bool print_timestamps;
244
245        // [EXPERIMENTAL] token-level timestamps
246        bool  token_timestamps; // enable token-level timestamps
247        float thold_pt;         // timestamp token probability threshold (~0.01)
248        float thold_ptsum;      // timestamp token sum probability threshold (~0.01)
249        int   max_len;          // max segment length in characters
250        int   max_tokens;       // max tokens per segment (0 = no limit)
251
252        // [EXPERIMENTAL] speed-up techniques
253        bool speed_up;          // speed-up the audio by 2x using Phase Vocoder
254        int  audio_ctx;         // overwrite the audio context size (0 = use default)
255
256        // tokens to provide the whisper model as initial prompt
257        // these are prepended to any existing text context from a previous call
258        const whisper_token * prompt_tokens;
259        int prompt_n_tokens;
260
261        // for auto-detection, set to nullptr, "" or "auto"
262        const char * language;
263
264        struct {
265            int n_past;
266        } greedy;
267
268        struct {
269            int n_past;
270            int beam_width;
271            int n_best;
272        } beam_search;
273
274        whisper_new_segment_callback new_segment_callback;
275        void * new_segment_callback_user_data;
276
277        whisper_encoder_begin_callback encoder_begin_callback;
278        void * encoder_begin_callback_user_data;
279    };
280
281    WHISPER_API struct whisper_full_params whisper_full_default_params(enum whisper_sampling_strategy strategy);
282
283    // Run the entire model: PCM -> log mel spectrogram -> encoder -> decoder -> text
284    // Uses the specified decoding strategy to obtain the text.
285    WHISPER_API int whisper_full(
286                struct whisper_context * ctx,
287            struct whisper_full_params   params,
288                           const float * samples,
289                                   int   n_samples);
290
291    // Split the input audio in chunks and process each chunk separately using whisper_full()
292    // It seems this approach can offer some speedup in some cases.
293    // However, the transcription accuracy can be worse at the beginning and end of each chunk.
294    WHISPER_API int whisper_full_parallel(
295                struct whisper_context * ctx,
296            struct whisper_full_params   params,
297                           const float * samples,
298                                   int   n_samples,
299                                   int   n_processors);
300
301    // Number of generated text segments.
302    // A segment can be a few words, a sentence, or even a paragraph.
303    WHISPER_API int whisper_full_n_segments(struct whisper_context * ctx);
304
305    // Get the start and end time of the specified segment.
306    WHISPER_API int64_t whisper_full_get_segment_t0(struct whisper_context * ctx, int i_segment);
307    WHISPER_API int64_t whisper_full_get_segment_t1(struct whisper_context * ctx, int i_segment);
308
309    // Get the text of the specified segment.
310    WHISPER_API const char * whisper_full_get_segment_text(struct whisper_context * ctx, int i_segment);
311
312    // Get number of tokens in the specified segment.
313    WHISPER_API int whisper_full_n_tokens(struct whisper_context * ctx, int i_segment);
314
315    // Get the token text of the specified token in the specified segment.
316    WHISPER_API const char * whisper_full_get_token_text(struct whisper_context * ctx, int i_segment, int i_token);
317    WHISPER_API whisper_token whisper_full_get_token_id (struct whisper_context * ctx, int i_segment, int i_token);
318
319    // Get token data for the specified token in the specified segment.
320    // This contains probabilities, timestamps, etc.
321    WHISPER_API whisper_token_data whisper_full_get_token_data(struct whisper_context * ctx, int i_segment, int i_token);
322
323    // Get the probability of the specified token in the specified segment.
324    WHISPER_API float whisper_full_get_token_p(struct whisper_context * ctx, int i_segment, int i_token);
325
326#ifdef __cplusplus
327}
328#endif
329
330#endif