Skip to content

Commit

Permalink
Refactor whisper_wrapper.cpp: Add trim function and handle exceptions…
Browse files Browse the repository at this point in the history
… in transcription and result callback
  • Loading branch information
royshil committed Oct 24, 2024
1 parent ac714b3 commit fddebc4
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions src/whisper_wrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@

namespace py = pybind11;

std::string trim(const std::string &str)
{
size_t start = str.find_first_not_of(" \t\n\r");
size_t end = str.find_last_not_of(" \t\n\r");

if (start == std::string::npos) // handles empty string "" and all-whitespace strings like " "
return "";

return str.substr(start, end - start + 1);
}

// Global variable to store the Python callback function
py::function g_py_log_callback;

Expand Down Expand Up @@ -212,7 +223,19 @@ class ThreadedWhisperModel
}

// Process audio
std::vector<std::string> segments = model.transcribe_raw_audio(process_buffer.data(), process_buffer.size());
std::vector<std::string> segments;
try
{
segments = model.transcribe_raw_audio(process_buffer.data(), process_buffer.size());
}
catch (const std::exception &e)
{
std::cerr << "Exception during transcription: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown exception during transcription" << std::endl;
}

std::cout << "Transcription: " << segments[0] << std::endl;

Expand Down Expand Up @@ -307,15 +330,33 @@ class ThreadedWhisperModel
py::gil_scoped_acquire gil;
for (const auto &result : results)
{
if (result.segments.empty())
continue;

// concatenate segments into a single string
std::string full_text;
for (const auto &segment : result.segments)
{
full_text += segment;
}
full_text = trim(full_text);
if (full_text.empty())
continue;

if (result_callback)
{
result_callback((int)result.chunk_id, py::str(full_text), result.is_partial);
try
{
result_callback((int)result.chunk_id, py::str(full_text), result.is_partial);
}
catch (const std::exception &e)
{
std::cerr << "Exception in result callback: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown exception in result callback" << std::endl;
}
}
}
}
Expand Down

0 comments on commit fddebc4

Please sign in to comment.