| |
| |
| |
|
|
| import os, sys, time, json, uuid, shutil, threading |
|
|
| import uvicorn |
| from fastapi import FastAPI, Form, File, UploadFile, HTTPException |
| from fastapi.responses import HTMLResponse, FileResponse, JSONResponse |
| from fastapi.middleware.cors import CORSMiddleware |
| import torch |
|
|
| |
| os.environ["COQUI_TOS_AGREED"] = "1" |
| |
| os.environ.setdefault("HF_HOME", "/home/user/.cache/huggingface") |
|
|
| VOICE_LIB = "/home/user/app/voice_library" |
| OUTPUT_DIR = "/home/user/app/outputs" |
| HISTORY_FILE = "/home/user/app/history.json" |
|
|
| for d in [VOICE_LIB, OUTPUT_DIR]: |
| os.makedirs(d, exist_ok=True) |
|
|
| |
| from TTS.api import TTS |
|
|
| |
| device = "cpu" |
|
|
| print(f"[*] Loading XTTS v2 on {device.upper()} …") |
| xtts_engine = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device) |
| print("[✓] Model ready.") |
|
|
| |
| def load_history(): |
| if os.path.exists(HISTORY_FILE): |
| try: |
| return json.load(open(HISTORY_FILE)) |
| except Exception: |
| pass |
| return [] |
|
|
| def save_history(h): |
| json.dump(h, open(HISTORY_FILE, "w"), ensure_ascii=False, indent=2) |
|
|
| |
| app = FastAPI(title="XTTS Studio") |
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], allow_methods=["*"], allow_headers=["*"] |
| ) |
|
|
| LANGUAGES = { |
| "ar": "العربية", "en": "English", "es": "Español", "fr": "Français", |
| "de": "Deutsch", "it": "Italiano", "pt": "Português","ru": "Русский", |
| "zh-cn": "中文", "ja": "日本語", "ko": "한국어", "tr": "Türkçe", |
| "nl": "Nederlands","pl": "Polski", "cs": "Čeština", "hi": "हिन्दी", |
| } |
|
|
| |
| |
| |
| HTML = r"""<!DOCTYPE html> |
| <html lang="ar" dir="rtl"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>XTTS Voice Studio</title> |
| <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans+Arabic:wght@300;400;600;700&display=swap" rel="stylesheet"> |
| <script src="https://cdn.tailwindcss.com"></script> |
| <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script> |
| <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> |
| <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> |
| <style> |
| :root { --bg: #0b0c0f; --surface: #13151a; --border: #1f2330; --amber: #f5a623; --amber-dim:#a06a10; --green: #3ddc84; --red: #ff5252; --text: #e8eaf0; --muted: #6b7280; --mono: 'IBM Plex Mono', monospace; --sans: 'IBM Plex Sans Arabic', sans-serif; } |
| * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--text); font-family: var(--sans); min-height: 100vh; } |
| ::-webkit-scrollbar { width: 5px; } ::-webkit-scrollbar-track { background: var(--surface); } ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; } |
| body::before { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 0; background: repeating-linear-gradient(0deg, transparent, transparent 39px, rgba(255,255,255,.02) 40px); } |
| .card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; } .amber { color: var(--amber); } .tag { font-family: var(--mono); font-size: 10px; letter-spacing: .12em; text-transform: uppercase; color: var(--muted); } |
| input[type=range] { -webkit-appearance: none; width: 100%; height: 3px; background: var(--border); border-radius: 2px; outline: none; } input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; background: var(--amber); border-radius: 50%; cursor: pointer; transition: transform .15s; } input[type=range]::-webkit-slider-thumb:hover { transform: scale(1.3); } |
| select, textarea { background: var(--bg); border: 1px solid var(--border); color: var(--text); border-radius: 6px; padding: 6px 10px; font-family: var(--sans); outline: none; transition: border-color .2s; } textarea { resize: vertical; padding: 12px; width: 100%; } select:focus, textarea:focus { border-color: var(--amber); } |
| .file-drop { border: 2px dashed var(--border); border-radius: 8px; padding: 16px; text-align: center; cursor: pointer; transition: border-color .2s, background .2s; position: relative; } .file-drop:hover, .file-drop.active { border-color: var(--amber); background: rgba(245,166,35,.05); } .file-drop input { position: absolute; inset: 0; opacity: 0; cursor: pointer; } |
| .btn-primary { background: var(--amber); color: #000; font-weight: 700; border: none; border-radius: 8px; padding: 14px 24px; cursor: pointer; font-family: var(--sans); font-size: 15px; width: 100%; transition: opacity .2s, transform .1s; } .btn-primary:hover { opacity: .9; } .btn-primary:active { transform: scale(.98); } .btn-primary:disabled { opacity: .4; cursor: not-allowed; } |
| .btn-ghost { background: transparent; border: 1px solid var(--border); color: var(--muted); border-radius: 6px; padding: 6px 12px; cursor: pointer; font-size: 12px; transition: color .2s, border-color .2s; } .btn-ghost:hover { color: var(--text); border-color: var(--muted); } |
| .badge { display: inline-flex; align-items: center; gap: 4px; background: rgba(245,166,35,.12); border: 1px solid rgba(245,166,35,.3); color: var(--amber); border-radius: 20px; padding: 2px 10px; font-size: 11px; font-family: var(--mono); } .badge.green { background: rgba(61,220,132,.1); border-color: rgba(61,220,132,.3); color: var(--green); } .badge.red { background: rgba(255,82,82,.1); border-color: rgba(255,82,82,.3); color: var(--red); } |
| .waveform { display: flex; align-items: center; gap: 3px; height: 28px; } .waveform span { flex: 1; background: var(--amber); border-radius: 2px; animation: wave 1s ease-in-out infinite; opacity: .7; } @keyframes wave { 0%,100%{height:4px} 50%{height:24px} } .waveform span:nth-child(2){animation-delay:.1s} .waveform span:nth-child(3){animation-delay:.2s} .waveform span:nth-child(4){animation-delay:.3s} .waveform span:nth-child(5){animation-delay:.2s} .waveform span:nth-child(6){animation-delay:.1s} .waveform span:nth-child(7){animation-delay:.05s} |
| .tab { cursor:pointer; padding:8px 16px; border-radius:6px; font-size:13px; color:var(--muted); transition:all .2s; } .tab.active { background:rgba(245,166,35,.15); color:var(--amber); } .tab:hover:not(.active) { color:var(--text); } |
| audio { width:100%; accent-color:var(--amber); } audio::-webkit-media-controls-panel { background:var(--surface); } |
| .history-row { display:flex; align-items:center; gap:12px; padding:10px 14px; border-radius:8px; border:1px solid var(--border); background:var(--bg); transition:border-color .2s; } .history-row:hover { border-color: var(--amber-dim); } |
| .param-row { display:grid; grid-template-columns:140px 1fr 48px; align-items:center; gap:12px; } .param-label { font-size:12px; color:var(--muted); font-family:var(--mono); } .param-val { font-size:13px; color:var(--amber); font-family:var(--mono); text-align:right; } |
| .voice-card { padding:10px 14px; border-radius:8px; border:1px solid var(--border); background:var(--bg); cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:space-between; } .voice-card:hover { border-color:var(--amber-dim); } .voice-card.selected { border-color:var(--amber); background:rgba(245,166,35,.06); } |
| </style> |
| </head> |
| <body> |
| <div id="root"></div> |
| <script type="text/babel"> |
| const { useState, useEffect, useRef, useCallback } = React; |
| const device = "DEVICE_PLACEHOLDER"; |
| const fmt = v => parseFloat(v).toFixed(2); |
| const apiPost = (url, body) => fetch(url, { method:"POST", body }).then(r => { if (!r.ok) return r.json().then(e => { throw new Error(e.detail || "Server error"); }); return r.json(); }); |
| |
| function Slider({ label, min, max, step, value, onChange }) { |
| return ( <div className="param-row"><span className="param-label">{label}</span><input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(parseFloat(e.target.value))} /><span className="param-val">{fmt(value)}</span></div> ); |
| } |
| |
| function FileZone({ label, file, onFile }) { |
| const [active, setActive] = useState(false); |
| return ( <div><div className="tag mb-1">{label}</div><div className={`file-drop ${active?"active":""}`} onDragOver={e=>{e.preventDefault();setActive(true)}} onDragLeave={()=>setActive(false)} onDrop={e=>{e.preventDefault();setActive(false);onFile(e.dataTransfer.files[0]);}}> <input type="file" accept="audio/*" onChange={e=>onFile(e.target.files[0])} /> {file ? <span style={{color:"var(--green)",fontSize:12}}>✓ {file.name}</span> : <span style={{color:"var(--muted)",fontSize:12}}>اسحب ملفاً أو انقر</span>} </div></div> ); |
| } |
| |
| function WaveAnim() { return <div className="waveform">{[1,2,3,4,5,6,7].map(i=><span key={i}/>)}</div>; } |
| |
| function App() { |
| const [tab, setTab] = useState("generate"); |
| const [text, setText] = useState(""); const [lang, setLang] = useState("ar"); const [file1, setFile1] = useState(null); const [file2, setFile2] = useState(null); |
| const [temperature, setTemp] = useState(0.75); const [speed, setSpeed] = useState(1.0); const [topK, setTopK] = useState(50); const [topP, setTopP] = useState(0.85); const [repPenalty, setRepPenalty] = useState(5.0); const [splitText, setSplitText] = useState(true); |
| const [status, setStatus] = useState("idle"); const [statusMsg, setStatusMsg] = useState(""); const [audioUrl, setAudioUrl] = useState(null); const [audioFilename, setAudioFilename] = useState(null); |
| const [history, setHistory] = useState([]); const [voices, setVoices] = useState([]); const [selVoice, setSelVoice] = useState(null); const [saveName, setSaveName] = useState(""); const [saveStatus, setSaveStatus] = useState(""); |
| const languages = LANGUAGES_JSON; |
| |
| useEffect(() => { fetch("/history").then(r=>r.json()).then(setHistory).catch(()=>{}); fetch("/voices").then(r=>r.json()).then(setVoices).catch(()=>{}); }, []); |
| |
| const generate = async () => { |
| if (!text.trim()) return setStatusMsg("أدخل النص أولاً."); |
| if (!file1 && !selVoice) return setStatusMsg("يجب تحديد عينة صوتية أو اختيار صوت من المكتبة."); |
| setStatus("running"); setStatusMsg(""); setAudioUrl(null); |
| const fd = new FormData(); |
| fd.append("text", text); fd.append("language", lang); fd.append("temperature", temperature); fd.append("speed", speed); fd.append("top_k", topK); fd.append("top_p", topP); fd.append("repetition_penalty", repPenalty); fd.append("enable_text_splitting", splitText); |
| if (file1) fd.append("files", file1); if (file2) fd.append("files", file2); if (selVoice) fd.append("voice_name", selVoice); |
| try { const data = await apiPost("/generate", fd); setAudioUrl(`/audio/${data.filename}`); setAudioFilename(data.filename); setStatus("done"); fetch("/history").then(r=>r.json()).then(setHistory).catch(()=>{}); } catch(e) { setStatus("error"); setStatusMsg(e.message); } |
| }; |
| |
| const saveVoice = async () => { |
| if (!saveName.trim() || !file1) return; |
| const fd = new FormData(); fd.append("name", saveName.trim()); fd.append("file", file1); if (file2) fd.append("file2", file2); |
| try { await apiPost("/voices/save", fd); setSaveStatus("✓ تم الحفظ"); fetch("/voices").then(r=>r.json()).then(setVoices).catch(()=>{}); setTimeout(()=>setSaveStatus(""),2000); } catch(e) { setSaveStatus("خطأ: " + e.message); } |
| }; |
| |
| const deleteVoice = async name => { await fetch(`/voices/${name}`, {method:"DELETE"}); setVoices(v => v.filter(x=>x!==name)); if (selVoice===name) setSelVoice(null); }; |
| const isRTL = ["ar","fa","he","ur"].includes(lang); |
| |
| return ( |
| <div style={{maxWidth:720,margin:"0 auto",padding:"24px 16px",position:"relative",zIndex:1}}> |
| <div style={{marginBottom:28,textAlign:"center"}}> |
| <div className="tag" style={{marginBottom:6}}>XTTS V2 MULTILINGUAL</div> |
| <h1 style={{margin:0,fontSize:26,fontWeight:700,letterSpacing:"-.02em"}}><span className="amber">Voice</span> Studio</h1> |
| <div style={{marginTop:8,display:"flex",justifyContent:"center",gap:6}}><span className={`badge ${device==="cuda"?"green":"red"}`}>● {device.toUpperCase()}</span><span className="badge">HuggingFace Space</span></div> |
| </div> |
| <div style={{display:"flex",gap:4,marginBottom:20,background:"var(--surface)",border:"1px solid var(--border)",borderRadius:8,padding:4}}> |
| {["generate","library","history"].map(t=>( <div key={t} className={`tab${tab===t?" active":""}`} onClick={()=>setTab(t)} style={{flex:1,textAlign:"center"}}>{t==="generate"?"⚡ توليد":t==="library"?"📚 مكتبة الأصوات":"🕘 السجل"}</div> ))} |
| </div> |
| {tab==="generate" && ( |
| <div style={{display:"flex",flexDirection:"column",gap:14}}> |
| <div className="card" style={{padding:16}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:10}}><div className="tag">النص المراد تحويله</div><select value={lang} onChange={e=>setLang(e.target.value)}>{Object.entries(languages).map(([k,v])=><option key={k} value={k}>{v}</option>)}</select></div><textarea dir={isRTL?"rtl":"ltr"} rows={5} placeholder={isRTL?"أدخل النص هنا…":"Enter text here…"} value={text} onChange={e=>setText(e.target.value)} /></div> |
| <div className="card" style={{padding:16}}><div className="tag" style={{marginBottom:10}}>المرجع الصوتي</div><div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}><FileZone label="عينة 1 (مطلوبة)" file={file1} onFile={setFile1} /><FileZone label="عينة 2 (اختيارية)" file={file2} onFile={setFile2} /></div> |
| {voices.length>0 && ( <div style={{marginTop:12}}><div className="tag" style={{marginBottom:8}}>أو من المكتبة</div><div style={{display:"flex",flexWrap:"wrap",gap:8}}>{voices.map(v=>( <div key={v} style={{padding:"6px 14px",borderRadius:20,cursor:"pointer",fontSize:12,border:"1px solid",borderColor:selVoice===v?"var(--amber)":"var(--border)",color:selVoice===v?"var(--amber)":"var(--muted)",background:selVoice===v?"rgba(245,166,35,.08)":"transparent",transition:"all .2s"}} onClick={()=>setSelVoice(selVoice===v?null:v)}>{v}</div> ))}</div></div> )} |
| {file1 && ( <div style={{marginTop:12,display:"flex",gap:8,alignItems:"center"}}><input type="text" placeholder="اسم الصوت للحفظ…" value={saveName} onChange={e=>setSaveName(e.target.value)} style={{flex:1,background:"var(--bg)",border:"1px solid var(--border)",color:"var(--text)",borderRadius:6,padding:"6px 10px",fontSize:12,fontFamily:"var(--sans)",outline:"none"}} /><button className="btn-ghost" onClick={saveVoice} style={{whiteSpace:"nowrap"}}>حفظ في المكتبة</button>{saveStatus && <span style={{fontSize:12,color:"var(--green)"}}>{saveStatus}</span>}</div> )} |
| </div> |
| <div className="card" style={{padding:16}}><details><summary style={{cursor:"pointer",listStyle:"none",display:"flex",justifyContent:"space-between",alignItems:"center",userSelect:"none"}}><div className="tag">المعاملات المتقدمة</div><span style={{fontSize:11,color:"var(--muted)"}}>انقر للتوسيع ▾</span></summary><div style={{marginTop:14,display:"flex",flexDirection:"column",gap:14}}><Slider label="temperature" min={0.05} max={1.0} step={0.05} value={temperature} onChange={setTemp} /><Slider label="speed" min={0.5} max={2.0} step={0.05} value={speed} onChange={setSpeed} /><Slider label="top_k" min={1} max={100} step={1} value={topK} onChange={setTopK} /><Slider label="top_p" min={0.1} max={1.0} step={0.05} value={topP} onChange={setTopP} /><Slider label="rep_penalty" min={1.0} max={10.0} step={0.5} value={repPenalty} onChange={setRepPenalty} /></div></details></div> |
| {statusMsg && <div style={{padding:"10px 14px",borderRadius:8,fontSize:13,background:"rgba(255,82,82,.08)",border:"1px solid rgba(255,82,82,.3)",color:"var(--red)"}}>{statusMsg}</div>} |
| <button className="btn-primary" onClick={generate} disabled={status==="running"}>{status==="running" ? <span style={{display:"flex",alignItems:"center",justifyContent:"center",gap:10}}><WaveAnim/> جاري التوليد…</span> : "⚡ توليد الصوت"}</button> |
| {audioUrl && ( <div className="card" style={{padding:16}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12}}><div style={{display:"flex",alignItems:"center",gap:8}}><span className="badge green">✓ تم التوليد</span></div><a href={audioUrl} download={audioFilename} style={{textDecoration:"none"}}><button className="btn-ghost">⬇ تحميل</button></a></div><audio src={audioUrl} controls autoPlay /></div> )} |
| </div> |
| )} |
| {tab==="library" && ( |
| <div style={{display:"flex",flexDirection:"column",gap:12}}> |
| <div className="card" style={{padding:16}}><div className="tag" style={{marginBottom:8}}>إضافة صوت جديد للمكتبة</div><div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12}}><FileZone label="عينة 1" file={file1} onFile={setFile1} /><FileZone label="عينة 2 (اختياري)" file={file2} onFile={setFile2} /></div><div style={{display:"flex",gap:8}}><input type="text" placeholder="اسم الصوت…" value={saveName} onChange={e=>setSaveName(e.target.value)} style={{flex:1,background:"var(--bg)",border:"1px solid var(--border)",color:"var(--text)",borderRadius:6,padding:"8px 12px",fontSize:13,fontFamily:"var(--sans)",outline:"none"}} /><button className="btn-primary" style={{width:"auto",padding:"8px 20px"}} onClick={saveVoice}>حفظ</button></div>{saveStatus && <div style={{marginTop:8,fontSize:12,color:"var(--green)"}}>{saveStatus}</div>}</div> |
| {voices.length===0 ? <div style={{textAlign:"center",color:"var(--muted)",padding:"40px 0",fontSize:14}}>لا توجد أصوات محفوظة بعد.</div> : voices.map(v=>( <div key={v} className="voice-card" onClick={()=>{setSelVoice(selVoice===v?null:v);setTab("generate");}}><div><div style={{fontSize:14,fontWeight:600}}>{v}</div><div style={{fontSize:11,color:"var(--muted)",marginTop:2,fontFamily:"var(--mono)"}}>{selVoice===v?"● محدد":"انقر للاستخدام"}</div></div><button className="btn-ghost" onClick={e=>{e.stopPropagation();deleteVoice(v);}}>حذف</button></div> ))} |
| </div> |
| )} |
| {tab==="history" && ( |
| <div style={{display:"flex",flexDirection:"column",gap:10}}> |
| {history.length===0 ? <div style={{textAlign:"center",color:"var(--muted)",padding:"40px 0",fontSize:14}}>السجل فارغ.</div> : [...history].reverse().map((h,i)=>( <div key={i} className="history-row"><div style={{flex:1,minWidth:0}}><div style={{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl"}}>{h.text}</div><div style={{display:"flex",gap:8,marginTop:4,flexWrap:"wrap"}}><span className="badge">{h.language}</span><span style={{fontSize:10,color:"var(--muted)",fontFamily:"var(--mono)"}}>{new Date(h.ts*1000).toLocaleString("ar-EG")}</span></div></div><div style={{display:"flex",gap:6,flexShrink:0}}><button className="btn-ghost" onClick={()=>{setAudioUrl(`/audio/${h.filename}`);setAudioFilename(h.filename);setTab("generate");setStatus("done");}}></button><a href={`/audio/${h.filename}`} download={h.filename} style={{textDecoration:"none"}}><button className="btn-ghost">⬇</button></a></div></div> ))} |
| </div> |
| )} |
| </div> |
| ); |
| } |
| ReactDOM.createRoot(document.getElementById("root")).render(<App/>); |
| </script> |
| </body> |
| </html> |
| """ |
|
|
| |
| |
| |
|
|
| @app.get("/", response_class=HTMLResponse) |
| async def ui(): |
| page = ( |
| HTML |
| .replace("LANGUAGES_JSON", json.dumps(LANGUAGES, ensure_ascii=False)) |
| .replace("DEVICE_PLACEHOLDER", device) |
| ) |
| return page |
|
|
|
|
| @app.post("/generate") |
| async def generate( |
| text: str = Form(...), |
| language: str = Form("ar"), |
| temperature: float = Form(0.75), |
| speed: float = Form(1.0), |
| top_k: int = Form(50), |
| top_p: float = Form(0.85), |
| repetition_penalty: float = Form(5.0), |
| enable_text_splitting: bool = Form(True), |
| voice_name: str = Form(None), |
| files: list[UploadFile] = File(default=[]), |
| ): |
| if not text.strip(): |
| raise HTTPException(400, "النص فارغ.") |
|
|
| ref_paths, tmp_files = [], [] |
| for f in files: |
| path = f"/tmp/ref_{uuid.uuid4().hex}_{f.filename}" |
| with open(path, "wb") as buf: |
| shutil.copyfileobj(f.file, buf) |
| ref_paths.append(path) |
| tmp_files.append(path) |
|
|
| if voice_name: |
| lib_dir = os.path.join(VOICE_LIB, voice_name) |
| if os.path.isdir(lib_dir): |
| ref_paths += [ |
| os.path.join(lib_dir, fn) |
| for fn in os.listdir(lib_dir) |
| if fn.lower().endswith((".wav", ".mp3", ".flac", ".ogg")) |
| ] |
|
|
| if not ref_paths: |
| raise HTTPException(400, "يجب تحديد عينة صوتية مرجعية.") |
|
|
| out_name = f"gen_{uuid.uuid4().hex[:8]}.wav" |
| out_path = os.path.join(OUTPUT_DIR, out_name) |
|
|
| try: |
| xtts_engine.tts_to_file( |
| text=text, |
| speaker_wav=ref_paths, |
| language=language, |
| file_path=out_path, |
| temperature=float(temperature), |
| speed=float(speed), |
| top_k=int(top_k), |
| top_p=float(top_p), |
| repetition_penalty=float(repetition_penalty), |
| enable_text_splitting=bool(enable_text_splitting), |
| ) |
| finally: |
| for p in tmp_files: |
| try: |
| os.remove(p) |
| except Exception: |
| pass |
|
|
| hist = load_history() |
| hist.append({"filename": out_name, "text": text[:120], "language": language, "ts": int(time.time())}) |
| save_history(hist) |
| return {"filename": out_name} |
|
|
|
|
| @app.get("/audio/{filename}") |
| def get_audio(filename: str): |
| path = os.path.join(OUTPUT_DIR, filename) |
| if not os.path.exists(path): |
| raise HTTPException(404, "File not found.") |
| return FileResponse(path, media_type="audio/wav") |
|
|
|
|
| @app.get("/history") |
| def get_history(): |
| return JSONResponse(load_history()) |
|
|
|
|
| @app.get("/voices") |
| def list_voices(): |
| if not os.path.isdir(VOICE_LIB): |
| return [] |
| return [d for d in os.listdir(VOICE_LIB) if os.path.isdir(os.path.join(VOICE_LIB, d))] |
|
|
|
|
| @app.post("/voices/save") |
| async def save_voice( |
| name: str = Form(...), |
| file: UploadFile = File(...), |
| file2: UploadFile = File(default=None), |
| ): |
| safe = name.strip().replace("/", "_").replace("..", "_") |
| lib_dir = os.path.join(VOICE_LIB, safe) |
| os.makedirs(lib_dir, exist_ok=True) |
| for f in ([file, file2] if file2 else [file]): |
| with open(os.path.join(lib_dir, f.filename), "wb") as buf: |
| shutil.copyfileobj(f.file, buf) |
| return {"name": safe} |
|
|
|
|
| @app.delete("/voices/{name}") |
| def delete_voice(name: str): |
| lib_dir = os.path.join(VOICE_LIB, name) |
| if os.path.isdir(lib_dir): |
| shutil.rmtree(lib_dir) |
| return {"deleted": name} |
|
|
|
|
| |
| |
| |
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info") |
|
|