Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970from fastapi import FastAPI, WebSocket, UploadFile, Filefrom pywhispercpp.model import Modelimport uvicornimport tempfileimport osfrom time import timeapp = FastAPI(title="pyWhisperCPP API")model = Model('base.en')@app.get("/")def root():return {"status": "Whisper.cpp API is running!"}@app.post("/transcribe")async def transcribe(file: UploadFile = File(...)):with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp:temp.write(await file.read())temp.flush()audio_path = temp.namestart = time()segments = model.transcribe(audio_path)text = " ".join([seg.text for seg in segments])elapsed = round(time() - start, 3)os.remove(audio_path)return {"text": text, "processing_time_seconds": elapsed}# ==========================================================# 🔥 Real-time Speech Recognition (WebSocket)# ==========================================================@app.websocket("/ws/transcribe_stream")async def websocket_transcription(websocket: WebSocket):await websocket.accept()buffer = b""while True:chunk = await websocket.receive_bytes()if chunk == b"__END__":breakbuffer += chunk# When buffer > 1 sec of audio, transcribeif len(buffer) >= 16000 * 2: # 16kHz * 2 bytes = 1 second PCM16# Save buffer temporarilywith tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp:temp.write(buffer)temp.flush()audio_path = temp.namesegments = model.transcribe(audio_path)text = " ".join([seg.text for seg in segments])await websocket.send_text(text)buffer = b"" # clear for next batchos.remove(audio_path)await websocket.send_text("stream_end")await websocket.close()if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120from fastapi import FastAPI, UploadFile, File, WebSocket, WebSocketDisconnectfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pywhispercpp.model import Modelimport uvicornimport tempfileimport osfrom time import timeapp = FastAPI(title="pyWhisperCPP Streaming API")# Allow CORS (useful if you host frontend separately, but fine on Spaces too)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Load Whisper.cpp model ONCE# OPTIONS: 'tiny.en', 'base.en', etc.model = Model("base.en")# ---------- Simple HTML frontend ----------@app.get("/", response_class=HTMLResponse)async def index():# Serve the index.html filewith open("index.html", "r", encoding="utf-8") as f:return HTMLResponse(f.read())# ---------- Normal file upload transcription ----------@app.post("/transcribe")async def transcribe(file: UploadFile = File(...)):# Save uploaded audio temporarilywith tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp:temp.write(await file.read())temp.flush()audio_path = temp.nametry:start = time()segments = model.transcribe(audio_path)text = " ".join(seg.text for seg in segments)elapsed = round(time() - start, 3)return {"text": text,"processing_time_seconds": elapsed}finally:os.remove(audio_path)# ---------- WebSocket streaming transcription ----------@app.websocket("/ws/transcribe_stream")async def websocket_transcription(websocket: WebSocket):"""Receives binary audio chunks (WebM/Opus) from the browser via WebSocket,periodically transcribes the buffered audio with Whisper.cpp,and sends back partial text."""await websocket.accept()buffer = b""MIN_CHUNK_SIZE = 40_000 # bytes before running a transcription (tune this)try:while True:message = await websocket.receive()# Handle text messages (control)if "text" in message and message["text"] is not None:text_msg = message["text"]if text_msg == "__END__":# Finish streambreak# Ignore other text controls for nowcontinue# Handle binary audio datachunk = message.get("bytes")if not chunk:continuebuffer += chunk# When enough audio collected, transcribeif len(buffer) >= MIN_CHUNK_SIZE:with tempfile.NamedTemporaryFile(delete=False, suffix=".webm") as temp:temp.write(buffer)temp.flush()audio_path = temp.nametry:segments = model.transcribe(audio_path)text = " ".join(seg.text for seg in segments).strip()finally:os.remove(audio_path)# Send partial transcript to clientif text:await websocket.send_text(text)# Clear buffer (or keep tail if you want overlap)buffer = b""# End-of-stream messageawait websocket.send_text("[stream ended]")except WebSocketDisconnect:# Client disconnectedpassfinally:await websocket.close()if __name__ == "__main__":# For local testing. On Spaces, you don't usually run uvicorn manually.uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+91-41