FastAPI Call Code Understanding
@router.post("/api/chat")
async def chat(
request: Request,
audio: Optional[UploadFile] = File(None),
text: Optional[str] = Form(None)
):
"""
Handle chat requests - supports both audio and text input
"""
try:
# Handle audio input
if audio:
# Validate file extension
file_extension = audio.filename.split('.')[-1].lower()
if file_extension not in settings.ALLOWED_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"File type not allowed. Allowed types: {settings.ALLOWED_EXTENSIONS}"
)
# Save uploaded audio file
file_path = os.path.join(settings.UPLOAD_FOLDER, audio.filename)
os.makedirs(settings.UPLOAD_FOLDER, exist_ok=True)
with open(file_path, "wb") as f:
content = await audio.read()
f.write(content)
# Transcribe audio to text
transcription = await speech_service.transcribe_audio(file_path)
# Clean up uploaded file
if os.path.exists(file_path):
os.remove(file_path)
return JSONResponse(content={"text": transcription})
# Handle text input
if text:
# Get AI response
response_text = await openai_service.get_answer(text)
# Convert response to audio
audio_filename = await audio_service.text_to_audio(response_text)
# Build audio URL
audio_url = f"/static/audio/{audio_filename}"
return JSONResponse(content={
"text": response_text,
"voice": audio_url
})
raise HTTPException(status_code=400, detail="No audio or text provided")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
