From 45d3faf9610050b4d19cfc7035b5f2b2c93b887c Mon Sep 17 00:00:00 2001 From: NETZkultur GmbH Date: Mon, 13 Jan 2025 07:55:21 +0100 Subject: [PATCH] server : generate unique tmp filenames (#2718) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #Summary This Merge Request adds a mechanism to generate unique filenames for FFmpeg conversions in whisper_server.cpp. Previously, a single fixed filename was used (e.g., whisper-server-tmp.wav), which could result in unexpected file overwrites under certain circumstances. By generating a unique filename per request, any risk of overwriting temporary files is eliminated. #Background / Motivation • Problem: Relying on a static filename for temporary audio files may lead to overwrites if multiple operations occur simultaneously or if the same file name is reused. • Goal: Dynamically generate unique filenames, ensuring each request or operation uses an isolated temporary file. --- examples/server/server.cpp | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/examples/server/server.cpp b/examples/server/server.cpp index a8b0de2d..529886c2 100644 --- a/examples/server/server.cpp +++ b/examples/server/server.cpp @@ -223,6 +223,24 @@ void check_ffmpeg_availibility() { } } +std::string generate_temp_filename(const std::string &prefix, const std::string &extension) { + auto now = std::chrono::system_clock::now(); + auto now_time_t = std::chrono::system_clock::to_time_t(now); + + static std::mt19937 rng{std::random_device{}()}; + std::uniform_int_distribution dist(0, 1'000'000'000); + + std::stringstream ss; + ss << prefix + << "-" + << std::put_time(std::localtime(&now_time_t), "%Y%m%d-%H%M%S") + << "-" + << dist(rng) + << extension; + + return ss.str(); +} + bool convert_to_wav(const std::string & temp_filename, std::string & error_resp) { std::ostringstream cmd_stream; std::string converted_filename_temp = temp_filename + "_temp.wav"; @@ -692,9 +710,7 @@ int main(int argc, char ** argv) { if (sparams.ffmpeg_converter) { // if file is not wav, convert to wav // write to temporary file - //const std::string temp_filename_base = std::tmpnam(nullptr); - const std::string temp_filename_base = "whisper-server-tmp"; // TODO: this is a hack, remove when the mutext is removed - const std::string temp_filename = temp_filename_base + ".wav"; + const std::string temp_filename = generate_temp_filename("whisper-server", ".wav"); std::ofstream temp_file{temp_filename, std::ios::binary}; temp_file << audio_file.content; temp_file.close();