Arabi32 commited on
Commit
de85899
ยท
verified ยท
1 Parent(s): ea9485d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +253 -0
app.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import json
4
+ import uuid
5
+ import shutil
6
+ import uvicorn
7
+ from fastapi import FastAPI, Form, File, UploadFile, HTTPException
8
+ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ import torch
11
+ from TTS.api import TTS
12
+
13
+ # โ”€โ”€ Env Configuration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
14
+ os.environ["COQUI_TOS_AGREED"] = "1"
15
+ VOICE_LIB = "voice_library"
16
+ OUTPUT_DIR = "outputs"
17
+ HISTORY_FILE = "history.json"
18
+
19
+ for d in [VOICE_LIB, OUTPUT_DIR]:
20
+ os.makedirs(d, exist_ok=True)
21
+
22
+ # โ”€โ”€ Load TTS Model โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
23
+ device = "cuda" if torch.cuda.is_available() else "cpu"
24
+ print(f"[*] Loading XTTS v2 on {device.upper()}...")
25
+ xtts_engine = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device)
26
+ print("[โœ“] Model Ready.")
27
+
28
+ # โ”€โ”€ History helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
29
+ def load_history():
30
+ if os.path.exists(HISTORY_FILE):
31
+ try: return json.load(open(HISTORY_FILE))
32
+ except: pass
33
+ return []
34
+
35
+ def save_history(h):
36
+ json.dump(h, open(HISTORY_FILE, "w"), ensure_ascii=False, indent=2)
37
+
38
+ # โ”€โ”€ FastAPI app โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
39
+ app = FastAPI(title="XTTS Studio")
40
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
41
+
42
+ LANGUAGES = {
43
+ "ar": "ุงู„ุนุฑุจูŠุฉ", "en": "English", "es": "Espaรฑol", "fr": "Franรงais",
44
+ "de": "Deutsch", "it": "Italiano", "pt": "Portuguรชs","ru": "ะ ัƒััะบะธะน",
45
+ "zh-cn": "ไธญๆ–‡", "ja": "ๆ—ฅๆœฌ่ชž", "ko": "ํ•œ๊ตญ์–ด", "tr": "Tรผrkรงe",
46
+ "nl": "Nederlands","pl": "Polski", "cs": "ฤŒeลกtina", "hi": "เคนเคฟเคจเฅเคฆเฅ€",
47
+ }
48
+
49
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
50
+ # HTML / React Frontend
51
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
52
+ HTML = r"""<!DOCTYPE html>
53
+ <html lang="ar" dir="rtl">
54
+ <head>
55
+ <meta charset="UTF-8">
56
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
57
+ <title>XTTS Voice Studio</title>
58
+ <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">
59
+ <script src="https://cdn.tailwindcss.com"></script>
60
+ <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
61
+ <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
62
+ <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
63
+ <style>
64
+ :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; }
65
+ * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--text); font-family: var(--sans); min-height: 100vh; }
66
+ ::-webkit-scrollbar { width: 5px; } ::-webkit-scrollbar-track { background: var(--surface); } ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
67
+ 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); }
68
+ .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); }
69
+ 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); }
70
+ 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); }
71
+ .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; }
72
+ .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; }
73
+ .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); }
74
+ .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); }
75
+ .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}
76
+ .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); }
77
+ audio { width:100%; accent-color:var(--amber); } audio::-webkit-media-controls-panel { background:var(--surface); }
78
+ .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); }
79
+ .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; }
80
+ .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); }
81
+ </style>
82
+ </head>
83
+ <body>
84
+ <div id="root"></div>
85
+ <script type="text/babel">
86
+ const { useState, useEffect, useRef, useCallback } = React;
87
+ const fmt = v => parseFloat(v).toFixed(2);
88
+ 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(); });
89
+
90
+ function Slider({ label, min, max, step, value, onChange }) {
91
+ 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> );
92
+ }
93
+
94
+ function FileZone({ label, file, onFile }) {
95
+ const [active, setActive] = useState(false);
96
+ 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> );
97
+ }
98
+
99
+ function WaveAnim() { return <div className="waveform">{[1,2,3,4,5,6,7].map(i=><span key={i}/>)}</div>; }
100
+
101
+ function App() {
102
+ const [tab, setTab] = useState("generate");
103
+ const [text, setText] = useState(""); const [lang, setLang] = useState("ar"); const [file1, setFile1] = useState(null); const [file2, setFile2] = useState(null);
104
+ 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);
105
+ const [status, setStatus] = useState("idle"); const [statusMsg, setStatusMsg] = useState(""); const [audioUrl, setAudioUrl] = useState(null); const [audioFilename, setAudioFilename] = useState(null);
106
+ const [history, setHistory] = useState([]); const [voices, setVoices] = useState([]); const [selVoice, setSelVoice] = useState(null); const [saveName, setSaveName] = useState(""); const [saveStatus, setSaveStatus] = useState("");
107
+ const languages = LANGUAGES_JSON;
108
+
109
+ useEffect(() => { fetch("/history").then(r=>r.json()).then(setHistory).catch(()=>{}); fetch("/voices").then(r=>r.json()).then(setVoices).catch(()=>{}); }, []);
110
+
111
+ const generate = async () => {
112
+ if (!text.trim()) return setStatusMsg("ุฃุฏุฎู„ ุงู„ู†ุต ุฃูˆู„ุงู‹.");
113
+ if (!file1 && !selVoice) return setStatusMsg("ูŠุฌุจ ุชุญุฏูŠุฏ ุนูŠู†ุฉ ุตูˆุชูŠุฉ ุฃูˆ ุงุฎุชูŠุงุฑ ุตูˆุช ู…ู† ุงู„ู…ูƒุชุจุฉ.");
114
+ setStatus("running"); setStatusMsg(""); setAudioUrl(null);
115
+ const fd = new FormData();
116
+ 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);
117
+ if (file1) fd.append("files", file1); if (file2) fd.append("files", file2); if (selVoice) fd.append("voice_name", selVoice);
118
+ 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); }
119
+ };
120
+
121
+ const saveVoice = async () => {
122
+ if (!saveName.trim() || !file1) return;
123
+ const fd = new FormData(); fd.append("name", saveName.trim()); fd.append("file", file1); if (file2) fd.append("file2", file2);
124
+ try { await apiPost("/voices/save", fd); setSaveStatus("โœ“ ุชู… ุงู„ุญูุธ"); fetch("/voices").then(r=>r.json()).then(setVoices).catch(()=>{}); setTimeout(()=>setSaveStatus(""),2000); } catch(e) { setSaveStatus("ุฎุทุฃ: " + e.message); }
125
+ };
126
+
127
+ const deleteVoice = async name => { await fetch(`/voices/${name}`, {method:"DELETE"}); setVoices(v => v.filter(x=>x!==name)); if (selVoice===name) setSelVoice(null); };
128
+ const isRTL = ["ar","fa","he","ur"].includes(lang);
129
+
130
+ return (
131
+ <div style={{maxWidth:720,margin:"0 auto",padding:"24px 16px",position:"relative",zIndex:1}}>
132
+ <div style={{marginBottom:28,textAlign:"center"}}>
133
+ <div className="tag" style={{marginBottom:6}}>XTTS V2 MULTILINGUAL</div>
134
+ <h1 style={{margin:0,fontSize:26,fontWeight:700,letterSpacing:"-.02em"}}><span className="amber">Voice</span> Studio</h1>
135
+ <div style={{marginTop:8,display:"flex",justifyContent:"center",gap:6}}><span className={`badge ${DEVICE_VAR==="cuda"?"green":"red"}`}>โ— {DEVICE_VAR.toUpperCase()}</span><span className="badge">HF Space</span></div>
136
+ </div>
137
+ <div style={{display:"flex",gap:4,marginBottom:20,background:"var(--surface)",border:"1px solid var(--border)",borderRadius:8,padding:4}}>
138
+ {["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> ))}
139
+ </div>
140
+ {tab==="generate" && (
141
+ <div style={{display:"flex",flexDirection:"column",gap:14}}>
142
+ <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>
143
+ <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>
144
+ {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> )}
145
+ {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> )}
146
+ </div>
147
+ <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>
148
+ {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>}
149
+ <button className="btn-primary" onClick={generate} disabled={status==="running"}>{status==="running" ? <span style={{display:"flex",alignItems:"center",justifyContent:"center",gap:10}}><WaveAnim/> ุฌุงุฑูŠ ุงู„ุชูˆู„ูŠุฏโ€ฆ</span> : "โšก ุชูˆู„ูŠุฏ ุงู„ุตูˆุช"}</button>
150
+ {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> )}
151
+ </div>
152
+ )}
153
+ {tab==="library" && (
154
+ <div style={{display:"flex",flexDirection:"column",gap:12}}>
155
+ <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>
156
+ {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> ))}
157
+ </div>
158
+ )}
159
+ {tab==="history" && (
160
+ <div style={{display:"flex",flexDirection:"column",gap:10}}>
161
+ {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> ))}
162
+ </div>
163
+ )}
164
+ </div>
165
+ );
166
+ }
167
+ ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
168
+ </script>
169
+ </body>
170
+ </html>
171
+ """
172
+
173
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
174
+ # Routes
175
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
176
+
177
+ @app.get("/", response_class=HTMLResponse)
178
+ async def ui():
179
+ # ุชู…ุฑูŠุฑ ุงู„ู…ุชุบูŠุฑุงุช ู„ุฏุงุฎู„ React
180
+ page = HTML.replace("LANGUAGES_JSON", json.dumps(LANGUAGES, ensure_ascii=False))
181
+ page = page.replace('DEVICE_VAR', f'"{device}"')
182
+ return page
183
+
184
+ @app.post("/generate")
185
+ 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=[])):
186
+ if not text.strip(): raise HTTPException(400, "ุงู„ู†ุต ูุงุฑุบ.")
187
+
188
+ ref_paths, tmp_files = [], []
189
+ for f in files:
190
+ if f.filename:
191
+ path = f"tmp_ref_{uuid.uuid4().hex}_{f.filename}"
192
+ with open(path, "wb") as buf: shutil.copyfileobj(f.file, buf)
193
+ ref_paths.append(path); tmp_files.append(path)
194
+
195
+ if voice_name:
196
+ lib_dir = os.path.join(VOICE_LIB, voice_name)
197
+ if os.path.isdir(lib_dir):
198
+ ref_paths += [os.path.join(lib_dir, fn) for fn in os.listdir(lib_dir) if fn.lower().endswith((".wav",".mp3",".flac",".ogg"))]
199
+
200
+ if not ref_paths:
201
+ raise HTTPException(400, "ูŠุฌุจ ุชุญุฏูŠุฏ ุนูŠู†ุฉ ุตูˆุชูŠุฉ ู…ุฑุฌุนูŠุฉ.")
202
+
203
+ out_name = f"gen_{uuid.uuid4().hex[:8]}.wav"
204
+ out_path = os.path.join(OUTPUT_DIR, out_name)
205
+
206
+ try:
207
+ xtts_engine.tts_to_file(
208
+ text=text, speaker_wav=ref_paths, language=language, file_path=out_path,
209
+ temperature=float(temperature), speed=float(speed), top_k=int(top_k),
210
+ top_p=float(top_p), repetition_penalty=float(repetition_penalty),
211
+ enable_text_splitting=bool(enable_text_splitting)
212
+ )
213
+ finally:
214
+ for p in tmp_files:
215
+ try: os.remove(p)
216
+ except: pass
217
+
218
+ hist = load_history()
219
+ hist.append({"filename": out_name, "text": text[:120], "language": language, "ts": int(time.time())})
220
+ save_history(hist)
221
+ return {"filename": out_name}
222
+
223
+ @app.get("/audio/{filename}")
224
+ def get_audio(filename: str):
225
+ path = os.path.join(OUTPUT_DIR, filename)
226
+ if not os.path.exists(path): raise HTTPException(404, "File not found.")
227
+ return FileResponse(path, media_type="audio/wav")
228
+
229
+ @app.get("/history")
230
+ def get_history():
231
+ return JSONResponse(load_history())
232
+
233
+ @app.get("/voices")
234
+ def list_voices():
235
+ if not os.path.isdir(VOICE_LIB): return []
236
+ return [d for d in os.listdir(VOICE_LIB) if os.path.isdir(os.path.join(VOICE_LIB, d))]
237
+
238
+ @app.post("/voices/save")
239
+ async def save_voice(name: str = Form(...), file: UploadFile = File(...), file2: UploadFile = File(default=None)):
240
+ safe = name.strip().replace("/", "_").replace("..", "_")
241
+ lib_dir = os.path.join(VOICE_LIB, safe)
242
+ os.makedirs(lib_dir, exist_ok=True)
243
+
244
+ for f in ([file, file2] if file2.filename else [file]):
245
+ if f.filename:
246
+ with open(os.path.join(lib_dir, f.filename), "wb") as buf: shutil.copyfileobj(f.file, buf)
247
+ return {"name": safe}
248
+
249
+ @app.delete("/voices/{name}")
250
+ def delete_voice(name: str):
251
+ lib_dir = os.path.join(VOICE_LIB, name)
252
+ if os.path.isdir(lib_dir): shutil.rmtree(lib_dir)
253
+ return {"deleted": name}