from fastapi import FastAPI, HTTPException, Response from pydantic import BaseModel from elevenlabs import generate_speech app = FastAPI() class SpeechRequest(BaseModel): model: str input: str voice: str @app.post("/v1/audio/speech") async def create_speech(request: SpeechRequest): try: # Map the OpenAI-style request to your ElevenLabs function result = generate_speech( model=request.model, voice=request.voice, input_text=request.input ) if isinstance(result, list): # If result is a list, it means there was an error raise HTTPException(status_code=result[0], detail=result[1]) # If successful, return the audio content return Response(content=result, media_type="audio/mpeg") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/") async def root(): return {"message": "Welcome to the Text-to-Speech API"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860) # print("Sample URL: http://localhost:7860/v1/audio/speech?model=eleven_multilingual_v2&input=Hello+world&voice=XB0fDUnXU5powFXDhCwa")