/ src / python / txtai / api / routers / texttospeech.py
texttospeech.py
 1  """
 2  Defines API paths for TTS endpoints
 3  """
 4  
 5  from typing import Optional
 6  
 7  from fastapi import APIRouter, Response
 8  
 9  from .. import application
10  from ..route import EncodingAPIRoute
11  
12  router = APIRouter(route_class=EncodingAPIRoute)
13  
14  
15  @router.get("/texttospeech")
16  def texttospeech(text: str, speaker: Optional[str] = None, encoding: Optional[str] = "mp3"):
17      """
18      Generates speech from text.
19  
20      Args:
21          text: text
22          speaker: speaker id, defaults to 1
23          encoding: optional audio encoding format
24  
25      Returns:
26          Audio data
27      """
28  
29      # Convert to audio
30      audio = application.get().pipeline("texttospeech", text, speaker=speaker, encoding=encoding)
31  
32      # Write audio
33      return Response(audio, headers={"Content-Disposition": f"attachment;filename=speech.{encoding.lower()}"})