Spaces:
Sleeping
Sleeping
Update Logic/SpeachToText.py
Browse files- Logic/SpeachToText.py +38 -17
Logic/SpeachToText.py
CHANGED
@@ -1,19 +1,40 @@
|
|
1 |
-
from fastapi import
|
2 |
-
from
|
|
|
3 |
import speech_recognition as sr
|
4 |
-
from
|
5 |
-
from
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from pydantic import BaseModel
|
4 |
import speech_recognition as sr
|
5 |
+
from io import BytesIO
|
6 |
+
from pydub import AudioSegment
|
7 |
+
import os
|
8 |
+
|
9 |
+
app = FastAPI()
|
10 |
+
|
11 |
+
class TranscriptionResponse(BaseModel):
|
12 |
+
text: str
|
13 |
+
|
14 |
+
@app.post("/transcribe", response_model=TranscriptionResponse)
|
15 |
+
async def transcribe_audio(file: UploadFile = File(...)):
|
16 |
+
if file.content_type not in ["audio/wav", "audio/mpeg", "audio/mp3", "audio/x-wav", "audio/flac"]:
|
17 |
+
raise HTTPException(status_code=400, detail="Unsupported file type")
|
18 |
+
|
19 |
+
try:
|
20 |
+
# Read the file into bytes
|
21 |
+
audio_data = await file.read()
|
22 |
+
audio_file = BytesIO(audio_data)
|
23 |
+
|
24 |
+
# Use pydub to handle different audio formats
|
25 |
+
audio = AudioSegment.from_file(audio_file, format=file.filename.split('.')[-1])
|
26 |
+
wav_audio = BytesIO()
|
27 |
+
audio.export(wav_audio, format="wav")
|
28 |
+
wav_audio.seek(0)
|
29 |
+
|
30 |
+
# Use speech_recognition to process the audio
|
31 |
+
recognizer = sr.Recognizer()
|
32 |
+
with sr.AudioFile(wav_audio) as source:
|
33 |
+
audio = recognizer.record(source)
|
34 |
|
35 |
+
# Recognize speech using Google Web Speech API
|
36 |
+
text = recognizer.recognize_google(audio, language="en-US")
|
37 |
+
return TranscriptionResponse(text=text)
|
38 |
+
|
39 |
+
except Exception as e:
|
40 |
+
raise HTTPException(status_code=500, detail=str(e))
|