l
File size: 25,780 Bytes
2dbc437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
# โ•‘          XTTS v2 Advanced Voice Studio โ€” HuggingFace Space       โ•‘
# โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

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

# โ”€โ”€ Env โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
os.environ["COQUI_TOS_AGREED"] = "1"
# Point HF cache to a writable directory inside the Space
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)

# โ”€โ”€ Load TTS on CPU โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
from TTS.api import TTS

# HF Spaces free tier is CPU-only; force CPU explicitly
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.")

# โ”€โ”€ History helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
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)

# โ”€โ”€ FastAPI app โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
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 / React Frontend
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
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>
"""

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# Routes
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

@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}


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# Entry point (used by Dockerfile CMD)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")