malek-messaoudii
Refactor audio processing and chatbot services; enhance STT and TTS functionalities with base64 support and session management
56dc677
raw
history blame
3 kB
from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from fastapi.responses import JSONResponse
import uuid
import base64
from models.audio import UserMessage, ChatbotResponse, MessageType
from services.chatbot_service import ChatbotService
router = APIRouter()
chatbot_service = ChatbotService()
@router.post("/chat/message", response_model=ChatbotResponse)
async def send_chat_message(
session_id: str = Form(...),
message_type: str = Form(...),
message: str = Form(None),
audio_file: UploadFile = File(None)
):
try:
# Validate input
if not message and not audio_file:
raise HTTPException(status_code=400, detail="Either message or audio file must be provided")
if message_type == "audio" and not audio_file:
raise HTTPException(status_code=400, detail="Audio file required for audio messages")
# Process audio file if provided
content = ""
if audio_file:
audio_data = await audio_file.read()
content = base64.b64encode(audio_data).decode('utf-8')
else:
content = message
# Create user message
user_message = UserMessage(
message_id=str(uuid.uuid4()),
content=content,
message_type=MessageType(message_type),
session_id=session_id
)
# Process through chatbot service
response = await chatbot_service.process_user_message(user_message)
return response
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing message: {str(e)}")
@router.post("/chat/audio")
async def send_audio_message(
session_id: str = Form(...),
audio_file: UploadFile = File(...)
):
"""Endpoint specifically for audio messages"""
try:
audio_data = await audio_file.read()
audio_base64 = base64.b64encode(audio_data).decode('utf-8')
user_message = UserMessage(
message_id=str(uuid.uuid4()),
content=audio_base64,
message_type=MessageType.AUDIO,
session_id=session_id
)
response = await chatbot_service.process_user_message(user_message)
return response
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing audio: {str(e)}")
@router.get("/session/{session_id}/history")
async def get_session_history(session_id: str):
"""Get conversation history for a session"""
history = chatbot_service.get_session_history(session_id)
if not history:
raise HTTPException(status_code=404, detail="Session not found")
return history
@router.post("/session/new")
async def create_new_session():
"""Create a new chat session"""
session_id = str(uuid.uuid4())
chatbot_service._get_or_create_session(session_id)
return {"session_id": session_id, "message": "New session created"}