CoolFace
Apppublic

quantumphysicistsam/SpeechGeneration

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py73 linesDownload Raw Back to root
1import os2import tempfile3from fastapi import FastAPI, UploadFile, File, Form4from fastapi.responses import FileResponse, JSONResponse5from TTS.api import TTS6import uvicorn7 8# Initialize FastAPI9app = FastAPI(10    title="TTS Voice Cloning API",11    description="API endpoint for synthesizing speech using Coqui TTS's voice cloning model.",12    version="1.0"13)14 15# Load the voice cloning model (YourTTS) for supported languages.16# Supported languages: "en", "fr-fr", "pt-br"17model_your_tts = TTS(18    model_name="tts_models/multilingual/multi-dataset/your_tts",19    progress_bar=False,20    gpu=False  # Change to True if your deployment environment has a GPU21)22 23@app.post("/synthesize/", summary="Synthesize speech from text")24async def synthesize_speech(25    text: str = Form(..., description="The text to synthesize."),26    language: str = Form(..., description="Language code (e.g., en, fr-fr, pt-br)."),27    speaker_file: UploadFile = File(None, description="Optional speaker reference WAV file")28):29    """30    Synthesize speech from text using the TTS model.  31    If no speaker file is uploaded, the default speaker (`my_voice.wav`) will be used if available.32    """33    # Create a temporary file to store the generated audio.34    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:35        output_path = tmp_file.name36 37    # Process the uploaded speaker file if provided.38    if speaker_file:39        try:40            # Save the uploaded file to a temporary location.41            with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as spk_file:42                content = await speaker_file.read()43                spk_file.write(content)44                speaker_path = spk_file.name45        except Exception as e:46            return JSONResponse(status_code=400, content={"error": f"Error processing speaker file: {str(e)}"})47    else:48        # Use the default recorded voice if available.49        default_speaker = "my_voice.wav"50        speaker_path = default_speaker if os.path.exists(default_speaker) else None51 52    # Attempt to synthesize speech.53    try:54        model_your_tts.tts_to_file(55            text=text,56            language=language,57            speaker_wav=speaker_path,58            file_path=output_path59        )60    except Exception as e:61        return JSONResponse(status_code=500, content={"error": f"Error during synthesis: {str(e)}"})62 63    # Return the synthesized audio as a WAV file.64    return FileResponse(65        output_path,66        media_type="audio/wav",67        filename="output.wav"68    )69 70# Optional: Run the server locally (useful for testing)71if __name__ == "__main__":72    uvicorn.run(app, host="0.0.0.0", port=8000)73