Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
-
from fastapi import FastAPI,
|
2 |
-
from fastapi.responses import JSONResponse
|
3 |
import speech_recognition as sr
|
4 |
import os
|
5 |
import uuid
|
@@ -11,25 +10,26 @@ os.makedirs(UPLOAD_DIR, exist_ok=True)
|
|
11 |
|
12 |
@app.post("/voice-to-text")
|
13 |
async def voice_to_text(file: UploadFile = File(...)):
|
14 |
-
# Check file
|
15 |
if not file.filename.endswith(".wav"):
|
16 |
raise HTTPException(status_code=400, detail="Only .wav files are supported")
|
17 |
|
18 |
# Save uploaded file
|
19 |
-
|
20 |
-
with open(
|
21 |
f.write(await file.read())
|
22 |
|
23 |
-
#
|
24 |
recognizer = sr.Recognizer()
|
25 |
try:
|
26 |
-
with sr.AudioFile(
|
27 |
audio_data = recognizer.record(source)
|
28 |
-
|
29 |
-
return
|
|
|
30 |
except sr.UnknownValueError:
|
31 |
-
raise HTTPException(status_code=400, detail="
|
32 |
except sr.RequestError as e:
|
33 |
-
raise HTTPException(status_code=500, detail=f"API error: {e}")
|
34 |
finally:
|
35 |
-
os.remove(
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
|
|
2 |
import speech_recognition as sr
|
3 |
import os
|
4 |
import uuid
|
|
|
10 |
|
11 |
@app.post("/voice-to-text")
|
12 |
async def voice_to_text(file: UploadFile = File(...)):
|
13 |
+
# Check for .wav file
|
14 |
if not file.filename.endswith(".wav"):
|
15 |
raise HTTPException(status_code=400, detail="Only .wav files are supported")
|
16 |
|
17 |
# Save uploaded file
|
18 |
+
file_path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4()}.wav")
|
19 |
+
with open(file_path, "wb") as f:
|
20 |
f.write(await file.read())
|
21 |
|
22 |
+
# Speech recognition
|
23 |
recognizer = sr.Recognizer()
|
24 |
try:
|
25 |
+
with sr.AudioFile(file_path) as source:
|
26 |
audio_data = recognizer.record(source)
|
27 |
+
recognized_text = recognizer.recognize_google(audio_data)
|
28 |
+
return {"recognized_text": recognized_text}
|
29 |
+
|
30 |
except sr.UnknownValueError:
|
31 |
+
raise HTTPException(status_code=400, detail="Could not understand audio")
|
32 |
except sr.RequestError as e:
|
33 |
+
raise HTTPException(status_code=500, detail=f"Speech API error: {e}")
|
34 |
finally:
|
35 |
+
os.remove(file_path)
|