HARI PREETHAM commited on
Commit
85f8e7f
·
1 Parent(s): 5cc4545

feat: smart task cancellation on client disconnect

Browse files
Files changed (1) hide show
  1. app.py +12 -1
app.py CHANGED
@@ -15,7 +15,7 @@ from pathlib import Path
15
  from typing import Optional, Dict, Any, List
16
  from collections import deque
17
 
18
- from fastapi import FastAPI, File, UploadFile, HTTPException, Form
19
  from fastapi.responses import Response
20
  from fastapi.middleware.cors import CORSMiddleware
21
  from pydantic import BaseModel
@@ -299,6 +299,7 @@ HALLUCINATION_BLACKLIST = {
299
 
300
  @app.post("/api/transcribe", response_model=TranscriptionResponse)
301
  async def transcribe_audio(
 
302
  file: UploadFile = File(...),
303
  language: Optional[str] = Form(None),
304
  initial_prompt: Optional[str] = Form(None),
@@ -313,6 +314,11 @@ async def transcribe_audio(
313
  temp_file.write(content)
314
  temp_path = temp_file.name
315
 
 
 
 
 
 
316
  model = load_whisper_model()
317
  logger.info(f"Transcribing {file.filename} | Lang: {language} | Seq: {seq_id}")
318
 
@@ -348,6 +354,11 @@ async def transcribe_audio(
348
  repetition_penalty=1.6 # Aggressive repetition control
349
  )
350
 
 
 
 
 
 
351
  segments, info = run_transcription(temp_path)
352
  segments_list = list(segments)
353
 
 
15
  from typing import Optional, Dict, Any, List
16
  from collections import deque
17
 
18
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
19
  from fastapi.responses import Response
20
  from fastapi.middleware.cors import CORSMiddleware
21
  from pydantic import BaseModel
 
299
 
300
  @app.post("/api/transcribe", response_model=TranscriptionResponse)
301
  async def transcribe_audio(
302
+ request: Request,
303
  file: UploadFile = File(...),
304
  language: Optional[str] = Form(None),
305
  initial_prompt: Optional[str] = Form(None),
 
314
  temp_file.write(content)
315
  temp_path = temp_file.name
316
 
317
+ # --- CANCELLATION CHECK 1: Before loading model ---
318
+ if await request.is_disconnected():
319
+ logger.info(f"Client disconnected before transcription (Seq: {seq_id})")
320
+ return TranscriptionResponse(text="", language=language or "en", seq_id=seq_id)
321
+
322
  model = load_whisper_model()
323
  logger.info(f"Transcribing {file.filename} | Lang: {language} | Seq: {seq_id}")
324
 
 
354
  repetition_penalty=1.6 # Aggressive repetition control
355
  )
356
 
357
+ # --- CANCELLATION CHECK 2: Before running Whisper ---
358
+ if await request.is_disconnected():
359
+ logger.info(f"Client disconnected before Whisper (Seq: {seq_id})")
360
+ return TranscriptionResponse(text="", language=language or "en", seq_id=seq_id)
361
+
362
  segments, info = run_transcription(temp_path)
363
  segments_list = list(segments)
364