国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

開源C++智能語音識別庫whisper.cpp開發(fā)使用入門

這篇具有很好參考價值的文章主要介紹了開源C++智能語音識別庫whisper.cpp開發(fā)使用入門。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

whisper.cpp是一個C++編寫的輕量級開源智能語音識別庫,是基于openai的開源python智能語音模型whisper的移植版本,依賴項少,內(nèi)存占用低,性能更優(yōu),方便作為依賴庫集成的到應(yīng)用程序中提供語音識別功能。

以下基于whisper.cpp的源碼利用C++ api來開發(fā)實例demo演示讀取本地音頻文件并轉(zhuǎn)成文字。

項目結(jié)構(gòu)

whispercpp_starter
    - whisper.cpp-v1.5.0
    - src
      |- main.cpp
    - CMakeLists.txt

CMakeLists.txt

cmake_minimum_required(VERSION 3.15)

# this only works for unix, xapian source code not support compile in windows yet

project(whispercpp_starter)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_subdirectory(whisper.cpp-v1.5.0)

include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}/whisper.cpp-v1.5.0
    ${CMAKE_CURRENT_SOURCE_DIR}/whisper.cpp-v1.5.0/examples
)

file(GLOB SRC
    src/*.h
    src/*.cpp
)

add_executable(${PROJECT_NAME} ${SRC})

target_link_libraries(${PROJECT_NAME}
    common
    whisper # remember to copy dll or so to bin folder
)

main.cpp

#include <cmath>
#include <fstream>
#include <cstdio>
#include <string>
#include <thread>
#include <vector>
#include <cstring>

#include "common.h"
#include "whisper.h"

#if defined(_MSC_VER)
#pragma warning(disable: 4244 4267) // possible loss of data
#endif

// Terminal color map. 10 colors grouped in ranges [0.0, 0.1, ..., 0.9]
// Lowest is red, middle is yellow, highest is green.
const std::vector<std::string> k_colors = {
    "\033[38;5;196m", "\033[38;5;202m", "\033[38;5;208m", "\033[38;5;214m", "\033[38;5;220m",
    "\033[38;5;226m", "\033[38;5;190m", "\033[38;5;154m", "\033[38;5;118m", "\033[38;5;82m",
};

//  500 -> 00:05.000
// 6000 -> 01:00.000
std::string to_timestamp(int64_t t, bool comma = false)
{
    int64_t msec = t * 10;
    int64_t hr = msec / (1000 * 60 * 60);
    msec = msec - hr * (1000 * 60 * 60);
    int64_t min = msec / (1000 * 60);
    msec = msec - min * (1000 * 60);
    int64_t sec = msec / 1000;
    msec = msec - sec * 1000;

    char buf[32];
    snprintf(buf, sizeof(buf), "%02d:%02d:%02d%s%03d", (int)hr, (int)min, (int)sec, comma ? "," : ".", (int)msec);

    return std::string(buf);
}

int timestamp_to_sample(int64_t t, int n_samples)
{
    return std::max(0, std::min((int)n_samples - 1, (int)((t * WHISPER_SAMPLE_RATE) / 100)));
}

// helper function to replace substrings
void replace_all(std::string& s, const std::string& search, const std::string& replace)
{
    for (size_t pos = 0; ; pos += replace.length())
    {
        pos = s.find(search, pos);
        if (pos == std::string::npos) break;
        s.erase(pos, search.length());
        s.insert(pos, replace);
    }
}

// command-line parameters
struct whisper_params
{
    int32_t n_threads = std::min(4, (int32_t)std::thread::hardware_concurrency());
    int32_t n_processors = 1;
    int32_t offset_t_ms = 0;
    int32_t offset_n = 0;
    int32_t duration_ms = 0;
    int32_t progress_step = 5;
    int32_t max_context = -1;
    int32_t max_len = 0;
    int32_t best_of = whisper_full_default_params(WHISPER_SAMPLING_GREEDY).greedy.best_of;
    int32_t beam_size = whisper_full_default_params(WHISPER_SAMPLING_BEAM_SEARCH).beam_search.beam_size;

    float word_thold = 0.01f;
    float entropy_thold = 2.40f;
    float logprob_thold = -1.00f;

    bool speed_up = false;
    bool debug_mode = false;
    bool translate = false;
    bool detect_language = false;
    bool diarize = false;
    bool tinydiarize = false;
    bool split_on_word = false;
    bool no_fallback = false;
    bool output_txt = false;
    bool output_vtt = false;
    bool output_srt = false;
    bool output_wts = false;
    bool output_csv = false;
    bool output_jsn = false;
    bool output_jsn_full = false;
    bool output_lrc = false;
    bool print_special = false;
    bool print_colors = false;
    bool print_progress = false;
    bool no_timestamps = false;
    bool log_score = false;
    bool use_gpu = true;

    std::string language = "en";
    std::string prompt;
    std::string font_path = "/System/Library/Fonts/Supplemental/Courier New Bold.ttf";
    std::string model = "models/ggml-base.en.bin";

    // [TDRZ] speaker turn string
    std::string tdrz_speaker_turn = " [SPEAKER_TURN]"; // TODO: set from command line

    std::string openvino_encode_device = "CPU";

    std::vector<std::string> fname_inp = {};
    std::vector<std::string> fname_out = {};
};

struct whisper_print_user_data
{
    const whisper_params* params;

    const std::vector<std::vector<float>>* pcmf32s;
    int progress_prev;
};

std::string estimate_diarization_speaker(std::vector<std::vector<float>> pcmf32s, int64_t t0, int64_t t1, bool id_only = false)
{
    std::string speaker = "";
    const int64_t n_samples = pcmf32s[0].size();

    const int64_t is0 = timestamp_to_sample(t0, n_samples);
    const int64_t is1 = timestamp_to_sample(t1, n_samples);

    double energy0 = 0.0f;
    double energy1 = 0.0f;

    for (int64_t j = is0; j < is1; j++)
    {
        energy0 += fabs(pcmf32s[0][j]);
        energy1 += fabs(pcmf32s[1][j]);
    }

    if (energy0 > 1.1 * energy1)
    {
        speaker = "0";
    }
    else if (energy1 > 1.1 * energy0)
    {
        speaker = "1";
    }
    else
    {
        speaker = "?";
    }

    //printf("is0 = %lld, is1 = %lld, energy0 = %f, energy1 = %f, speaker = %s\n", is0, is1, energy0, energy1, speaker.c_str());

    if (!id_only)
    {
        speaker.insert(0, "(speaker ");
        speaker.append(")");
    }

    return speaker;
}
void whisper_print_progress_callback(struct whisper_context* /*ctx*/, struct whisper_state* /*state*/, int progress, void* user_data)
{
    int progress_step = ((whisper_print_user_data*)user_data)->params->progress_step;
    int* progress_prev = &(((whisper_print_user_data*)user_data)->progress_prev);
    if (progress >= *progress_prev + progress_step)
    {
        *progress_prev += progress_step;
        fprintf(stderr, "%s: progress = %3d%%\n", __func__, progress);
    }
}

void whisper_print_segment_callback(struct whisper_context* ctx, struct whisper_state* /*state*/, int n_new, void* user_data)
{
    const auto& params = *((whisper_print_user_data*)user_data)->params;
    const auto& pcmf32s = *((whisper_print_user_data*)user_data)->pcmf32s;

    const int n_segments = whisper_full_n_segments(ctx);

    std::string speaker = "";

    int64_t t0 = 0;
    int64_t t1 = 0;

    // print the last n_new segments
    const int s0 = n_segments - n_new;

    if (s0 == 0)
    {
        printf("\n");
    }

    for (int i = s0; i < n_segments; i++)
    {
        if (!params.no_timestamps || params.diarize)
        {
            t0 = whisper_full_get_segment_t0(ctx, i);
            t1 = whisper_full_get_segment_t1(ctx, i);
        }

        if (!params.no_timestamps)
        {
            printf("[%s --> %s]  ", to_timestamp(t0).c_str(), to_timestamp(t1).c_str());
        }

        if (params.diarize && pcmf32s.size() == 2)
        {
            speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
        }

        if (params.print_colors)
        {
            for (int j = 0; j < whisper_full_n_tokens(ctx, i); ++j)
            {
                if (params.print_special == false)
                {
                    const whisper_token id = whisper_full_get_token_id(ctx, i, j);
                    if (id >= whisper_token_eot(ctx))
                    {
                        continue;
                    }
                }

                const char* text = whisper_full_get_token_text(ctx, i, j);
                const float  p = whisper_full_get_token_p(ctx, i, j);

                const int col = std::max(0, std::min((int)k_colors.size() - 1, (int)(std::pow(p, 3) * float(k_colors.size()))));

                printf("%s%s%s%s", speaker.c_str(), k_colors[col].c_str(), text, "\033[0m");
            }
        }
        else
        {
            const char* text = whisper_full_get_segment_text(ctx, i);

            printf("%s%s", speaker.c_str(), text);
        }

        if (params.tinydiarize)
        {
            if (whisper_full_get_segment_speaker_turn_next(ctx, i))
            {
                printf("%s", params.tdrz_speaker_turn.c_str());
            }
        }

        // with timestamps or speakers: each segment on new line
        if (!params.no_timestamps || params.diarize)
        {
            printf("\n");
        }

        fflush(stdout);
    }
}

bool output_txt(struct whisper_context* ctx, const char* fname, const whisper_params& params, std::vector<std::vector<float>> pcmf32s)
{
    std::ofstream fout(fname);
    if (!fout.is_open())
    {
        fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname);
        return false;
    }

    fprintf(stderr, "%s: saving output to '%s'\n", __func__, fname);

    const int n_segments = whisper_full_n_segments(ctx);
    for (int i = 0; i < n_segments; ++i)
    {
        const char* text = whisper_full_get_segment_text(ctx, i);
        std::string speaker = "";

        if (params.diarize && pcmf32s.size() == 2)
        {
            const int64_t t0 = whisper_full_get_segment_t0(ctx, i);
            const int64_t t1 = whisper_full_get_segment_t1(ctx, i);
            speaker = estimate_diarization_speaker(pcmf32s, t0, t1);
        }

        fout << speaker << text << "\n";
    }

    return true;
}

int main(int argc, char** argv)
{
    const std::string model_file_path = "./ggml-base.en.bin";
    const std::string audio_file_path = "sample.wav"; // should be wav 16bit format

    // set whisper params
    whisper_params params;
    params.model = model_file_path;
    params.fname_inp.emplace_back(audio_file_path);

    // whisper init
    struct whisper_context_params cparams;
    cparams.use_gpu = params.use_gpu;

    struct whisper_context* ctx = whisper_init_from_file_with_params(params.model.c_str(), cparams);

    if (ctx == nullptr)
    {
        fprintf(stderr, "error: failed to initialize whisper context\n");
        return 3;
    }

    // initialize openvino encoder. this has no effect on whisper.cpp builds that don't have OpenVINO configured
    whisper_ctx_init_openvino_encoder(ctx, nullptr, params.openvino_encode_device.c_str(), nullptr);

    for (int f = 0; f < (int)params.fname_inp.size(); ++f)
    {
        const auto fname_inp = params.fname_inp[f];
        const auto fname_out = f < (int)params.fname_out.size() && !params.fname_out[f].empty() ? params.fname_out[f] : params.fname_inp[f];

        std::vector<float> pcmf32;               // mono-channel F32 PCM
        std::vector<std::vector<float>> pcmf32s; // stereo-channel F32 PCM

        if (!read_wav(fname_inp, pcmf32, pcmf32s, params.diarize))
        {
            fprintf(stderr, "error: failed to read WAV file '%s'\n", fname_inp.c_str());
            continue;
        }

        // print system information
        {
            fprintf(stderr, "\n");
            fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
                params.n_threads * params.n_processors, std::thread::hardware_concurrency(), whisper_print_system_info());
        }

        // print some info about the processing
        {
            fprintf(stderr, "\n");
            if (!whisper_is_multilingual(ctx))
            {
                if (params.language != "en" || params.translate)
                {
                    params.language = "en";
                    params.translate = false;
                    fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);
                }
            }
            if (params.detect_language)
            {
                params.language = "auto";
            }
            fprintf(stderr, "%s: processing '%s' (%d samples, %.1f sec), %d threads, %d processors, %d beams + best of %d, lang = %s, task = %s, %stimestamps = %d ...\n",
                __func__, fname_inp.c_str(), int(pcmf32.size()), float(pcmf32.size()) / WHISPER_SAMPLE_RATE,
                params.n_threads, params.n_processors, params.beam_size, params.best_of,
                params.language.c_str(),
                params.translate ? "translate" : "transcribe",
                params.tinydiarize ? "tdrz = 1, " : "",
                params.no_timestamps ? 0 : 1);

            fprintf(stderr, "\n");
        }

        // run the inference
        {
            whisper_full_params wparams = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);

            wparams.strategy = params.beam_size > 1 ? WHISPER_SAMPLING_BEAM_SEARCH : WHISPER_SAMPLING_GREEDY;

            wparams.print_realtime = false;
            wparams.print_progress = params.print_progress;
            wparams.print_timestamps = !params.no_timestamps;
            wparams.print_special = params.print_special;
            wparams.translate = params.translate;
            wparams.language = params.language.c_str();
            wparams.detect_language = params.detect_language;
            wparams.n_threads = params.n_threads;
            wparams.n_max_text_ctx = params.max_context >= 0 ? params.max_context : wparams.n_max_text_ctx;
            wparams.offset_ms = params.offset_t_ms;
            wparams.duration_ms = params.duration_ms;

            wparams.token_timestamps = params.output_wts || params.output_jsn_full || params.max_len > 0;
            wparams.thold_pt = params.word_thold;
            wparams.max_len = params.output_wts && params.max_len == 0 ? 60 : params.max_len;
            wparams.split_on_word = params.split_on_word;

            wparams.speed_up = params.speed_up;
            wparams.debug_mode = params.debug_mode;

            wparams.tdrz_enable = params.tinydiarize; // [TDRZ]

            wparams.initial_prompt = params.prompt.c_str();

            wparams.greedy.best_of = params.best_of;
            wparams.beam_search.beam_size = params.beam_size;

            wparams.temperature_inc = params.no_fallback ? 0.0f : wparams.temperature_inc;
            wparams.entropy_thold = params.entropy_thold;
            wparams.logprob_thold = params.logprob_thold;

            whisper_print_user_data user_data = { &params, &pcmf32s, 0 };

            // this callback is called on each new segment
            if (!wparams.print_realtime)
            {
                wparams.new_segment_callback = whisper_print_segment_callback;
                wparams.new_segment_callback_user_data = &user_data;
            }

            if (wparams.print_progress)
            {
                wparams.progress_callback = whisper_print_progress_callback;
                wparams.progress_callback_user_data = &user_data;
            }

            // examples for abort mechanism
            // in examples below, we do not abort the processing, but we could if the flag is set to true

            // the callback is called before every encoder run - if it returns false, the processing is aborted
            {
                static bool is_aborted = false; // NOTE: this should be atomic to avoid data race

                wparams.encoder_begin_callback = [](struct whisper_context* /*ctx*/, struct whisper_state* /*state*/, void* user_data) {
                    bool is_aborted = *(bool*)user_data;
                    return !is_aborted;
                    };
                wparams.encoder_begin_callback_user_data = &is_aborted;
            }

            // the callback is called before every computation - if it returns true, the computation is aborted
            {
                static bool is_aborted = false; // NOTE: this should be atomic to avoid data race

                wparams.abort_callback = [](void* user_data) {
                    bool is_aborted = *(bool*)user_data;
                    return is_aborted;
                    };
                wparams.abort_callback_user_data = &is_aborted;
            }

            if (whisper_full_parallel(ctx, wparams, pcmf32.data(), pcmf32.size(), params.n_processors) != 0)
            {
                fprintf(stderr, "%s: failed to process audio\n", argv[0]);
                return 10;
            }
        }

        // output stuff
        {
            printf("\n");

            // output to text file
            if (params.output_txt)
            {
                const auto fname_txt = fname_out + ".txt";
                output_txt(ctx, fname_txt.c_str(), params, pcmf32s);
            }
        }
    }

    // whisper release
    whisper_print_timings(ctx);
    whisper_free(ctx);

    return 0;
}

注:

  • whisper支持的模型文件需要自己去下載
  • whisper.cpp編譯可以配置多種類型的增強選項,比如支持CPU/GPU加速,數(shù)據(jù)計算加速庫
  • whisper.cpp的編譯cmake文件做了少量改動,方便集成到項目,具體可參看demo

源碼

whispercpp_starter

本文由博客一文多發(fā)平臺 OpenWrite 發(fā)布!文章來源地址http://www.zghlxwxcb.cn/news/detail-828523.html

到了這里,關(guān)于開源C++智能語音識別庫whisper.cpp開發(fā)使用入門的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • OpenAI 開源語音識別 Whisper

    OpenAI 開源語音識別 Whisper

    ????????Whisper是一個通用語音識別模型。它是在各種音頻的大型數(shù)據(jù)集上訓(xùn)練的,也是一個多任務(wù)模型,可以執(zhí)行多語言語音識別以及語音翻譯和語言識別。???????? ???????人工智能公司 OpenAI?擁有 GTP-3 語言模型,并為 GitHub Copilot 提供技術(shù)支持的 ,宣布開源了

    2024年02月09日
    瀏覽(111)
  • Whisper OpenAI開源語音識別模型

    Whisper 是一個自動語音識別(ASR,Automatic Speech Recognition)系統(tǒng),OpenAI 通過從網(wǎng)絡(luò)上收集了 68 萬小時的多語言(98 種語言)和多任務(wù)(multitask)監(jiān)督數(shù)據(jù)對 Whisper 進行了訓(xùn)練。OpenAI 認為使用這樣一個龐大而多樣的數(shù)據(jù)集,可以提高對口音、背景噪音和技術(shù)術(shù)語的識別能力。除

    2024年02月16日
    瀏覽(96)
  • 可以白嫖的語音識別開源項目whisper的搭建詳細過程 | 如何在Linux中搭建OpenAI開源的語音識別項目Whisper

    可以白嫖的語音識別開源項目whisper的搭建詳細過程 | 如何在Linux中搭建OpenAI開源的語音識別項目Whisper

    原文來自我個人的博客。 服務(wù)器為GPU服務(wù)器。點擊這里跳轉(zhuǎn)到我使用的GPU服務(wù)器。我搭建 whisper 選用的是 NVIDIA A 100顯卡,4GB顯存。 Python版本要在3.8~3.11之間。 輸入下面命令查看使用的Python版本。 為啥要安裝Anaconda? 為了減少不同項目使用的庫的版本沖突,我們可以使用An

    2024年02月09日
    瀏覽(21)
  • 語音識別開源框架 openAI-whisper

    Whisper 是一種通用的語音識別模型。 它是OpenAI于2022年9月份開源的在各種音頻的大型數(shù)據(jù)集上訓(xùn)練的語音識別模型,也是一個可以執(zhí)行多語言語音識別、語音翻譯和語言識別的多任務(wù)模型。 GitHub - yeyupiaoling/Whisper-Finetune: 微調(diào)Whisper語音識別模型和加速推理,支持Web部署和Andr

    2024年02月17日
    瀏覽(97)
  • 開源語音識別faster-whisper部署教程

    源碼地址 模型下載地址: 下載 cuBLAS and cuDNN 在 conda 環(huán)境中創(chuàng)建 python 運行環(huán)境 激活虛擬環(huán)境 安裝 faster-whisper 依賴 執(zhí)行完以上步驟后,我們可以寫代碼了 說明: 更多內(nèi)容歡迎訪問博客 對應(yīng)視頻內(nèi)容歡迎訪問視頻

    2024年02月04日
    瀏覽(18)
  • OpenAI開源??!Whisper語音識別實戰(zhàn)??!【環(huán)境配置+代碼實現(xiàn)】

    OpenAI開源??!Whisper語音識別實戰(zhàn)?。 经h(huán)境配置+代碼實現(xiàn)】

    目錄 環(huán)境配置 代碼實現(xiàn) ******? 實現(xiàn) .mp4轉(zhuǎn)換為 .wav文件,識別后進行匹配并輸出出現(xiàn)的次數(shù) ******? 完整代碼實現(xiàn)請私信 安裝 ffmpeg 打開網(wǎng)址? ?https://github.com/BtbN/FFmpeg-Builds/releases 下載如下圖所示的文件 下載后解壓 ?我的路徑是G:ffmpeg-master-latest-win64-gpl-shared

    2024年02月13日
    瀏覽(25)
  • chatGPT的耳朵!OpenAI的開源語音識別AI:Whisper !

    chatGPT的耳朵!OpenAI的開源語音識別AI:Whisper !

    語音識別是通用人工智能的重要一環(huán)!可以說是AI的耳朵! 它可以讓機器理解人類的語音,并將其轉(zhuǎn)換為文本或其他形式的輸出。 語音識別的應(yīng)用場景非常廣泛,比如智能助理、語音搜索、語音翻譯、語音輸入等等。 然而,語音識別也面臨著很多挑戰(zhàn),比如不同的語言、口

    2024年03月14日
    瀏覽(26)
  • OpenAI開源全新解碼器和語音識別模型Whisper-v3

    OpenAI開源全新解碼器和語音識別模型Whisper-v3

    在11月7日OpenAI的首屆開發(fā)者大會上,除了推出一系列重磅產(chǎn)品之外,還開源了兩款產(chǎn)品,全新解碼器Consistency Decoder(一致性解碼器)和最新語音識別模型Whisper v3。 據(jù)悉,Consistency Decoder可以替代Stable Diffusion VAE解碼器。該解碼器可以改善所有與Stable Diffusion 1.0+ VAE兼容的圖像,

    2024年02月05日
    瀏覽(92)
  • OpenAI開源語音識別模型Whisper在Windows系統(tǒng)的安裝詳細過程

    OpenAI開源語音識別模型Whisper在Windows系統(tǒng)的安裝詳細過程

    Python的安裝很簡單,點擊這里進行下載。 安裝完成之后,輸入python -V可以看到版本信息,說明已經(jīng)安裝成功了。 如果輸入python -V命令沒有看到上面的這樣的信息,要么是安裝失敗,要么是安裝好之后沒有自動配置環(huán)境變量,如何配置環(huán)境變量可以從網(wǎng)上搜索。 Python的具體安

    2024年02月08日
    瀏覽(90)
  • whisper實踐--基于whisper+pyqt5開發(fā)的語音識別翻譯生成字幕工具

    whisper實踐--基于whisper+pyqt5開發(fā)的語音識別翻譯生成字幕工具

    大家新年快樂,事業(yè)生活蒸蒸日上,解封的第一個年,想必大家都回家過年,好好陪陪家人了吧,這篇文章也是我在老家碼的,還記得上篇我?guī)Т蠹一玖私饬藈hisper,相信大家對whisper是什么,怎么安裝whisper,以及使用都有了一個認識,這次作為新年第一篇文章,我將介紹一

    2024年02月01日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包