NETZkultur GmbH commited on
Commit
89d94b1
·
unverified ·
1 Parent(s): cb32a92

server : generate unique tmp filenames (#2718)

Browse files

#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.

Files changed (1) hide show
  1. examples/server/server.cpp +19 -3
examples/server/server.cpp CHANGED
@@ -223,6 +223,24 @@ void check_ffmpeg_availibility() {
223
  }
224
  }
225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  bool convert_to_wav(const std::string & temp_filename, std::string & error_resp) {
227
  std::ostringstream cmd_stream;
228
  std::string converted_filename_temp = temp_filename + "_temp.wav";
@@ -692,9 +710,7 @@ int main(int argc, char ** argv) {
692
  if (sparams.ffmpeg_converter) {
693
  // if file is not wav, convert to wav
694
  // write to temporary file
695
- //const std::string temp_filename_base = std::tmpnam(nullptr);
696
- const std::string temp_filename_base = "whisper-server-tmp"; // TODO: this is a hack, remove when the mutext is removed
697
- const std::string temp_filename = temp_filename_base + ".wav";
698
  std::ofstream temp_file{temp_filename, std::ios::binary};
699
  temp_file << audio_file.content;
700
  temp_file.close();
 
223
  }
224
  }
225
 
226
+ std::string generate_temp_filename(const std::string &prefix, const std::string &extension) {
227
+ auto now = std::chrono::system_clock::now();
228
+ auto now_time_t = std::chrono::system_clock::to_time_t(now);
229
+
230
+ static std::mt19937 rng{std::random_device{}()};
231
+ std::uniform_int_distribution<long long> dist(0, 1'000'000'000);
232
+
233
+ std::stringstream ss;
234
+ ss << prefix
235
+ << "-"
236
+ << std::put_time(std::localtime(&now_time_t), "%Y%m%d-%H%M%S")
237
+ << "-"
238
+ << dist(rng)
239
+ << extension;
240
+
241
+ return ss.str();
242
+ }
243
+
244
  bool convert_to_wav(const std::string & temp_filename, std::string & error_resp) {
245
  std::ostringstream cmd_stream;
246
  std::string converted_filename_temp = temp_filename + "_temp.wav";
 
710
  if (sparams.ffmpeg_converter) {
711
  // if file is not wav, convert to wav
712
  // write to temporary file
713
+ const std::string temp_filename = generate_temp_filename("whisper-server", ".wav");
 
 
714
  std::ofstream temp_file{temp_filename, std::ios::binary};
715
  temp_file << audio_file.content;
716
  temp_file.close();