File size: 4,348 Bytes
89ccb6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import uuid
from pathlib import Path
from typing import Optional

from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel

from TTS.api import TTS
import soundfile as sf
import numpy as np

# ---------- Paths ----------
BASE_DIR = Path(__file__).parent
VOICES_DIR = BASE_DIR / "voices"
OUTPUTS_DIR = BASE_DIR / "outputs"
VOICES_DIR.mkdir(exist_ok=True)
OUTPUTS_DIR.mkdir(exist_ok=True)

# ---------- FastAPI app ----------
app = FastAPI(title="Meshcraft Voice Clone Backend")

# Allow calls from any origin (your site will call this)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ---------- TTS model ----------
# You can change this to another Coqui model if you prefer.
TTS_MODEL_NAME = os.getenv(
    "TTS_MODEL_NAME",
    "tts_models/multilingual/multi-dataset/xtts_v2",
)

_tts: Optional[TTS] = None


def get_tts() -> TTS:
    global _tts
    if _tts is None:
        _tts = TTS(TTS_MODEL_NAME, gpu=False)
    return _tts


# ---------- Schemas ----------
class GenerateRequest(BaseModel):
    voice_id: str
    text: str


# ---------- Helpers ----------
def validate_audio_duration(path: Path, min_sec: int = 30, max_sec: int = 300):
    try:
        data, sr = sf.read(str(path))
    except Exception:
        raise HTTPException(
            status_code=400,
            detail="Could not read audio file. Please upload a valid WAV/MP3 file.",
        )

    if data.ndim > 1:
        data = np.mean(data, axis=1)

    duration_sec = len(data) / float(sr)

    if duration_sec < min_sec:
        raise HTTPException(
            status_code=400,
            detail=f"Audio is too short ({duration_sec:.1f}s). Use at least {min_sec} seconds of speech.",
        )
    if duration_sec > max_sec:
        raise HTTPException(
            status_code=400,
            detail=f"Audio is too long ({duration_sec:.1f}s). Limit is {max_sec} seconds.",
        )


# ---------- Endpoints ----------
@app.post("/api/upload-voice")
async def upload_voice(file: UploadFile = File(...)):
    if not file.filename:
        raise HTTPException(status_code=400, detail="No file uploaded.")

    ext = Path(file.filename).suffix.lower()
    if ext not in {".wav", ".mp3"}:
        raise HTTPException(
            status_code=400,
            detail="Unsupported file type. Please upload WAV or MP3.",
        )

    voice_id = str(uuid.uuid4())
    dest_path = VOICES_DIR / f"{voice_id}{ext}"

    with dest_path.open("wb") as f:
        f.write(await file.read())

    # Validate basic duration constraints
    validate_audio_duration(dest_path)

    return {"voice_id": voice_id}


@app.post("/api/generate")
async def generate_audio(payload: GenerateRequest):
    text = payload.text.strip()
    if not text:
        raise HTTPException(status_code=400, detail="Text cannot be empty.")
    if len(text) > 500:
        raise HTTPException(status_code=400, detail="Text is limited to 500 characters.")

    # Find voice file
    candidates = list(VOICES_DIR.glob(f"{payload.voice_id}.*"))
    if not candidates:
        raise HTTPException(status_code=404, detail="Voice profile not found.")
    ref_audio_path = candidates[0]

    tts = get_tts()

    out_path = OUTPUTS_DIR / f"{uuid.uuid4()}.wav"
    # Generate conditioned on reference voice
    tts.tts_to_file(
        text=text,
        file_path=str(out_path),
        speaker_wav=str(ref_audio_path),
        language="en",
    )

    # HF Spaces will serve static files from the app; return relative URL
    audio_url = f"/outputs/{out_path.name}"
    return {"audio_url": audio_url}


@app.delete("/api/voices/{voice_id}")
async def delete_voice(voice_id: str):
    deleted = False
    for p in VOICES_DIR.glob(f"{voice_id}.*"):
        try:
            p.unlink()
            deleted = True
        except Exception:
            pass

    # Also delete any generated outputs that start with this voice_id if you choose
    # (here we keep outputs independent, so just succeed even if nothing deleted).
    return {"deleted": deleted}


@app.get("/")
async def root():
    return {"status": "ok", "message": "Meshcraft voice clone backend running."}