convert this ai model inference python gradio script into a fully functional uvicorn server and provide that and a c# example of how to inference into the script (windows forms c# visual studio {no need to write form data just need example code just being hyper specific.}).
Copyright (c) 2023 Amphion.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
import os
from huggingface_hub import snapshot_download
from models.vc.vevo.vevo_utils import *
def vevo_tts(
src_text,
ref_wav_path,
timbre_ref_wav_path=None,
output_path=None,
ref_text=None,
src_language="en",
ref_language="en",
):
if timbre_ref_wav_path is None:
timbre_ref_wav_path = ref_wav_path
code
gen_audio = inference_pipeline.inference_ar_and_fm(
src_wav_path=None,
src_text=src_text,
style_ref_wav_path=ref_wav_path,
timbre_ref_wav_path=timbre_ref_wav_path,
style_ref_wav_text=ref_text,
src_text_language=src_language,
style_ref_wav_text_language=ref_language,
)
assert output_path is not None
save_audio(gen_audio, output_path=output_path)
if name == "main":
# ===== Device =====
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
code
Assistant
User
the uvicorn script provided just loads the models then ends with no errors or debug output, please fix the script and provide the full script fixed.
Assistant
# ===== Content-Style Tokenizer =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["tokenizer/vq8192/*"],
)
content_style_tokenizer_ckpt_path = os.path.join(local_dir, "tokenizer/vq8192")
# ===== Autoregressive Transformer =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
)
ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
ar_ckpt_path = os.path.join(local_dir, "contentstyle_modeling/PhoneToVq8192")
# ===== Flow Matching Transformer =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
)
fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
fmt_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vq8192ToMels")
# ===== Vocoder =====
local_dir = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vocoder/*"],
)
vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
vocoder_ckpt_path = os.path.join(local_dir, "acoustic_modeling/Vocoder")
# ===== Inference =====
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
src_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences."
ref_wav_path = "./models/vc/vevo/wav/arabic_male.wav"
ref_text = "Flip stood undecided, his ears strained to catch the slightest sound."
# 1. Zero-Shot TTS (the style reference and timbre reference are same)
vevo_tts(
src_text,
ref_wav_path,
output_path="./models/vc/vevo/wav/output_vevotts1.wav",
ref_text=ref_text,
src_language="en",
ref_language="en",
)
# 2. Style and Timbre Controllable Zero-Shot TTS (the style reference and timbre reference are different)
vevo_tts(
src_text,
ref_wav_path,
timbre_ref_wav_path="./models/vc/vevo/wav/mandarin_female.wav",
output_path="./models/vc/vevo/wav/output_vevotts2.wav",
ref_text=ref_text,
src_language="en",
ref_language="en",
)
Certainly! Below is a conversion of your Gradio-based Python script to a fully functional FastAPI-based server running on Uvicorn, exposing the TTS inference via a REST API. Additionally, I've included a minimal C# example demonstrating how to consume this API in a Windows Forms context.
Part 1: Python - FastAPI + Uvicorn Server
python
# server.py
import os
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import FileResponse
from pydantic import BaseModel
import torch
from huggingface_hub import snapshot_download
from tempfile import NamedTemporaryFile
from typing import Optional
from models.vc.vevo.vevo_utils import VevoInferencePipeline, save_audio # Adjust import if necessary
app = FastAPI(title="Vevo TTS API")
# ===== Device =====
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
# Download & Prepare Model Checkpoints only once at startup
print("Downloading model checkpoints and initializing the inference pipeline...")
local_dir_tokenizer = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["tokenizer/vq8192/*"],
)
content_style_tokenizer_ckpt_path = os.path.join(local_dir_tokenizer, "tokenizer/vq8192")
local_dir_ar = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
)
ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
ar_ckpt_path = os.path.join(local_dir_ar, "contentstyle_modeling/PhoneToVq8192")
local_dir_fmt = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
)
fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
fmt_ckpt_path = os.path.join(local_dir_fmt, "acoustic_modeling/Vq8192ToMels")
local_dir_vocoder = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vocoder/*"],
)
vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
vocoder_ckpt_path = os.path.join(local_dir_vocoder, "acoustic_modeling/Vocoder")
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
print("Model loaded and ready.")
class TTSRequest(BaseModel):
src_text: str
ref_text: Optional[str] = None
src_language: str = "en"
ref_language: str = "en"
@app.post("/vevo_tts/")
async def vevo_tts_endpoint(
src_text: str = Form(...),
ref_text: Optional[str] = Form(None),
src_language: str = Form("en"),
ref_language: str = Form("en"),
style_ref_wav: UploadFile = File(...),
timbre_ref_wav: Optional[UploadFile] = File(None),
):
try:
# Save uploaded style_ref_wav to tempfile
with NamedTemporaryFile(suffix=os.path.splitext(style_ref_wav.filename)[-1], delete=False) as style_tmp:
style_tmp.write(await style_ref_wav.read())
style_ref_path = style_tmp.name
if timbre_ref_wav is None:
timbre_ref_wav_path = style_ref_path
else:
with NamedTemporaryFile(suffix=os.path.splitext(timbre_ref_wav.filename)[-1], delete=False) as timbre_tmp:
timbre_tmp.write(await timbre_ref_wav.read())
timbre_ref_wav_path = timbre_tmp.name
# Create a temporary output wav file
with NamedTemporaryFile(suffix=".wav", delete=False) as output_tmp:
output_path = output_tmp.name
# Run inference
gen_audio = inference_pipeline.inference_ar_and_fm(
src_wav_path=None,
src_text=src_text,
style_ref_wav_path=style_ref_path,
timbre_ref_wav_path=timbre_ref_wav_path,
style_ref_wav_text=ref_text,
src_text_language=src_language,
style_ref_wav_text_language=ref_language,
)
save_audio(gen_audio, output_path=output_path)
# Clean up input temp files
os.unlink(style_ref_path)
if timbre_ref_wav is not None:
os.unlink(timbre_ref_wav_path)
# Return the generated audio file
return FileResponse(output_path, media_type="audio/wav", filename="output.wav")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Part 2: C# Example to Call This API from Windows Forms
csharp
// Necessary imports
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;
class VevoTTSClient
{
private readonly HttpClient _client = new HttpClient();
// Replace with your API base URL
private readonly string baseApiUrl = "http://localhost:8000";
public async Task<byte[]> GenerateTTSAsync(
string srcText,
string refText,
string srcLanguage,
string refLanguage,
string styleRefWavPath,
string timbreRefWavPath = null)
{
using (var content = new MultipartFormDataContent())
{
// Add form fields
content.Add(new StringContent(srcText), "src_text");
if (!string.IsNullOrEmpty(refText))
content.Add(new StringContent(refText), "ref_text");
content.Add(new StringContent(srcLanguage), "src_language");
content.Add(new StringContent(refLanguage), "ref_language");
// Add style_ref_wav file
var styleWavBytes = File.ReadAllBytes(styleRefWavPath);
var styleByteContent = new ByteArrayContent(styleWavBytes);
styleByteContent.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");
content.Add(styleByteContent, "style_ref_wav", Path.GetFileName(styleRefWavPath));
// Add timbre_ref_wav file if provided
if (!string.IsNullOrEmpty(timbreRefWavPath))
{
var timbreWavBytes = File.ReadAllBytes(timbreRefWavPath);
var timbreByteContent = new ByteArrayContent(timbreWavBytes);
timbreByteContent.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");
content.Add(timbreByteContent, "timbre_ref_wav", Path.GetFileName(timbreRefWavPath));
}
// Send POST request
HttpResponseMessage response = await _client.PostAsync($"{baseApiUrl}/vevo_tts/", content);
response.EnsureSuccessStatusCode();
// Read WAV bytes from response
byte[] wavBytes = await response.Content.ReadAsByteArrayAsync();
return wavBytes;
}
}
}
How to use this C# client snippet
csharp
// Example usage within an async method in your Windows Forms app
var client = new VevoTTSClient();
byte[] generatedAudio = await client.GenerateTTSAsync(
srcText: "Hello world, this is a test.",
refText: "Reference speech text.",
srcLanguage: "en",
refLanguage: "en",
styleRefWavPath: @"C:\path\to\arabic_male.wav",
timbreRefWavPath: @"C:\path\to\mandarin_female.wav"
);
// Save output WAV to file
File.WriteAllBytes(@"C:\path\to\output_vevotts.wav", generatedAudio);
// Play or process output_vevotts.wav as needed
Notes:
Make sure to install all model dependencies and contain your model weights/configs accordingly.
The Python server expects the audio files (style_ref_wav and optionally timbre_ref_wav) as file uploads in the request.
The generated WAV file is returned directly in the response, so your C# client just consumes the response as bytes and can save/play them as needed.
This example assumes you host the Python API locally on port 8000. Change the URL accordingly.
If you want me to include detailed requirements.txt or data validation, just ask!
Thanks for the feedback — the cause of the issue is that the script you run just loads the models but Uvicorn server is not started because in the script I omitted the if __name__ == "__main__": block or command to start Uvicorn programmatically.
The corrected approach is:
Option A: Run the server with uvicorn server:app --host 0.0.0.0 --port 8000 manually (simple, recommended)
Option B: Add the if __name__ == "__main__" block in the script to start Uvicorn from within Python when running python server.py.
You reported that after running python server.py nothing happens. That's because no server start command is executed.
Fixed full script for server.py with embedded Uvicorn server start
python
import os
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import FileResponse
import torch
from huggingface_hub import snapshot_download
from tempfile import NamedTemporaryFile
from typing import Optional
import uvicorn
from models.vc.vevo.vevo_utils import VevoInferencePipeline, save_audio # Make sure this path is correct
app = FastAPI(title="Vevo TTS API")
# ===== Device =====
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
# Download and initialize model pipeline once
print("Downloading model checkpoints and initializing the inference pipeline...")
local_dir_tokenizer = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["tokenizer/vq8192/*"],
)
content_style_tokenizer_ckpt_path = os.path.join(local_dir_tokenizer, "tokenizer/vq8192")
local_dir_ar = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["contentstyle_modeling/PhoneToVq8192/*"],
)
ar_cfg_path = "./models/vc/vevo/config/PhoneToVq8192.json"
ar_ckpt_path = os.path.join(local_dir_ar, "contentstyle_modeling/PhoneToVq8192")
local_dir_fmt = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vq8192ToMels/*"],
)
fmt_cfg_path = "./models/vc/vevo/config/Vq8192ToMels.json"
fmt_ckpt_path = os.path.join(local_dir_fmt, "acoustic_modeling/Vq8192ToMels")
local_dir_vocoder = snapshot_download(
repo_id="amphion/Vevo",
repo_type="model",
cache_dir="./ckpts/Vevo",
allow_patterns=["acoustic_modeling/Vocoder/*"],
)
vocoder_cfg_path = "./models/vc/vevo/config/Vocoder.json"
vocoder_ckpt_path = os.path.join(local_dir_vocoder, "acoustic_modeling/Vocoder")
inference_pipeline = VevoInferencePipeline(
content_style_tokenizer_ckpt_path=content_style_tokenizer_ckpt_path,
ar_cfg_path=ar_cfg_path,
ar_ckpt_path=ar_ckpt_path,
fmt_cfg_path=fmt_cfg_path,
fmt_ckpt_path=fmt_ckpt_path,
vocoder_cfg_path=vocoder_cfg_path,
vocoder_ckpt_path=vocoder_ckpt_path,
device=device,
)
print("Model loaded and ready.")
@app.post("/vevo_tts/")
async def vevo_tts_endpoint(
src_text: str = Form(...),
ref_text: Optional[str] = Form(None),
src_language: str = Form("en"),
ref_language: str = Form("en"),
style_ref_wav: UploadFile = File(...),
timbre_ref_wav: Optional[UploadFile] = File(None),
):
try:
# Save uploaded style_ref_wav to a temporary file
with NamedTemporaryFile(suffix=os.path.splitext(style_ref_wav.filename)[-1], delete=False) as style_tmp:
style_tmp.write(await style_ref_wav.read())
style_ref_path = style_tmp.name
if timbre_ref_wav is None:
timbre_ref_wav_path = style_ref_path
else:
with NamedTemporaryFile(suffix=os.path.splitext(timbre_ref_wav.filename)[-1], delete=False) as timbre_tmp:
timbre_tmp.write(await timbre_ref_wav.read())
timbre_ref_wav_path = timbre_tmp.name
# Temporary file for output audio
with NamedTemporaryFile(suffix=".wav", delete=False) as output_tmp:
output_path = output_tmp.name
# Run inference
gen_audio = inference_pipeline.inference_ar_and_fm(
src_wav_path=None,
src_text=src_text,
style_ref_wav_path=style_ref_path,
timbre_ref_wav_path=timbre_ref_wav_path,
style_ref_wav_text=ref_text,
src_text_language=src_language,
style_ref_wav_text_language=ref_language,
)
save_audio(gen_audio, output_path=output_path)
# Cleanup input temp files
os.unlink(style_ref_path)
if timbre_ref_wav is not None:
os.unlink(timbre_ref_wav_path)
# Send output wav file
return FileResponse(output_path, media_type="audio/wav", filename="output.wav")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
# Run Uvicorn programmatically with reload disabled for actual deployments
uvicorn.run(app, host="0.0.0.0", port=8000)
Explanation / Fix summary:
Added the if __name__ == "__main__": with uvicorn.run() call to start the FastAPI server when you run python server.py.
Added some print statements for startup progress visibility.
Now when you run:
bash
python server.py
You will see log output that Uvicorn has started and the app is listening on port 8000.
How to test
Run: python server.py
Access the automatic docs at: http://localhost:8000/docs (Swagger UI)
Test your endpoint /vevo_tts/ through UI or the C# client.
If you want me to help with adding logging or async improvements, just ask!