File size: 4,797 Bytes
95636c5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
import logging
import os
import uuid
from contextlib import asynccontextmanager
from tempfile import NamedTemporaryFile
import boto3
import torchaudio
from fastapi import BackgroundTasks, Depends, FastAPI, Header, HTTPException
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
from inference import load_models, process_voice_conversion
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global variables
models = None
API_KEY = os.getenv("API_KEY")
api_key_header = APIKeyHeader(name="Authorization", auto_error=False)
async def verify_api_key(authorization: str = Header(None)):
if not authorization:
logger.warning("No API key provided")
raise HTTPException(status_code=401, detail="API key is missing")
if authorization.startswith("Bearer "):
token = authorization.replace("Bearer ", "")
else:
token = authorization
if token != API_KEY:
logger.warning("Invalid API key provided")
raise HTTPException(status_code=401, detail="Invalid API key")
return token
def get_s3_client():
client_kwargs = {'region_name': os.getenv("AWS_REGION", "us-east-1")}
if os.getenv("AWS_ACCESS_KEY_ID") and os.getenv("AWS_SECRET_ACCESS_KEY"):
client_kwargs.update({
'aws_access_key_id': os.getenv("AWS_ACCESS_KEY_ID"),
'aws_secret_access_key': os.getenv("AWS_SECRET_ACCESS_KEY")
})
return boto3.client('s3', **client_kwargs)
s3_client = get_s3_client()
S3_PREFIX = os.getenv("S3_PREFIX", "seedvc-outputs")
S3_BUCKET = os.getenv("S3_BUCKET", "elevenlabs-clone")
@asynccontextmanager
async def lifespan(app: FastAPI):
global models
logger.info("Loading Seed-VC model...")
try:
models = load_models()
logger.info("Seed-VC model loaded successfully")
except Exception as e:
logger.error(f"Failed to load model: {e}")
raise
yield
logger.info("Shutting down Seed-VC API")
app = FastAPI(title="Seed-VC API",
lifespan=lifespan)
TARGET_VOICES = {
"andreas": "examples/reference/andreas1.wav",
"woman": "examples/reference/s1p1.wav",
"trump": "examples/reference/trump_0.wav",
}
class VoiceConversionRequest(BaseModel):
source_audio_key: str
target_voice: str
@app.post("/convert", dependencies=[Depends(verify_api_key)])
async def generate_speech(request: VoiceConversionRequest, background_tasks: BackgroundTasks):
if not models:
raise HTTPException(status_code=500, detail="Model not loaded")
if request.target_voice not in TARGET_VOICES:
raise HTTPException(
status_code=400, detail=f"Target voice not supported. Choose from: {', '.join(TARGET_VOICES.keys())}")
try:
target_audio_path = TARGET_VOICES[request.target_voice]
logger.info(
f"Converting voice: {request.source_audio_key} to {request.target_voice}")
# Generate a unique filename
audio_id = str(uuid.uuid4())
output_filename = f"{audio_id}.wav"
local_path = f"/tmp/{output_filename}"
logger.info("Downloading source audio")
source_temp = NamedTemporaryFile(delete=False, suffix=".wav")
try:
s3_client.download_fileobj(
S3_BUCKET, Key=request.source_audio_key, Fileobj=source_temp)
source_temp.close()
except Exception as e:
os.unlink(source_temp.name)
raise HTTPException(
status_code=404, detail="Source audio not found")
vc_wave, sr = process_voice_conversion(
models=models, source=source_temp.name, target_name=target_audio_path, output=None)
os.unlink(source_temp.name)
torchaudio.save(local_path, vc_wave, sr)
# Upload to S3
s3_key = f"{S3_PREFIX}/{output_filename}"
s3_client.upload_file(local_path, S3_BUCKET, s3_key)
presigned_url = s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': S3_BUCKET, 'Key': s3_key},
ExpiresIn=3600
)
background_tasks.add_task(os.remove, local_path)
return {
"audio_url": presigned_url,
"s3_key": s3_key
}
except Exception as e:
logger.error(f"Error in voice conversion: {e}")
raise HTTPException(
status_code=500, detail="Error in voice conversion")
@app.get("/voices", dependencies=[Depends(verify_api_key)])
async def list_voices():
return {"voices": list(TARGET_VOICES.keys())}
@app.get("/health", dependencies=[Depends(verify_api_key)])
async def health_check():
if models:
return {"status": "healthy", "model": "loaded"}
return {"status": "unhealthy", "model": "not loaded"}
|