sachin commited on
Commit
1a0c6cf
·
1 Parent(s): 1f029a6
Files changed (1) hide show
  1. src/server/main.py +23 -12
src/server/main.py CHANGED
@@ -156,6 +156,7 @@ async def home():
156
  return RedirectResponse(url="/docs")
157
 
158
  from fastapi.responses import FileResponse
 
159
  import tempfile
160
  import os
161
 
@@ -173,7 +174,8 @@ async def generate_audio(
173
  request: Request,
174
  input: str = Query(..., description="Text to convert to speech (max 1000 characters)"),
175
  response_format: str = Query("mp3", description="Audio format (ignored, defaults to mp3 for external API)"),
176
- tts_service: TTSService = Depends(get_tts_service)
 
177
  ):
178
  if not input.strip():
179
  raise HTTPException(status_code=400, detail="Input cannot be empty")
@@ -188,16 +190,19 @@ async def generate_audio(
188
 
189
  payload = {"text": input}
190
 
 
 
 
 
191
  try:
192
  response = await tts_service.generate_speech(payload)
193
  response.raise_for_status()
194
 
195
- # Create a temporary file to store the audio
196
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file:
197
  for chunk in response.iter_content(chunk_size=8192):
198
  if chunk:
199
- temp_file.write(chunk)
200
- temp_file_path = temp_file.name
201
 
202
  # Prepare headers for the response
203
  headers = {
@@ -205,6 +210,17 @@ async def generate_audio(
205
  "Cache-Control": "no-cache",
206
  }
207
 
 
 
 
 
 
 
 
 
 
 
 
208
  # Return the file as a FileResponse
209
  return FileResponse(
210
  path=temp_file_path,
@@ -217,13 +233,8 @@ async def generate_audio(
217
  logger.error(f"External TTS request failed: {str(e)}")
218
  raise HTTPException(status_code=502, detail=f"External TTS service error: {str(e)}")
219
  finally:
220
- # Clean up the temporary file if it exists
221
- if 'temp_file_path' in locals() and os.path.exists(temp_file_path):
222
- try:
223
- os.unlink(temp_file_path)
224
- except Exception as e:
225
- logger.error(f"Failed to delete temporary file: {str(e)}")
226
-
227
 
228
  @app.post("/v1/chat",
229
  response_model=ChatResponse,
 
156
  return RedirectResponse(url="/docs")
157
 
158
  from fastapi.responses import FileResponse
159
+ from fastapi.background import BackgroundTasks
160
  import tempfile
161
  import os
162
 
 
174
  request: Request,
175
  input: str = Query(..., description="Text to convert to speech (max 1000 characters)"),
176
  response_format: str = Query("mp3", description="Audio format (ignored, defaults to mp3 for external API)"),
177
+ tts_service: TTSService = Depends(get_tts_service),
178
+ background_tasks: BackgroundTasks = BackgroundTasks()
179
  ):
180
  if not input.strip():
181
  raise HTTPException(status_code=400, detail="Input cannot be empty")
 
190
 
191
  payload = {"text": input}
192
 
193
+ # Create a temporary file to store the audio
194
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
195
+ temp_file_path = temp_file.name
196
+
197
  try:
198
  response = await tts_service.generate_speech(payload)
199
  response.raise_for_status()
200
 
201
+ # Write audio content to the temporary file
202
+ with open(temp_file_path, "wb") as f:
203
  for chunk in response.iter_content(chunk_size=8192):
204
  if chunk:
205
+ f.write(chunk)
 
206
 
207
  # Prepare headers for the response
208
  headers = {
 
210
  "Cache-Control": "no-cache",
211
  }
212
 
213
+ # Schedule file cleanup as a background task
214
+ def cleanup_file(file_path: str):
215
+ try:
216
+ if os.path.exists(file_path):
217
+ os.unlink(file_path)
218
+ logger.info(f"Deleted temporary file: {file_path}")
219
+ except Exception as e:
220
+ logger.error(f"Failed to delete temporary file {file_path}: {str(e)}")
221
+
222
+ background_tasks.add_task(cleanup_file, temp_file_path)
223
+
224
  # Return the file as a FileResponse
225
  return FileResponse(
226
  path=temp_file_path,
 
233
  logger.error(f"External TTS request failed: {str(e)}")
234
  raise HTTPException(status_code=502, detail=f"External TTS service error: {str(e)}")
235
  finally:
236
+ # Close the temporary file to ensure it's fully written
237
+ temp_file.close()
 
 
 
 
 
238
 
239
  @app.post("/v1/chat",
240
  response_model=ChatResponse,