This commit is contained in:
Dan Chen
2024-03-18 16:19:26 +08:00
parent 253577da04
commit afb78295c8
6 changed files with 62 additions and 55 deletions

View File

@ -1,3 +1,5 @@
from fastapi import Response,status
from fastapi.responses import JSONResponse
import speech_recognition as sr
import filetype
import io
@ -10,9 +12,13 @@ class AudioToText(Blackbox):
kind = filetype.guess(data)
if kind is None:
return False
return kind.mime == "audio/wav"
return kind.extension == "wav"
def processing(self, data: io.BytesIO):
def processing(self, data: bytes | io.BytesIO):
if data is None:
raise ValueError("Data is required")
if isinstance(data, bytes):
data = io.BytesIO(data)
if not self.valid(data):
raise ValueError("Invalid data")
r = sr.Recognizer()
@ -20,3 +26,14 @@ class AudioToText(Blackbox):
audio_data = r.record(source)
text = r.recognize_google(audio_data)
return text
async def fast_api_handler(self, request) -> Response:
data = (await request.form()).get("data")
if data is None:
return JSONResponse(content={"error": "data is required"}, status_code=status.HTTP_400_BAD_REQUEST)
d = await data.read()
try:
txt = self.processing(d)
except ValueError as e:
return JSONResponse(content={"error": str(e)}, status_code=status.HTTP_400_BAD_REQUEST)
return JSONResponse(content={"txt": txt}, status_code=status.HTTP_200_OK)

View File

@ -1,18 +1,21 @@
from abc import ABC, abstractmethod
from fastapi import Request, Response
class Blackbox(ABC):
def __init__(self, config: any) -> None:
pass
@abstractmethod
def processing(self, data: any):
pass
@abstractmethod
def valid(self, data: any) -> bool:
pass
class TextToAudio(Blackbox):
def processing(self, data: any):
print("TextToAudio processing")
@abstractmethod
def fast_api_handler(self, request: Request) -> Response:
pass

View File

@ -0,0 +1,12 @@
from blackbox.audio_to_text import AudioToText
from blackbox.blackbox import Blackbox
class BlockboxFactory:
def create_blockbox(self, blockbox_type: str, blockbox_config: dict) -> Blackbox:
if blockbox_type == "audio_to_text":
return AudioToText(blockbox_config)
raise ValueError("Invalid blockbox type")