Update index.html
Browse files- index.html +680 -400
index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
| 6 |
<meta name="color-scheme" content="dark light">
|
| 7 |
-
<title>AI Studio
|
| 8 |
<style>
|
| 9 |
:root,[data-theme=dark]{--bg:#0f1115;--s1:#171a21;--s2:#1f232c;--s3:#2a2f3a;--bd:#2c313c;--tx:#eceef2;--mu:#8f97a6;--ac:#e06f4f;--ok:#4ade80;--er:#fb7185;--wr:#fbbf24;--code:#0a0c10;color-scheme:dark}
|
| 10 |
[data-theme=light]{--bg:#f6f6f3;--s1:#fff;--s2:#f0efeb;--s3:#e5e3dd;--bd:#dad8d1;--tx:#1f201e;--mu:#6f726b;--ac:#cc6748;--ok:#16a34a;--er:#dc2626;--wr:#d97706;--code:#f4f4f0;color-scheme:light}
|
|
@@ -16,7 +16,6 @@ button{cursor:pointer;-webkit-tap-highlight-color:transparent}
|
|
| 16 |
::-webkit-scrollbar{width:7px;height:7px}::-webkit-scrollbar-thumb{background:var(--s3);border-radius:9px}
|
| 17 |
.ib,.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px}
|
| 18 |
#snd,#stp{align-items:center;justify-content:center}
|
| 19 |
-
i[data-i]{display:inline-flex;vertical-align:middle;font-style:normal}
|
| 20 |
.ib{width:36px;height:36px;border:1px solid transparent;border-radius:10px;background:none;color:var(--mu);flex:none}
|
| 21 |
.ib:hover{background:var(--s2);border-color:var(--bd);color:var(--tx)}
|
| 22 |
.btn{padding:10px 16px;border:0;border-radius:11px;background:var(--ac);color:#fff;font-weight:600;font-size:13px}
|
|
@@ -104,6 +103,8 @@ code.in{background:var(--s2);padding:1px 6px;border-radius:6px;font-size:.9em;di
|
|
| 104 |
.fd input,.fd select,.fd textarea{width:100%;padding:9px 11px;border-radius:10px;border:1px solid var(--bd);background:var(--s2);font-size:13px}
|
| 105 |
.fd textarea{resize:vertical;min-height:70px}
|
| 106 |
.g3{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
|
|
|
|
|
|
|
| 107 |
#cp{position:fixed;top:0;left:0;bottom:0;width:55vw;max-width:100vw;background:var(--s1);border-right:1px solid var(--bd);display:none;flex-direction:column;z-index:80}
|
| 108 |
#cp.open{display:flex}
|
| 109 |
#cp.full{width:100vw}
|
|
@@ -125,49 +126,51 @@ code.in{background:var(--s2);padding:1px 6px;border-radius:6px;font-size:.9em;di
|
|
| 125 |
<body>
|
| 126 |
<div id="ov" onclick="closeAll()"></div>
|
| 127 |
<aside id="sb">
|
| 128 |
-
<div class="top"><button class="btn" onclick="newChat()">
|
| 129 |
<div id="ss"></div>
|
| 130 |
-
<div class="ft"><span>محفوظة محلياً</span><button class="ib" id="thb" onclick="toggleTheme()"></button></div>
|
| 131 |
</aside>
|
| 132 |
<main>
|
| 133 |
<div id="tb">
|
| 134 |
-
<button class="ib" id="hb" onclick="event.stopPropagation();toggleSb()"><
|
| 135 |
<select id="mp" onchange="onModelChange()"></select>
|
| 136 |
<div class="sp"></div>
|
| 137 |
<div class="pill"><span class="led" id="led"></span><span id="ledT">جاهز</span></div>
|
| 138 |
-
<button class="ib" id="loadBtn" onclick="doLoad()" title="تحميل النموذج"><
|
| 139 |
-
<button class="ib" onclick="doUnload()" title="تفريغ النموذج"><
|
| 140 |
<button class="ib" id="spk" onclick="toggleAuto()" title="النطق التلقائي"></button>
|
| 141 |
-
<button class="ib" onclick="openDiag()" title="التشخيص"><
|
| 142 |
-
<button class="ib" onclick="openSet()" title="الإعدادات"><
|
| 143 |
-
<button class="ib" onclick="exportChat()" title="تصدير"><
|
| 144 |
-
<button class="ib" onclick="clearChat()" title="مسح"><
|
| 145 |
</div>
|
| 146 |
<div id="chat"><div id="ci"></div></div>
|
| 147 |
<div id="cmp"><div class="in">
|
| 148 |
<div id="chips"></div>
|
| 149 |
<textarea id="inp" rows="1" placeholder="اكتب رسالتك..." onkeydown="if(event.key==='Enter'&&!event.shiftKey&&!event.isComposing){event.preventDefault();sendMsg()}"></textarea>
|
| 150 |
<div class="cr">
|
| 151 |
-
<div id="pw"><button class="ib" style="font-size:20px;border:1px solid var(--bd)" onclick="event.stopPropagation();$('pp').classList.toggle('open')"><
|
| 152 |
<div id="pp" onclick="event.stopPropagation()"><div class="sc">
|
| 153 |
-
<button class="pi" onclick="$('fi').click();closeAll()">
|
| 154 |
</div></div>
|
| 155 |
</div>
|
| 156 |
-
<button class="ib" id="mic" onclick="toggleMic()" title="تفريغ صوتي"><
|
| 157 |
-
<button class="ib" id="vcb" onclick="startVoice()" title="محادثة صوتية"><
|
| 158 |
<div class="sp"></div>
|
| 159 |
-
<button id="stp" onclick="stopGen()"><
|
| 160 |
</div>
|
| 161 |
</div></div>
|
| 162 |
</main>
|
| 163 |
<input type="file" id="fi" multiple hidden onchange="addFiles(this.files)">
|
| 164 |
<div id="cp" data-v="code">
|
| 165 |
<div class="cph">
|
| 166 |
-
<button class="ib" onclick="closePanel()"><
|
| 167 |
<div class="tabs"><button data-v="code" class="on" onclick="setView('code')">الكود</button><button data-v="preview" onclick="setView('preview')">معاينة</button><button data-v="split" onclick="setView('split')">مقسّم</button></div>
|
| 168 |
-
<button class="ib" onclick="reloadPrev()" title="تحديث"><
|
| 169 |
-
<button class="ib" onclick="
|
| 170 |
-
<button class="ib" onclick="
|
|
|
|
|
|
|
| 171 |
</div>
|
| 172 |
<div class="cpb">
|
| 173 |
<div class="cv"><iframe id="cf" sandbox="allow-scripts allow-modals allow-forms allow-popups"></iframe><div id="pe" onclick="this.style.display='none'"></div></div>
|
|
@@ -175,381 +178,520 @@ code.in{background:var(--s2);padding:1px 6px;border-radius:6px;font-size:.9em;di
|
|
| 175 |
</div>
|
| 176 |
</div>
|
| 177 |
<div id="vc">
|
| 178 |
-
<button class="ib vx" onclick="endVoice()"
|
| 179 |
<div class="vm"><div id="orb" onclick="vTap()"><i></i><i></i><i></i></div><div id="vS"></div><div id="vT"></div><div id="vR"></div></div>
|
| 180 |
-
<div class="vb"><button class="ib" id="vMute" onclick="vMuteTog()"
|
| 181 |
</div>
|
| 182 |
<div id="toasts"></div>
|
| 183 |
|
| 184 |
<div id="set" class="md" onclick="if(event.target===this)this.classList.remove('open')"><div class="card">
|
| 185 |
-
<h2>الإعدادات <button class="ib" onclick="$('set').classList.remove('open')"><
|
| 186 |
<div class="sec"><b>🧠 تعليمات النظام</b><div class="fd"><textarea id="cSys" placeholder="You are a helpful assistant..."></textarea></div></div>
|
| 187 |
<div class="sec"><b>🎛 التوليد</b><div class="g3">
|
| 188 |
<div class="fd"><label>Temperature</label><input id="cTemp" type="number" step="0.1" min="0" max="2"></div>
|
| 189 |
-
<div class="fd"><label>Max Tokens</label><input id="cMax" type="number" min="32" max="32000"></div>
|
| 190 |
<div class="fd"><label>Top P</label><input id="cTop" type="number" step="0.05" min="0" max="1"></div></div>
|
| 191 |
-
<div class="fd"><label>Max Tokens: <b id="mMax">256</b></label><input id="cMaxRange" type="range" min="32" max="32000" step="32"></div>
|
| 192 |
-
<div class="fd"><label>تجميع أولي قبل البث: <b id="rChunk">8</b> توكنات</label><input id="cChunk" type="range" min="0" max="30" step="1"></div>
|
| 193 |
</div>
|
| 194 |
<div class="sec"><b>🔊 النطق (إخراج الصوت)</b>
|
| 195 |
-
<div class="fd"><label>سرعة النطق: <b id="rV">1.5</b>×</label><input id="cRate" type="range" min="0.8" max="2" step="0.1"></div>
|
| 196 |
<div class="fd"><label>صوت النطق</label><select id="cVoice"></select></div>
|
| 197 |
<div class="fd"><label><input type="checkbox" id="cAutoSpeak"> النطق التلقائي لكل رد</label></div>
|
| 198 |
<button class="btn g" style="width:100%" onclick="testVoice()">🔊 اختبار الصوت</button>
|
| 199 |
</div>
|
| 200 |
<div class="sec"><b>🎤 التفريغ الصوتي</b>
|
| 201 |
<div class="fd"><label>اللغة</label><select id="cStt">
|
| 202 |
-
<option value="ar-SA">العربية (الفصحى)</option>
|
| 203 |
-
<option value="
|
|
|
|
|
|
|
|
|
|
| 204 |
</select></div>
|
| 205 |
</div>
|
| 206 |
<button class="btn" style="width:100%" onclick="saveSet()">💾 حفظ</button>
|
| 207 |
</div></div>
|
| 208 |
|
| 209 |
<div id="dg" class="md" onclick="if(event.target===this)this.classList.remove('open')"><div class="card">
|
| 210 |
-
<h2>🩺 التشخيص <span><button class="btn g" style="padding:6px 11px;font-size:11px" onclick="copyDiag()">نسخ</button> <button class="ib" onclick="$('dg').classList.remove('open')"><
|
| 211 |
<pre id="diagB" style="direction:ltr;text-align:left;white-space:pre-wrap;font-size:11px;color:var(--mu);max-height:300px;overflow:auto;background:var(--code);border-radius:8px;padding:8px"></pre>
|
| 212 |
</div></div>
|
| 213 |
|
| 214 |
<script>
|
| 215 |
-
const LS = "ai_studio_v4";
|
| 216 |
const $ = i => document.getElementById(i);
|
| 217 |
-
const
|
|
|
|
|
|
|
|
|
|
| 218 |
const hash = s => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0; return h.toString(36); };
|
| 219 |
-
const J = o => JSON.stringify(o);
|
| 220 |
-
const uid = () => (crypto.randomUUID ? crypto.randomUUID() : 'id' + Date.now() + Math.random().toString(36).slice(2));
|
| 221 |
-
const IC = {
|
| 222 |
-
x: '<path d="M18 6 6 18M6 6l12 12"/>', plus: '<path d="M12 5v14M5 12h14"/>', menu: '<path d="M4 6h16M4 12h16M4 18h16"/>',
|
| 223 |
-
mic: '<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"/>',
|
| 224 |
-
wave: '<path d="M4 10v4M8 6v12M12 3v18M16 8v8M20 11v2"/>', send: '<path d="M12 19V5M5 12l7-7 7 7"/>',
|
| 225 |
-
stop: '<rect x="6" y="6" width="12" height="12" rx="2" fill="currentColor"/>',
|
| 226 |
-
set: '<path d="M4 6h10M18 6h2M4 12h2M10 12h10M4 18h12M20 18h0"/><circle cx="16" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="18" cy="18" r="2"/>',
|
| 227 |
-
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
|
| 228 |
-
moon: '<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z"/>',
|
| 229 |
-
spk: '<path d="M11 5 6 9H3v6h3l5 4V5Z"/><path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13"/>',
|
| 230 |
-
spkoff: '<path d="M11 5 6 9H3v6h3l5 4V5Z"/><path d="M22 9l-6 6M16 9l6 6"/>',
|
| 231 |
-
refresh: '<path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/>',
|
| 232 |
-
ext: '<path d="M7 17 17 7M8 7h9v9"/>', copy: '<rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>',
|
| 233 |
-
down: '<path d="M12 4v12M6 11l6 6 6-6M5 21h14"/>', full: '<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>',
|
| 234 |
-
pulse: '<path d="M3 12h4l3-8 4 16 3-8h4"/>', clip: '<path d="m21 12-8.5 8.5a5.5 5.5 0 0 1-7.8-7.8L13.5 4a3.7 3.7 0 0 1 5.3 5.3l-8.5 8.5a1.8 1.8 0 0 1-2.6-2.6L15 7"/>',
|
| 235 |
-
chat: '<path d="M21 12a8 8 0 0 1-11.6 7.1L3 21l1.9-5.4A8 8 0 1 1 21 12Z"/>', trash: '<path d="M3 6h18M8 6V4h8v2M6 6l1 15h10l1-15"/>',
|
| 236 |
-
file: '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z"/><path d="M14 3v5h5"/>'
|
| 237 |
-
};
|
| 238 |
-
const svg = (n, z = 18) => `<svg width="${z}" height="${z}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${IC[n] || ''}</svg>`;
|
| 239 |
-
const hydrate = () => document.querySelectorAll('[data-i]').forEach(e => e.innerHTML = svg(e.dataset.i, +e.dataset.z || 18));
|
| 240 |
-
|
| 241 |
-
/* ============ State ============ */
|
| 242 |
-
let cfg = Object.assign({
|
| 243 |
-
sys: 'You are a helpful assistant. Answer concisely, in the same language as the user.',
|
| 244 |
-
temp: 0.7, maxTok: 256, topP: 0.9, streamChunk: 8,
|
| 245 |
-
ttsRate: 1.5, ttsVoice: '', autoSpeak: false, sttLang: 'ar-SA',
|
| 246 |
-
theme: 'dark', model: 'qwen25'
|
| 247 |
-
}, JSON.parse(localStorage.getItem(LS) || '{}'));
|
| 248 |
-
const saveCfg = () => localStorage.setItem(LS, J(cfg));
|
| 249 |
-
let S = JSON.parse(localStorage.getItem(LS + '_sessions') || '[]');
|
| 250 |
-
let cid = localStorage.getItem(LS + '_cid') || null;
|
| 251 |
-
if (!cid || !S.find(s => s.id === cid)) { cid = uid(); S = [{ id: cid, title: 'دردشة جديدة', messages: [], artifacts: [], ts: Date.now() }]; }
|
| 252 |
-
const cur = () => S.find(s => s.id === cid);
|
| 253 |
-
function persist() { try { localStorage.setItem(LS + '_sessions', J(S)); localStorage.setItem(LS + '_cid', cid); } catch {} }
|
| 254 |
-
let MODELS = {}, STATUS = {};
|
| 255 |
-
let busy = false, curReqId = null, curArt = null, files = [], micOn = false, rec = null, micBase = '';
|
| 256 |
-
const DIAG = [];
|
| 257 |
-
function logDiag(t) { DIAG.unshift(new Date().toLocaleTimeString('en-GB') + ' ' + t); if (DIAG.length > 80) DIAG.pop(); }
|
| 258 |
-
function toast(t) { const d = document.createElement('div'); d.className = 'toast'; d.textContent = t; $('toasts').appendChild(d); setTimeout(() => d.remove(), Math.max(2200, t.length * 70)); }
|
| 259 |
-
function openDiag() { $('diagB').textContent = DIAG.join('\n') || 'لا سجلات'; $('dg').classList.add('open'); }
|
| 260 |
-
function copyDiag() { navigator.clipboard.writeText(DIAG.join('\n')).then(() => toast('📋 تم النسخ')); }
|
| 261 |
|
| 262 |
-
/* ============
|
| 263 |
-
|
| 264 |
-
function toggleTheme() { cfg.theme = cfg.theme === 'dark' ? 'light' : 'dark'; applyTheme(); saveCfg(); }
|
| 265 |
-
|
| 266 |
-
/* ============ Gradio API with Streaming ============ */
|
| 267 |
-
let base = '/gradio_api/call';
|
| 268 |
async function call(name, args = [], onUpdate) {
|
| 269 |
-
const post = () => fetch(`${base}/${name}`, {
|
|
|
|
|
|
|
| 270 |
let r = await post();
|
| 271 |
-
if (r.status === 404 && base !==
|
| 272 |
if (!r.ok) throw new Error(`${name}: ${r.status}`);
|
| 273 |
const { event_id } = await r.json();
|
| 274 |
const res = await fetch(`${base}/${name}/${event_id}`);
|
| 275 |
if (!res.ok || !res.body) throw new Error(`${name}: ${res.status}`);
|
| 276 |
const rd = res.body.getReader(), dec = new TextDecoder();
|
| 277 |
-
let buf =
|
| 278 |
for (;;) {
|
| 279 |
const { done, value } = await rd.read();
|
| 280 |
if (done) break;
|
| 281 |
buf += dec.decode(value, { stream: true });
|
| 282 |
const parts = buf.split(/\r?\n\r?\n/); buf = parts.pop();
|
| 283 |
for (const p of parts) {
|
| 284 |
-
let ev =
|
| 285 |
for (const l of p.split(/\r?\n/)) {
|
| 286 |
-
if (l.startsWith(
|
| 287 |
-
else if (l.startsWith(
|
| 288 |
}
|
| 289 |
let j = null; try { j = JSON.parse(data); } catch {}
|
| 290 |
-
if (ev ===
|
| 291 |
-
if (ev ===
|
| 292 |
-
|
| 293 |
-
if (typeof obj.text === 'string') { last = obj.text; if (obj.text !== lastText) { lastText = obj.text; onUpdate?.(last); } }
|
| 294 |
-
if (obj.ok === false && obj.error) throw new Error(obj.error);
|
| 295 |
-
}
|
| 296 |
-
if (ev === 'complete') {
|
| 297 |
-
const o = Array.isArray(j) ? j[0] : j;
|
| 298 |
-
if (o && typeof o.text === 'string') return o.text;
|
| 299 |
-
if (typeof o === 'string') return o;
|
| 300 |
-
return last;
|
| 301 |
-
}
|
| 302 |
}
|
| 303 |
}
|
|
|
|
| 304 |
return last;
|
| 305 |
}
|
| 306 |
|
| 307 |
-
/* ============
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
}
|
| 317 |
-
function
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
|
|
|
| 332 |
}
|
| 333 |
-
|
|
|
|
| 334 |
try {
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
else { led.className = 'led'; lt.textContent = 'غير محمّل'; }
|
| 342 |
-
} catch (e) { logDiag('refreshStatus: ' + e.message); }
|
| 343 |
-
}
|
| 344 |
-
let statusTimer = null;
|
| 345 |
-
function startPolling() { if (statusTimer) return; statusTimer = setInterval(refreshStatus, 1500); }
|
| 346 |
-
function stopPolling() { if (statusTimer) { clearInterval(statusTimer); statusTimer = null; } }
|
| 347 |
-
function onModelChange() { cfg.model = $('mp').value; saveCfg(); refreshStatus(); }
|
| 348 |
-
|
| 349 |
-
async function ensureLoaded(id, maxWait = 180000) {
|
| 350 |
-
if (STATUS[id]?.state === 'ready') return;
|
| 351 |
-
toast('⏳ تحميل النموذج...');
|
| 352 |
-
startPolling();
|
| 353 |
-
try { await call('load', [id]); } catch (e) { logDiag('load fail: ' + e.message); }
|
| 354 |
-
const t0 = Date.now();
|
| 355 |
-
while (Date.now() - t0 < maxWait) {
|
| 356 |
-
await new Promise(r => setTimeout(r, 1200));
|
| 357 |
-
await refreshStatus();
|
| 358 |
-
const st = STATUS[id];
|
| 359 |
-
if (st?.state === 'ready') { stopPolling(); return; }
|
| 360 |
-
if (st?.state === 'error') { stopPolling(); throw new Error(st.error || 'فشل التحميل'); }
|
| 361 |
}
|
| 362 |
-
stopPolling();
|
| 363 |
-
throw new Error('انتهت مهلة التحميل');
|
| 364 |
}
|
| 365 |
-
async function doLoad() { try { await ensureLoaded($('mp').value); toast('✅ جاهز'); } catch (e) { toast('❌ ' + e.message); } }
|
| 366 |
-
async function doUnload() { const id = $('mp').value; try { await call('unload', [id]); await refreshStatus(); toast('🗑️ فُرّغ'); } catch (e) { toast('❌ ' + e.message); } }
|
| 367 |
-
|
| 368 |
-
/* ============ Sessions ============ */
|
| 369 |
function renderSessions() {
|
| 370 |
-
$(
|
| 371 |
-
<div class="se ${s.id === cid ?
|
| 372 |
-
|
| 373 |
-
<button class="x" onclick="delSession(event,'${s.id}')">
|
| 374 |
-
</div>`).join(
|
| 375 |
}
|
| 376 |
function openSession(id) { cid = id; persist(); renderSessions(); renderChat(); closeAll(); }
|
| 377 |
-
function delSession(e, id) {
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
-
/* ============ Markdown ============ */
|
| 382 |
-
const qual = (l, n) => l === 'html' || l === 'svg' || n >= 150;
|
| 383 |
-
const prevable = l => l === 'html' || l === 'svg';
|
| 384 |
function md(src, s) {
|
| 385 |
-
if (!src) return
|
| 386 |
const cb = [];
|
| 387 |
-
let t = String(src).replace(/```([\w+-]*)\n?([\s\S]*?)```/g, (_, l, c) => {
|
|
|
|
|
|
|
|
|
|
| 388 |
let h = esc(t);
|
| 389 |
h = h.replace(/`([^`\n]+)`/g, '<code class="in">$1</code>')
|
| 390 |
-
.replace(/^### (.*)$/gm,
|
| 391 |
-
.replace(/
|
| 392 |
-
.replace(/^
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
|
| 394 |
-
.replace(/\n/g,
|
| 395 |
-
.replace(/<br>(?=<(?:div|h\d|ul|li|pre|blockquote|button))/g,
|
| 396 |
-
.replace(/(<\/(?:div|h\d|ul|li|pre|blockquote|button)>)<br>/g,
|
| 397 |
return h.replace(/(<br>)?\u0000(\d+)\u0000(<br>)?/g, (_, a, i) => {
|
| 398 |
const { l, c } = cb[+i];
|
|
|
|
| 399 |
if (s && qual(l, c.length)) {
|
| 400 |
-
const id =
|
| 401 |
let art = (s.artifacts = s.artifacts || []).find(x => x.id === id);
|
| 402 |
-
if (!art) {
|
|
|
|
|
|
|
|
|
|
| 403 |
return `<button class="artifact" onclick="openArtifact('${id}')" style="display:flex;gap:12px;align-items:center;width:100%;margin:10px 0;padding:11px 13px;background:var(--s1);border:1px solid var(--bd);border-radius:12px;color:var(--tx);text-align:right;cursor:pointer;font:inherit">
|
| 404 |
-
<span style="width:38px;height:38px;border-radius:10px;background:var(--s2);display:flex;align-items:center;justify-content:center;flex:none">
|
| 405 |
-
<span style="flex:1;min-width:0"><b style="display:block;font-size:13px;direction:ltr;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(art.title)}</b><small style="color:var(--mu);font-size:11px">${esc(l.toUpperCase())} · ${c.length} حرف · اضغط للعرض والمعاينة</small></span>
|
|
|
|
| 406 |
}
|
| 407 |
-
|
| 408 |
-
return `<div class="cw"><div class="ch"><span>${esc(l)}</span><div style="display:flex;gap:6px"><button onclick="copyCode(this)">نسخ</button>${isP ? `<button class="open-btn" onclick="openCodePanel(this)" data-lang="${esc(l)}">📄 عرض في اللوحة</button>` : ''}</div></div><pre>${esc(c)}</pre></div>`;
|
| 409 |
});
|
| 410 |
}
|
| 411 |
-
function copyCode(b) {
|
|
|
|
|
|
|
|
|
|
| 412 |
function openCodePanel(b) {
|
| 413 |
-
const cw = b.closest(
|
| 414 |
-
const
|
| 415 |
-
const
|
| 416 |
-
|
| 417 |
-
if (
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
return d;
|
| 433 |
}
|
| 434 |
function actions(idx) {
|
| 435 |
return `<div class="ma">
|
| 436 |
-
<button onclick="copyMsg(this)">
|
| 437 |
-
<button onclick="regenFrom(${idx})">
|
| 438 |
-
<button class="spb" onclick="speakMsg(this)">
|
| 439 |
</div>`;
|
| 440 |
}
|
| 441 |
-
function copyMsg(b) { navigator.clipboard.writeText(b.closest(
|
| 442 |
function renderChat() {
|
| 443 |
-
const s = cur(); $(
|
| 444 |
if (!s || !s.messages.length) {
|
| 445 |
-
$(
|
| 446 |
return;
|
| 447 |
}
|
| 448 |
s.messages.forEach((m, i) => {
|
| 449 |
-
if (m.role ===
|
| 450 |
-
let txt =
|
| 451 |
-
if (typeof m.content ===
|
| 452 |
-
else if (Array.isArray(m.content))
|
| 453 |
-
|
| 454 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
});
|
|
|
|
| 456 |
}
|
| 457 |
async function regenFrom(i) {
|
| 458 |
-
if (busy) return;
|
| 459 |
-
|
| 460 |
-
|
|
|
|
|
|
|
|
|
|
| 461 |
await ask(txt);
|
| 462 |
}
|
| 463 |
|
| 464 |
-
/* ============
|
| 465 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
function wrap(code, lang) {
|
| 467 |
const er = `<script>(function(){function r(m){try{parent.postMessage({__pe:1,m:String(m).slice(0,400)},'*')}catch(e){}}addEventListener('error',function(e){r((e.message||'error')+' @'+e.lineno)});addEventListener('unhandledrejection',function(e){r('promise: '+(e.reason&&e.reason.message||e.reason))})})()<\/script>`;
|
| 468 |
-
if (lang ===
|
| 469 |
if (/<head[\s>]/i.test(code)) return code.replace(/<head[^>]*>/i, m => m + er);
|
| 470 |
if (/<html[\s>]/i.test(code)) return code.replace(/<html[^>]*>/i, m => m + '<head>' + er + '</head>');
|
| 471 |
return er + code;
|
| 472 |
}
|
| 473 |
-
addEventListener(
|
| 474 |
-
|
| 475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
function liveWrite(lang, code) {
|
| 477 |
-
const st = !L.on;
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
$(
|
|
|
|
|
|
|
| 482 |
if (L.closed || !prevable(lang)) return;
|
| 483 |
clearTimeout(L.t);
|
| 484 |
if (Date.now() - L.last > 800) { L.last = Date.now(); prev(code, lang); }
|
| 485 |
else L.t = setTimeout(() => { L.last = Date.now(); prev(L.code, L.lang); }, 800);
|
| 486 |
}
|
| 487 |
-
function liveEnd() {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
function parseLive(f) {
|
| 489 |
-
const p = f.split(
|
| 490 |
-
if (p.length % 2 === 0) {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
return { inside: false };
|
| 492 |
}
|
| 493 |
function openArtifact(id) {
|
| 494 |
-
const a = cur()?.artifacts?.find(x => x.id === id);
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
$(
|
| 499 |
-
}
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
function
|
| 508 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
function addFiles(l) {
|
| 510 |
[...l].forEach(f => {
|
| 511 |
const r = new FileReader();
|
| 512 |
r.onload = () => { files.push({ name: f.name, type: f.type, data: r.result }); chips(); };
|
| 513 |
-
if (f.type.startsWith(
|
|
|
|
| 514 |
});
|
| 515 |
-
$(
|
| 516 |
}
|
|
|
|
| 517 |
async function sendMsg() {
|
| 518 |
if (busy) return;
|
| 519 |
-
const text = $(
|
| 520 |
if (!text && !files.length) return;
|
| 521 |
const s = cur();
|
| 522 |
-
if (!s.messages.length) { s.title = text.slice(0, 40) ||
|
| 523 |
-
const images = files.filter(f => f.type.startsWith(
|
| 524 |
-
const texts = files.filter(f => !f.type.startsWith('image/'));
|
| 525 |
|
|
|
|
| 526 |
let imgDescriptions = [];
|
| 527 |
if (images.length) {
|
| 528 |
setBusy(true);
|
| 529 |
-
try { await ensureLoaded('caption'); } catch (e) { toast('⚠️ نموذج الصور غير متاح'); }
|
| 530 |
for (const img of images) {
|
| 531 |
try {
|
| 532 |
-
const b64 = img.data.split(
|
| 533 |
-
const r = await call(
|
| 534 |
if (r?.ok && r.text) imgDescriptions.push(r.text);
|
| 535 |
-
else imgDescriptions.push(
|
| 536 |
-
} catch (e) { imgDescriptions.push(
|
| 537 |
}
|
| 538 |
setBusy(false);
|
| 539 |
}
|
| 540 |
|
| 541 |
let content = text;
|
| 542 |
if (imgDescriptions.length) {
|
| 543 |
-
content = imgDescriptions.map((d, i) => `[صورة ${i + 1}: ${d ||
|
| 544 |
}
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
const userMsg = { role: 'user', content };
|
| 548 |
userMsg._files = files.map(f => f.name);
|
| 549 |
userMsg._images = images.map(f => f.data);
|
| 550 |
s.messages.push(userMsg);
|
| 551 |
files = []; chips();
|
| 552 |
-
$(
|
| 553 |
persist(); renderSessions(); renderChat();
|
| 554 |
await ask(content);
|
| 555 |
}
|
|
@@ -558,211 +700,349 @@ async function ask(text) {
|
|
| 558 |
if (busy) return;
|
| 559 |
setBusy(true);
|
| 560 |
const s = cur();
|
| 561 |
-
const bubble = addMsg(
|
| 562 |
-
const status = document.createElement(
|
| 563 |
-
status.style.cssText =
|
| 564 |
-
status.textContent =
|
| 565 |
bubble.appendChild(status);
|
| 566 |
curReqId = uid();
|
| 567 |
|
| 568 |
-
// Smart streaming: buffer first N tokens, then flush
|
| 569 |
-
let totalText = '', displayed = '', tokenCount = 0;
|
| 570 |
-
const chunkSize = Math.max(0, parseInt(cfg.streamChunk) || 0);
|
| 571 |
-
|
| 572 |
try {
|
| 573 |
await ensureLoaded(cfg.model);
|
| 574 |
-
status.textContent =
|
| 575 |
|
| 576 |
-
const msgs = [{ role:
|
| 577 |
-
logDiag(
|
| 578 |
|
| 579 |
-
const
|
| 580 |
cfg.model, J(msgs), curReqId,
|
| 581 |
parseInt(cfg.maxTok) || 256,
|
| 582 |
parseFloat(cfg.temp) || 0.7
|
| 583 |
-
]
|
| 584 |
-
totalText = partial;
|
| 585 |
-
tokenCount++;
|
| 586 |
-
// Buffer first N tokens, then display
|
| 587 |
-
if (tokenCount <= chunkSize) return;
|
| 588 |
-
displayed = partial;
|
| 589 |
-
bubble.innerHTML = md(displayed, s);
|
| 590 |
-
bubble.dataset.raw = displayed;
|
| 591 |
-
const c = $('chat'); c.scrollTop = c.scrollHeight;
|
| 592 |
-
});
|
| 593 |
|
| 594 |
status.remove();
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
|
|
|
|
|
|
| 600 |
persist();
|
| 601 |
-
|
| 602 |
-
const
|
| 603 |
-
|
| 604 |
-
|
|
|
|
| 605 |
if (s.artifacts?.find(x => x.id === id)) setTimeout(() => openArtifact(id), 100);
|
| 606 |
}
|
| 607 |
-
if (cfg.autoSpeak && !micOn) ttsSpeak(
|
| 608 |
} else {
|
| 609 |
bubble.innerHTML = '<span style="color:var(--mu)">(رد فارغ — جرّب مرة أخرى)</span>';
|
| 610 |
}
|
| 611 |
} catch (e) {
|
| 612 |
bubble.remove();
|
| 613 |
-
addMsg(
|
| 614 |
-
logDiag(
|
| 615 |
} finally {
|
| 616 |
status.remove();
|
| 617 |
curReqId = null;
|
| 618 |
setBusy(false);
|
| 619 |
-
$(
|
| 620 |
}
|
| 621 |
}
|
| 622 |
-
function stopGen() { if (curReqId) { call(
|
| 623 |
|
| 624 |
-
/* ============ TTS ============ */
|
| 625 |
-
const hasTTS =
|
| 626 |
if (hasTTS) { speechSynthesis.getVoices(); speechSynthesis.onvoiceschanged = () => fillVoices(); }
|
| 627 |
const TTS = { id: 0 };
|
| 628 |
-
function ttsClean(t) {
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
function ttsSpeak(text, btn) {
|
| 633 |
-
if (!hasTTS) return toast(
|
| 634 |
-
ttsStop();
|
| 635 |
-
const
|
| 636 |
-
|
|
|
|
|
|
|
|
|
|
| 637 |
const next = () => {
|
| 638 |
if (my !== TTS.id) return;
|
| 639 |
-
if (i >= ch.length) { if (btn) { btn.classList.remove(
|
| 640 |
const u = new SpeechSynthesisUtterance(ch[i++]);
|
| 641 |
-
u.rate = cfg.ttsRate || 1.5;
|
| 642 |
-
|
| 643 |
-
u.
|
|
|
|
|
|
|
|
|
|
| 644 |
};
|
| 645 |
next();
|
| 646 |
}
|
| 647 |
-
function speakMsg(b) {
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
|
| 653 |
-
/* ============ STT ============ */
|
| 654 |
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
| 655 |
-
|
| 656 |
-
function
|
| 657 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 658 |
if (micOn) { micOn = false; try { rec?.stop(); } catch {} micUI(); return; }
|
| 659 |
-
navigator.mediaDevices.getUserMedia({ audio: true })
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
if (micOn) { micOn = false; try { rec?.stop(); } catch {} micUI(); }
|
| 679 |
-
ttsStop();
|
| 680 |
-
|
|
|
|
| 681 |
}
|
| 682 |
function vListen() {
|
| 683 |
if (!V.on || V.muted || busy) return;
|
| 684 |
-
V.text =
|
| 685 |
-
|
| 686 |
-
r
|
| 687 |
-
r.
|
| 688 |
-
r.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
try { r.start(); } catch {}
|
| 690 |
}
|
| 691 |
function vSend() {
|
| 692 |
-
clearTimeout(V.sil);
|
| 693 |
-
|
|
|
|
| 694 |
const r = V.rec; V.rec = null; try { r?.abort(); } catch {}
|
| 695 |
-
V.done = false; V.spoken = 0; $(
|
| 696 |
-
|
|
|
|
|
|
|
| 697 |
}
|
| 698 |
function vSay(t) {
|
| 699 |
const tok = V.tok;
|
| 700 |
for (const c of ttsChunks(t).filter(Boolean)) {
|
| 701 |
const { v, ar } = pickVoice(c);
|
| 702 |
-
const u = new SpeechSynthesisUtterance(c);
|
| 703 |
-
u.
|
| 704 |
-
|
|
|
|
|
|
|
|
|
|
| 705 |
u.onend = u.onerror = () => { if (tok !== V.tok) return; V.pend--; vCheck(); };
|
| 706 |
speechSynthesis.speak(u);
|
| 707 |
}
|
| 708 |
}
|
| 709 |
-
function vCheck() {
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 713 |
|
| 714 |
-
/* ============ Settings ============ */
|
| 715 |
-
function openSet() { fillVoices(); $(
|
| 716 |
function saveSet() {
|
| 717 |
-
cfg.sys = $(
|
| 718 |
-
cfg.
|
| 719 |
-
cfg.
|
| 720 |
-
cfg.
|
| 721 |
-
cfg.ttsRate = parseFloat($(
|
| 722 |
-
cfg.
|
| 723 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
}
|
| 725 |
|
| 726 |
-
/* ============ Export
|
| 727 |
function exportChat() {
|
| 728 |
-
const s = cur(); if (!s.messages.length) return toast(
|
| 729 |
-
const t =
|
| 730 |
-
|
| 731 |
-
return
|
| 732 |
-
}).join(
|
| 733 |
-
const a = document.createElement(
|
| 734 |
-
a.
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
|
|
|
|
|
|
| 751 |
});
|
| 752 |
|
| 753 |
-
/* ============ Boot ============ */
|
| 754 |
function boot() {
|
| 755 |
-
|
| 756 |
-
$(
|
| 757 |
-
$(
|
| 758 |
-
$(
|
| 759 |
-
$(
|
| 760 |
-
$(
|
| 761 |
-
$(
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
boot();
|
| 767 |
</script>
|
| 768 |
</body>
|
|
|
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
| 6 |
<meta name="color-scheme" content="dark light">
|
| 7 |
+
<title>AI Studio — دردشة محلية</title>
|
| 8 |
<style>
|
| 9 |
:root,[data-theme=dark]{--bg:#0f1115;--s1:#171a21;--s2:#1f232c;--s3:#2a2f3a;--bd:#2c313c;--tx:#eceef2;--mu:#8f97a6;--ac:#e06f4f;--ok:#4ade80;--er:#fb7185;--wr:#fbbf24;--code:#0a0c10;color-scheme:dark}
|
| 10 |
[data-theme=light]{--bg:#f6f6f3;--s1:#fff;--s2:#f0efeb;--s3:#e5e3dd;--bd:#dad8d1;--tx:#1f201e;--mu:#6f726b;--ac:#cc6748;--ok:#16a34a;--er:#dc2626;--wr:#d97706;--code:#f4f4f0;color-scheme:light}
|
|
|
|
| 16 |
::-webkit-scrollbar{width:7px;height:7px}::-webkit-scrollbar-thumb{background:var(--s3);border-radius:9px}
|
| 17 |
.ib,.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px}
|
| 18 |
#snd,#stp{align-items:center;justify-content:center}
|
|
|
|
| 19 |
.ib{width:36px;height:36px;border:1px solid transparent;border-radius:10px;background:none;color:var(--mu);flex:none}
|
| 20 |
.ib:hover{background:var(--s2);border-color:var(--bd);color:var(--tx)}
|
| 21 |
.btn{padding:10px 16px;border:0;border-radius:11px;background:var(--ac);color:#fff;font-weight:600;font-size:13px}
|
|
|
|
| 103 |
.fd input,.fd select,.fd textarea{width:100%;padding:9px 11px;border-radius:10px;border:1px solid var(--bd);background:var(--s2);font-size:13px}
|
| 104 |
.fd textarea{resize:vertical;min-height:70px}
|
| 105 |
.g3{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
|
| 106 |
+
.de{border:1px solid var(--bd);border-radius:10px;padding:9px;margin-bottom:7px;font-size:11px;direction:ltr;text-align:left;line-height:1.6}
|
| 107 |
+
.de pre{background:var(--code);border-radius:6px;padding:6px;margin-top:4px;max-height:80px;font-size:10.5px}
|
| 108 |
#cp{position:fixed;top:0;left:0;bottom:0;width:55vw;max-width:100vw;background:var(--s1);border-right:1px solid var(--bd);display:none;flex-direction:column;z-index:80}
|
| 109 |
#cp.open{display:flex}
|
| 110 |
#cp.full{width:100vw}
|
|
|
|
| 126 |
<body>
|
| 127 |
<div id="ov" onclick="closeAll()"></div>
|
| 128 |
<aside id="sb">
|
| 129 |
+
<div class="top"><button class="btn" onclick="newChat()">+ محادثة جديدة</button></div>
|
| 130 |
<div id="ss"></div>
|
| 131 |
+
<div class="ft"><span>محفوظة محلياً</span><button class="ib" id="thb" onclick="toggleTheme()">☀</button></div>
|
| 132 |
</aside>
|
| 133 |
<main>
|
| 134 |
<div id="tb">
|
| 135 |
+
<button class="ib" id="hb" onclick="event.stopPropagation();toggleSb()">☰</button>
|
| 136 |
<select id="mp" onchange="onModelChange()"></select>
|
| 137 |
<div class="sp"></div>
|
| 138 |
<div class="pill"><span class="led" id="led"></span><span id="ledT">جاهز</span></div>
|
| 139 |
+
<button class="ib" id="loadBtn" onclick="doLoad()" title="تحميل النموذج">⬇</button>
|
| 140 |
+
<button class="ib" onclick="doUnload()" title="تفريغ النموذج">🗑</button>
|
| 141 |
<button class="ib" id="spk" onclick="toggleAuto()" title="النطق التلقائي"></button>
|
| 142 |
+
<button class="ib" onclick="openDiag()" title="التشخيص">◉</button>
|
| 143 |
+
<button class="ib" onclick="openSet()" title="الإعدادات">⚙</button>
|
| 144 |
+
<button class="ib" onclick="exportChat()" title="تصدير">⬇</button>
|
| 145 |
+
<button class="ib" onclick="clearChat()" title="مسح">🗑</button>
|
| 146 |
</div>
|
| 147 |
<div id="chat"><div id="ci"></div></div>
|
| 148 |
<div id="cmp"><div class="in">
|
| 149 |
<div id="chips"></div>
|
| 150 |
<textarea id="inp" rows="1" placeholder="اكتب رسالتك..." onkeydown="if(event.key==='Enter'&&!event.shiftKey&&!event.isComposing){event.preventDefault();sendMsg()}"></textarea>
|
| 151 |
<div class="cr">
|
| 152 |
+
<div id="pw"><button class="ib" style="font-size:20px;border:1px solid var(--bd)" onclick="event.stopPropagation();$('pp').classList.toggle('open')">+</button>
|
| 153 |
<div id="pp" onclick="event.stopPropagation()"><div class="sc">
|
| 154 |
+
<button class="pi" onclick="$('fi').click();closeAll()">📎 إرفاق صور وملفات</button>
|
| 155 |
</div></div>
|
| 156 |
</div>
|
| 157 |
+
<button class="ib" id="mic" onclick="toggleMic()" title="تفريغ صوتي">🎤</button>
|
| 158 |
+
<button class="ib" id="vcb" onclick="startVoice()" title="محادثة صوتية">〰</button>
|
| 159 |
<div class="sp"></div>
|
| 160 |
+
<button id="stp" onclick="stopGen()">■</button><button id="snd" onclick="sendMsg()">↑</button>
|
| 161 |
</div>
|
| 162 |
</div></div>
|
| 163 |
</main>
|
| 164 |
<input type="file" id="fi" multiple hidden onchange="addFiles(this.files)">
|
| 165 |
<div id="cp" data-v="code">
|
| 166 |
<div class="cph">
|
| 167 |
+
<button class="ib" onclick="closePanel()">✕</button><span class="tt" id="cpT"></span>
|
| 168 |
<div class="tabs"><button data-v="code" class="on" onclick="setView('code')">الكود</button><button data-v="preview" onclick="setView('preview')">معاينة</button><button data-v="split" onclick="setView('split')">مقسّم</button></div>
|
| 169 |
+
<button class="ib" onclick="reloadPrev()" title="تحديث">↻</button>
|
| 170 |
+
<button class="ib" onclick="newTab()" title="تبويب جديد">↗</button>
|
| 171 |
+
<button class="ib" onclick="copyArt()" title="نسخ">⧉</button>
|
| 172 |
+
<button class="ib" onclick="dlArt()" title="تنزيل">↓</button>
|
| 173 |
+
<button class="ib" onclick="$('cp').classList.toggle('full')" title="ملء الشاشة">⛶</button>
|
| 174 |
</div>
|
| 175 |
<div class="cpb">
|
| 176 |
<div class="cv"><iframe id="cf" sandbox="allow-scripts allow-modals allow-forms allow-popups"></iframe><div id="pe" onclick="this.style.display='none'"></div></div>
|
|
|
|
| 178 |
</div>
|
| 179 |
</div>
|
| 180 |
<div id="vc">
|
| 181 |
+
<button class="ib vx" onclick="endVoice()">✕</button>
|
| 182 |
<div class="vm"><div id="orb" onclick="vTap()"><i></i><i></i><i></i></div><div id="vS"></div><div id="vT"></div><div id="vR"></div></div>
|
| 183 |
+
<div class="vb"><button class="ib" id="vMute" onclick="vMuteTog()" style="border:1px solid var(--bd);width:46px;height:46px">🎤</button><button class="btn" onclick="endVoice()">إنهاء المحادثة</button></div>
|
| 184 |
</div>
|
| 185 |
<div id="toasts"></div>
|
| 186 |
|
| 187 |
<div id="set" class="md" onclick="if(event.target===this)this.classList.remove('open')"><div class="card">
|
| 188 |
+
<h2>الإعدادات <button class="ib" onclick="$('set').classList.remove('open')">✕</button></h2>
|
| 189 |
<div class="sec"><b>🧠 تعليمات النظام</b><div class="fd"><textarea id="cSys" placeholder="You are a helpful assistant..."></textarea></div></div>
|
| 190 |
<div class="sec"><b>🎛 التوليد</b><div class="g3">
|
| 191 |
<div class="fd"><label>Temperature</label><input id="cTemp" type="number" step="0.1" min="0" max="2"></div>
|
| 192 |
+
<div class="fd"><label>Max Tokens (حتى 32000)</label><input id="cMax" type="number" min="32" max="32000"></div>
|
| 193 |
<div class="fd"><label>Top P</label><input id="cTop" type="number" step="0.05" min="0" max="1"></div></div>
|
| 194 |
+
<div class="fd"><label>Max Tokens: <b id="mMax">256</b></label><input id="cMaxRange" type="range" min="32" max="32000" step="32" oninput="$('cMax').value=this.value;$('mMax').textContent=this.value"></div>
|
|
|
|
| 195 |
</div>
|
| 196 |
<div class="sec"><b>🔊 النطق (إخراج الصوت)</b>
|
| 197 |
+
<div class="fd"><label>سرعة النطق: <b id="rV">1.5</b>×</label><input id="cRate" type="range" min="0.8" max="2" step="0.1" oninput="$('rV').textContent=this.value"></div>
|
| 198 |
<div class="fd"><label>صوت النطق</label><select id="cVoice"></select></div>
|
| 199 |
<div class="fd"><label><input type="checkbox" id="cAutoSpeak"> النطق التلقائي لكل رد</label></div>
|
| 200 |
<button class="btn g" style="width:100%" onclick="testVoice()">🔊 اختبار الصوت</button>
|
| 201 |
</div>
|
| 202 |
<div class="sec"><b>🎤 التفريغ الصوتي</b>
|
| 203 |
<div class="fd"><label>اللغة</label><select id="cStt">
|
| 204 |
+
<option value="ar-SA">العربية (الفصحى)</option>
|
| 205 |
+
<option value="ar-MA">العربية (المغرب)</option>
|
| 206 |
+
<option value="ar-EG">العربية (مصر)</option>
|
| 207 |
+
<option value="en-US">English</option>
|
| 208 |
+
<option value="fr-FR">Français</option>
|
| 209 |
</select></div>
|
| 210 |
</div>
|
| 211 |
<button class="btn" style="width:100%" onclick="saveSet()">💾 حفظ</button>
|
| 212 |
</div></div>
|
| 213 |
|
| 214 |
<div id="dg" class="md" onclick="if(event.target===this)this.classList.remove('open')"><div class="card">
|
| 215 |
+
<h2>🩺 التشخيص <span><button class="btn g" style="padding:6px 11px;font-size:11px" onclick="copyDiag()">نسخ</button> <button class="ib" onclick="$('dg').classList.remove('open')">✕</button></span></h2>
|
| 216 |
<pre id="diagB" style="direction:ltr;text-align:left;white-space:pre-wrap;font-size:11px;color:var(--mu);max-height:300px;overflow:auto;background:var(--code);border-radius:8px;padding:8px"></pre>
|
| 217 |
</div></div>
|
| 218 |
|
| 219 |
<script>
|
|
|
|
| 220 |
const $ = i => document.getElementById(i);
|
| 221 |
+
const LS = "ai_studio_gradio_v3";
|
| 222 |
+
const esc = s => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
| 223 |
+
const uid = () => (crypto.randomUUID ? crypto.randomUUID() : "id" + Date.now() + Math.random().toString(36).slice(2));
|
| 224 |
+
const J = JSON.stringify;
|
| 225 |
const hash = s => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0; return h.toString(36); };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
+
/* ==================== Gradio API ==================== */
|
| 228 |
+
let base = "/gradio_api/call";
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
async function call(name, args = [], onUpdate) {
|
| 230 |
+
const post = () => fetch(`${base}/${name}`, {
|
| 231 |
+
method: "POST", headers: { "Content-Type": "application/json" }, body: J({ data: args })
|
| 232 |
+
});
|
| 233 |
let r = await post();
|
| 234 |
+
if (r.status === 404 && base !== "/call") { base = "/call"; r = await post(); }
|
| 235 |
if (!r.ok) throw new Error(`${name}: ${r.status}`);
|
| 236 |
const { event_id } = await r.json();
|
| 237 |
const res = await fetch(`${base}/${name}/${event_id}`);
|
| 238 |
if (!res.ok || !res.body) throw new Error(`${name}: ${res.status}`);
|
| 239 |
const rd = res.body.getReader(), dec = new TextDecoder();
|
| 240 |
+
let buf = "", last;
|
| 241 |
for (;;) {
|
| 242 |
const { done, value } = await rd.read();
|
| 243 |
if (done) break;
|
| 244 |
buf += dec.decode(value, { stream: true });
|
| 245 |
const parts = buf.split(/\r?\n\r?\n/); buf = parts.pop();
|
| 246 |
for (const p of parts) {
|
| 247 |
+
let ev = "message", data = "";
|
| 248 |
for (const l of p.split(/\r?\n/)) {
|
| 249 |
+
if (l.startsWith("event:")) ev = l.slice(6).trim();
|
| 250 |
+
else if (l.startsWith("data:")) data += l.slice(5).trim();
|
| 251 |
}
|
| 252 |
let j = null; try { j = JSON.parse(data); } catch {}
|
| 253 |
+
if (ev === "error") throw new Error(typeof j === "string" ? j : "خطأ من الخادم");
|
| 254 |
+
if (ev === "generating" && Array.isArray(j)) { last = j[0]; onUpdate?.(last); }
|
| 255 |
+
if (ev === "complete") { const o = Array.isArray(j) ? j[0] : j; if (o !== undefined && o !== null) last = o; return last; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
}
|
| 257 |
}
|
| 258 |
+
if (last === undefined) throw new Error("انتهى الاتصال دون رد");
|
| 259 |
return last;
|
| 260 |
}
|
| 261 |
|
| 262 |
+
/* ==================== Config ==================== */
|
| 263 |
+
let cfg = Object.assign({
|
| 264 |
+
sys: "You are a helpful assistant. Answer concisely, in the same language as the user.",
|
| 265 |
+
temp: 0.7, maxTok: 256, topP: 0.9,
|
| 266 |
+
ttsRate: 1.5, ttsVoice: "", autoSpeak: false,
|
| 267 |
+
sttLang: "ar-SA",
|
| 268 |
+
theme: "dark",
|
| 269 |
+
model: "qwen25",
|
| 270 |
+
}, JSON.parse(localStorage.getItem(LS) || "{}"));
|
| 271 |
+
const saveCfg = () => localStorage.setItem(LS, J(cfg));
|
| 272 |
+
|
| 273 |
+
/* ==================== Theme ==================== */
|
| 274 |
+
function applyTheme() {
|
| 275 |
+
document.documentElement.dataset.theme = cfg.theme;
|
| 276 |
+
$("thb").textContent = cfg.theme === "dark" ? "☀" : "☾";
|
| 277 |
}
|
| 278 |
+
function toggleTheme() { cfg.theme = cfg.theme === "dark" ? "light" : "dark"; applyTheme(); saveCfg(); }
|
| 279 |
+
|
| 280 |
+
/* ==================== Diagnostics ==================== */
|
| 281 |
+
const DIAG = [];
|
| 282 |
+
function logDiag(t) { DIAG.unshift(new Date().toLocaleTimeString("en-GB") + " " + t); if (DIAG.length > 60) DIAG.pop(); }
|
| 283 |
+
function openDiag() { $("diagB").textContent = DIAG.join("\n") || "لا سجلات"; $("dg").classList.add("open"); }
|
| 284 |
+
function copyDiag() { navigator.clipboard.writeText(DIAG.join("\n")).then(() => toast("📋 تم النسخ"), () => toast("❌ تعذر")); }
|
| 285 |
+
|
| 286 |
+
/* ==================== Toast ==================== */
|
| 287 |
+
function toast(t) { const d = document.createElement("div"); d.className = "toast"; d.textContent = t; $("toasts").appendChild(d); setTimeout(() => d.remove(), Math.max(2500, t.length * 80)); }
|
| 288 |
+
|
| 289 |
+
/* ==================== Sessions ==================== */
|
| 290 |
+
let S = JSON.parse(localStorage.getItem(LS + "_sessions") || "[]");
|
| 291 |
+
let cid = localStorage.getItem(LS + "_cid") || null;
|
| 292 |
+
if (!cid || !S.find(s => s.id === cid)) {
|
| 293 |
+
cid = uid();
|
| 294 |
+
S = [{ id: cid, title: "دردشة جديدة", messages: [], ts: Date.now() }];
|
| 295 |
}
|
| 296 |
+
const cur = () => S.find(s => s.id === cid);
|
| 297 |
+
function persist() {
|
| 298 |
try {
|
| 299 |
+
localStorage.setItem(LS + "_sessions", J(S));
|
| 300 |
+
localStorage.setItem(LS + "_cid", cid);
|
| 301 |
+
} catch (e) {
|
| 302 |
+
// Prune oldest sessions if storage full
|
| 303 |
+
S = S.slice(0, 10);
|
| 304 |
+
try { localStorage.setItem(LS + "_sessions", J(S)); } catch {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
}
|
|
|
|
|
|
|
| 306 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
function renderSessions() {
|
| 308 |
+
$("ss").innerHTML = S.slice().sort((a, b) => b.ts - a.ts).map(s => `
|
| 309 |
+
<div class="se ${s.id === cid ? "on" : ""}" onclick="openSession('${s.id}')">
|
| 310 |
+
💬 <span>${esc(s.title)}</span>
|
| 311 |
+
<button class="x" onclick="delSession(event,'${s.id}')">🗑</button>
|
| 312 |
+
</div>`).join("");
|
| 313 |
}
|
| 314 |
function openSession(id) { cid = id; persist(); renderSessions(); renderChat(); closeAll(); }
|
| 315 |
+
function delSession(e, id) {
|
| 316 |
+
e.stopPropagation();
|
| 317 |
+
if (!confirm("حذف هذه المحادثة؟")) return;
|
| 318 |
+
S = S.filter(s => s.id !== id);
|
| 319 |
+
if (cid === id) { cid = S[0]?.id; if (!cid) { newChat(); return; } }
|
| 320 |
+
persist(); renderSessions(); renderChat();
|
| 321 |
+
}
|
| 322 |
+
function newChat() {
|
| 323 |
+
const s = { id: uid(), title: "دردشة جديدة", messages: [], artifacts: [], ts: Date.now() };
|
| 324 |
+
S.unshift(s); cid = s.id; persist(); renderSessions(); renderChat(); closeAll();
|
| 325 |
+
}
|
| 326 |
+
function clearChat() {
|
| 327 |
+
if (!confirm("مسح كل رسائل هذه المحادثة؟")) return;
|
| 328 |
+
const s = cur(); if (!s) return;
|
| 329 |
+
s.messages = []; s.artifacts = []; s.title = "دردشة جديدة";
|
| 330 |
+
persist(); renderSessions(); renderChat();
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
/* ==================== Markdown + Code detection ==================== */
|
| 334 |
+
const qual = (l, n) => l === "html" || l === "svg" || n >= 150;
|
| 335 |
+
const prevable = l => l === "html" || l === "svg";
|
| 336 |
|
|
|
|
|
|
|
|
|
|
| 337 |
function md(src, s) {
|
| 338 |
+
if (!src) return "";
|
| 339 |
const cb = [];
|
| 340 |
+
let t = String(src).replace(/```([\w+-]*)\n?([\s\S]*?)```/g, (_, l, c) => {
|
| 341 |
+
cb.push({ l: (l || "text").toLowerCase(), c });
|
| 342 |
+
return "\u0000" + (cb.length - 1) + "\u0000";
|
| 343 |
+
});
|
| 344 |
let h = esc(t);
|
| 345 |
h = h.replace(/`([^`\n]+)`/g, '<code class="in">$1</code>')
|
| 346 |
+
.replace(/^### (.*)$/gm, "<h3>$1</h3>")
|
| 347 |
+
.replace(/^## (.*)$/gm, "<h2>$1</h2>")
|
| 348 |
+
.replace(/^# (.*)$/gm, "<h1>$1</h1>")
|
| 349 |
+
.replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>")
|
| 350 |
+
.replace(/^> (.*)$/gm, "<blockquote>$1</blockquote>")
|
| 351 |
+
.replace(/^[-*] (.*)$/gm, "<li>$1</li>")
|
| 352 |
+
.replace(/(?:<li>.*<\/li>\n?)+/g, m => "<ul>" + m.trim() + "</ul>")
|
| 353 |
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
|
| 354 |
+
.replace(/\n/g, "<br>")
|
| 355 |
+
.replace(/<br>(?=<(?:div|h\d|ul|li|pre|blockquote|button))/g, "")
|
| 356 |
+
.replace(/(<\/(?:div|h\d|ul|li|pre|blockquote|button)>)<br>/g, "$1");
|
| 357 |
return h.replace(/(<br>)?\u0000(\d+)\u0000(<br>)?/g, (_, a, i) => {
|
| 358 |
const { l, c } = cb[+i];
|
| 359 |
+
const isPreviewable = prevable(l);
|
| 360 |
if (s && qual(l, c.length)) {
|
| 361 |
+
const id = "a" + hash(c);
|
| 362 |
let art = (s.artifacts = s.artifacts || []).find(x => x.id === id);
|
| 363 |
+
if (!art) {
|
| 364 |
+
art = { id, lang: l, content: c, title: l === "html" ? "index.html" : l === "svg" ? "image.svg" : "file." + l };
|
| 365 |
+
s.artifacts.push(art);
|
| 366 |
+
}
|
| 367 |
return `<button class="artifact" onclick="openArtifact('${id}')" style="display:flex;gap:12px;align-items:center;width:100%;margin:10px 0;padding:11px 13px;background:var(--s1);border:1px solid var(--bd);border-radius:12px;color:var(--tx);text-align:right;cursor:pointer;font:inherit">
|
| 368 |
+
<span style="width:38px;height:38px;border-radius:10px;background:var(--s2);display:flex;align-items:center;justify-content:center;flex:none">📄</span>
|
| 369 |
+
<span style="flex:1;min-width:0"><b style="display:block;font-size:13px;direction:ltr;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(art.title)}</b><small style="color:var(--mu);font-size:11px">${esc(l.toUpperCase())} · ${c.length} حرف · اضغط للعرض${isPreviewable ? " والمعاينة" : ""}</small></span>
|
| 370 |
+
</button>`;
|
| 371 |
}
|
| 372 |
+
return `<div class="cw"><div class="ch"><span>${esc(l)}</span><div style="display:flex;gap:6px"><button onclick="copyCode(this)">نسخ</button>${isPreviewable ? `<button class="open-btn" onclick="openCodePanel(this)" data-lang="${esc(l)}">📄 عرض في اللوحة</button>` : ""}</div></div><pre>${esc(c)}</pre></div>`;
|
|
|
|
| 373 |
});
|
| 374 |
}
|
| 375 |
+
function copyCode(b) {
|
| 376 |
+
const code = b.closest(".cw").querySelector("pre").textContent;
|
| 377 |
+
navigator.clipboard.writeText(code).then(() => toast("📋 تم النسخ"), () => toast("❌ تعذر"));
|
| 378 |
+
}
|
| 379 |
function openCodePanel(b) {
|
| 380 |
+
const cw = b.closest(".cw");
|
| 381 |
+
const code = cw.querySelector("pre").textContent;
|
| 382 |
+
const lang = b.dataset.lang || "html";
|
| 383 |
+
const s = cur();
|
| 384 |
+
if (s) {
|
| 385 |
+
const id = "a" + hash(code);
|
| 386 |
+
let art = (s.artifacts = s.artifacts || []).find(x => x.id === id);
|
| 387 |
+
if (!art) {
|
| 388 |
+
art = { id, lang, content: code, title: lang === "html" ? "index.html" : "image.svg" };
|
| 389 |
+
s.artifacts.push(art);
|
| 390 |
+
}
|
| 391 |
+
persist();
|
| 392 |
+
openArtifact(id);
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
/* ==================== Render chat ==================== */
|
| 397 |
+
function addMsg(role, text = "", files = [], idx = null, images = []) {
|
| 398 |
+
$("ci").querySelector(".welcome")?.remove();
|
| 399 |
+
const d = document.createElement("div");
|
| 400 |
+
d.className = "msg " + role;
|
| 401 |
+
d.dataset.raw = text || "";
|
| 402 |
+
const body = role === "assistant" ? md(text, cur()) : esc(text).replace(/\n/g, "<br>");
|
| 403 |
+
d.innerHTML = images.map(src => `<img class="chat-img" src="${esc(src)}" alt="صورة">`).join("")
|
| 404 |
+
+ body
|
| 405 |
+
+ (files?.length ? `<div class="files">📎 ${files.map(esc).join("، ")}</div>` : "")
|
| 406 |
+
+ (idx != null && role === "assistant" ? actions(idx) : "");
|
| 407 |
+
$("ci").appendChild(d);
|
| 408 |
+
scrollDown(role === "user");
|
| 409 |
return d;
|
| 410 |
}
|
| 411 |
function actions(idx) {
|
| 412 |
return `<div class="ma">
|
| 413 |
+
<button onclick="copyMsg(this)">📋 نسخ</button>
|
| 414 |
+
<button onclick="regenFrom(${idx})">🔄 إعادة</button>
|
| 415 |
+
<button class="spb" onclick="speakMsg(this)" title="نطق">🔊 استمع</button>
|
| 416 |
</div>`;
|
| 417 |
}
|
| 418 |
+
function copyMsg(b) { navigator.clipboard.writeText(b.closest(".msg").dataset.raw || "").then(() => toast("📋 تم"), () => toast("❌ تعذر")); }
|
| 419 |
function renderChat() {
|
| 420 |
+
const s = cur(); $("ci").innerHTML = "";
|
| 421 |
if (!s || !s.messages.length) {
|
| 422 |
+
$("ci").innerHTML = `<div class="welcome"><h2>مرحباً 👋</h2><p>اكتب رسالتك. سيُحمَّل النموذج تلقائياً عند أول رسالة.</p></div>`;
|
| 423 |
return;
|
| 424 |
}
|
| 425 |
s.messages.forEach((m, i) => {
|
| 426 |
+
if (m.role === "user") {
|
| 427 |
+
let txt = "", imgs = [];
|
| 428 |
+
if (typeof m.content === "string") txt = m.content;
|
| 429 |
+
else if (Array.isArray(m.content)) {
|
| 430 |
+
m.content.forEach(c => {
|
| 431 |
+
if (c.type === "text") txt = c.text;
|
| 432 |
+
if (c.type === "image_url") imgs.push(c.image_url.url);
|
| 433 |
+
});
|
| 434 |
+
}
|
| 435 |
+
addMsg("user", txt, m._files, i, imgs);
|
| 436 |
+
} else if (m.role === "assistant" && m.content) {
|
| 437 |
+
addMsg("assistant", m.content, null, i);
|
| 438 |
+
}
|
| 439 |
});
|
| 440 |
+
scrollDown(true);
|
| 441 |
}
|
| 442 |
async function regenFrom(i) {
|
| 443 |
+
if (busy) return;
|
| 444 |
+
const s = cur(); let u = i; while (u >= 0 && s.messages[u].role !== "user") u--;
|
| 445 |
+
if (u < 0) return;
|
| 446 |
+
s.messages = s.messages.slice(0, u + 1); persist(); renderChat();
|
| 447 |
+
const m = s.messages[u];
|
| 448 |
+
const txt = typeof m.content === "string" ? m.content : (m.content.find?.(c => c.type === "text")?.text || "");
|
| 449 |
await ask(txt);
|
| 450 |
}
|
| 451 |
|
| 452 |
+
/* ==================== Scroll ==================== */
|
| 453 |
+
let follow = true;
|
| 454 |
+
$("chat").addEventListener("scroll", () => { const c = $("chat"); follow = c.scrollTop + c.clientHeight >= c.scrollHeight - 60; });
|
| 455 |
+
function scrollDown(f) { const c = $("chat"); if (f || follow) c.scrollTop = c.scrollHeight; }
|
| 456 |
+
|
| 457 |
+
/* ==================== Code panel + Preview ==================== */
|
| 458 |
+
const L = { t: 0, last: 0, code: "", lang: "html", on: false, closed: false };
|
| 459 |
+
let curArt = null;
|
| 460 |
function wrap(code, lang) {
|
| 461 |
const er = `<script>(function(){function r(m){try{parent.postMessage({__pe:1,m:String(m).slice(0,400)},'*')}catch(e){}}addEventListener('error',function(e){r((e.message||'error')+' @'+e.lineno)});addEventListener('unhandledrejection',function(e){r('promise: '+(e.reason&&e.reason.message||e.reason))})})()<\/script>`;
|
| 462 |
+
if (lang === "svg") return '<!doctype html><meta charset="utf-8"><style>html,body{margin:0;height:100%;display:flex;align-items:center;justify-content:center;background:#fff}svg{max-width:100%;max-height:100%}</style>' + code + er;
|
| 463 |
if (/<head[\s>]/i.test(code)) return code.replace(/<head[^>]*>/i, m => m + er);
|
| 464 |
if (/<html[\s>]/i.test(code)) return code.replace(/<html[^>]*>/i, m => m + '<head>' + er + '</head>');
|
| 465 |
return er + code;
|
| 466 |
}
|
| 467 |
+
addEventListener("message", e => {
|
| 468 |
+
if (e.data && e.data.__pe) {
|
| 469 |
+
const b = $("pe");
|
| 470 |
+
b.textContent = "⚠ " + e.data.m + " (اضغط للإخفاء)";
|
| 471 |
+
b.style.display = "block";
|
| 472 |
+
}
|
| 473 |
+
});
|
| 474 |
+
const prev = (code, lang) => { $("pe").style.display = "none"; $("cf").srcdoc = wrap(code, lang); };
|
| 475 |
+
function setView(v) {
|
| 476 |
+
$("cp").dataset.v = v;
|
| 477 |
+
document.querySelectorAll(".tabs button").forEach(b => b.classList.toggle("on", b.dataset.v === v));
|
| 478 |
+
}
|
| 479 |
function liveWrite(lang, code) {
|
| 480 |
+
const st = !L.on;
|
| 481 |
+
L.on = true; L.code = code; L.lang = lang;
|
| 482 |
+
if (st) { L.closed = false; L.last = 0; $("cp").classList.add("open"); setView(prevable(lang) ? "split" : "code"); }
|
| 483 |
+
$("cpT").textContent = "✍ يكتب (" + lang + ")...";
|
| 484 |
+
const el = $("cpS"), near = el.scrollTop + el.clientHeight >= el.scrollHeight - 40;
|
| 485 |
+
$("cpC").textContent = code;
|
| 486 |
+
if (near) el.scrollTop = el.scrollHeight;
|
| 487 |
if (L.closed || !prevable(lang)) return;
|
| 488 |
clearTimeout(L.t);
|
| 489 |
if (Date.now() - L.last > 800) { L.last = Date.now(); prev(code, lang); }
|
| 490 |
else L.t = setTimeout(() => { L.last = Date.now(); prev(L.code, L.lang); }, 800);
|
| 491 |
}
|
| 492 |
+
function liveEnd() {
|
| 493 |
+
clearTimeout(L.t);
|
| 494 |
+
if (L.on && prevable(L.lang) && L.code && !L.closed) prev(L.code, L.lang);
|
| 495 |
+
L.on = false;
|
| 496 |
+
}
|
| 497 |
function parseLive(f) {
|
| 498 |
+
const p = f.split("```");
|
| 499 |
+
if (p.length % 2 === 0) {
|
| 500 |
+
const g = p[p.length - 1], n = g.indexOf("\n");
|
| 501 |
+
if (n < 0) return { inside: true, lang: "text", code: "" };
|
| 502 |
+
return { inside: true, lang: (g.slice(0, n).trim() || "text").toLowerCase(), code: g.slice(n + 1) };
|
| 503 |
+
}
|
| 504 |
return { inside: false };
|
| 505 |
}
|
| 506 |
function openArtifact(id) {
|
| 507 |
+
const a = cur()?.artifacts?.find(x => x.id === id);
|
| 508 |
+
if (!a) return toast("❌ العنصر غير موجود");
|
| 509 |
+
liveEnd(); curArt = a;
|
| 510 |
+
$("cpT").textContent = a.title;
|
| 511 |
+
$("cpC").textContent = a.content;
|
| 512 |
+
if (prevable(a.lang)) { prev(a.content, a.lang); setView("split"); }
|
| 513 |
+
else {
|
| 514 |
+
$("cf").srcdoc = '<body style="font-family:sans-serif;color:#888;display:flex;align-items:center;justify-content:center;height:100vh">لا معاينة لهذا النوع</body>';
|
| 515 |
+
setView("code");
|
| 516 |
+
}
|
| 517 |
+
$("cp").classList.add("open");
|
| 518 |
+
}
|
| 519 |
+
function closePanel() { $("cp").classList.remove("open", "full"); if (L.on) L.closed = true; clearTimeout(L.t); }
|
| 520 |
+
function reloadPrev() { const c = curArt ? curArt.content : L.code, l = curArt ? curArt.lang : L.lang; c ? prev(c, l) : toast("لا محتوى"); }
|
| 521 |
+
function newTab() {
|
| 522 |
+
const c = curArt ? curArt.content : L.code, l = curArt ? curArt.lang : L.lang;
|
| 523 |
+
if (!c) return toast("لا محتوى");
|
| 524 |
+
const w = open("about:blank", "_blank");
|
| 525 |
+
if (w) { w.document.write(wrap(c, l)); w.document.close(); }
|
| 526 |
+
}
|
| 527 |
+
function copyArt() { const c = curArt ? curArt.content : L.code; if (!c) return toast("لا كود"); navigator.clipboard.writeText(c).then(() => toast("📋 تم"), () => toast("❌ تعذر")); }
|
| 528 |
+
function dlArt() {
|
| 529 |
+
if (!curArt) return toast("لا ملف");
|
| 530 |
+
const a = document.createElement("a");
|
| 531 |
+
a.href = URL.createObjectURL(new Blob([curArt.content], { type: "text/plain;charset=utf-8" }));
|
| 532 |
+
a.download = curArt.title; a.click();
|
| 533 |
+
toast("⬇ تم");
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
/* ==================== Models ==================== */
|
| 537 |
+
let MODELS = {}, MODEL_LIST = [], STATUS = {};
|
| 538 |
+
async function initModels() {
|
| 539 |
+
try {
|
| 540 |
+
const r = await call("models");
|
| 541 |
+
MODEL_LIST = r.models || [];
|
| 542 |
+
MODEL_LIST.forEach(m => MODELS[m.id] = m);
|
| 543 |
+
renderModelSelect();
|
| 544 |
+
await refreshStatus();
|
| 545 |
+
} catch (e) {
|
| 546 |
+
toast("⚠️ تعذر جلب النماذج: " + e.message);
|
| 547 |
+
logDiag("initModels: " + e.message);
|
| 548 |
+
}
|
| 549 |
+
}
|
| 550 |
+
function renderModelSelect() {
|
| 551 |
+
const sel = $("mp");
|
| 552 |
+
const groups = {};
|
| 553 |
+
MODEL_LIST.filter(m => m.group !== "aux").forEach(m => {
|
| 554 |
+
const g = m.group || "أخرى";
|
| 555 |
+
if (!groups[g]) groups[g] = [];
|
| 556 |
+
groups[g].push(m);
|
| 557 |
+
});
|
| 558 |
+
sel.innerHTML = "";
|
| 559 |
+
const entries = Object.entries(groups);
|
| 560 |
+
if (entries.length === 1) {
|
| 561 |
+
entries[0][1].forEach(m => {
|
| 562 |
+
const o = document.createElement("option");
|
| 563 |
+
o.value = m.id;
|
| 564 |
+
o.textContent = `${m.repo.split("/").pop()} (${m.size || ""})`;
|
| 565 |
+
sel.appendChild(o);
|
| 566 |
+
});
|
| 567 |
+
} else {
|
| 568 |
+
for (const [g, list] of entries) {
|
| 569 |
+
const og = document.createElement("optgroup"); og.label = g;
|
| 570 |
+
list.forEach(m => {
|
| 571 |
+
const o = document.createElement("option");
|
| 572 |
+
o.value = m.id;
|
| 573 |
+
o.textContent = `${m.repo.split("/").pop()} (${m.size || ""})`;
|
| 574 |
+
og.appendChild(o);
|
| 575 |
+
});
|
| 576 |
+
sel.appendChild(og);
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
const saved = MODELS[cfg.model] ? cfg.model : MODEL_LIST.find(m => m.group !== "aux")?.id || "";
|
| 580 |
+
sel.value = saved;
|
| 581 |
+
onModelChange();
|
| 582 |
+
}
|
| 583 |
+
async function refreshStatus() {
|
| 584 |
+
try {
|
| 585 |
+
STATUS = await call("status") || {};
|
| 586 |
+
const cur_id = $("mp").value;
|
| 587 |
+
const st = STATUS[cur_id];
|
| 588 |
+
const led = $("led"), lt = $("ledT");
|
| 589 |
+
if (st?.state === "ready") { led.className = "led on"; lt.textContent = "جاهز"; }
|
| 590 |
+
else if (st?.state === "loading") { led.className = "led wr"; lt.textContent = "تحميل " + Math.round(st.pct || 0) + "%"; }
|
| 591 |
+
else if (st?.state === "error") { led.className = "led"; led.style.background = "var(--er)"; lt.textContent = "خطأ"; }
|
| 592 |
+
else { led.className = "led"; lt.textContent = "غير محمّل"; }
|
| 593 |
+
} catch (e) { logDiag("refreshStatus: " + e.message); }
|
| 594 |
+
}
|
| 595 |
+
let statusTimer = null;
|
| 596 |
+
function startStatusPolling() { stopStatusPolling(); statusTimer = setInterval(refreshStatus, 2000); }
|
| 597 |
+
function stopStatusPolling() { if (statusTimer) clearInterval(statusTimer); statusTimer = null; }
|
| 598 |
+
function onModelChange() {
|
| 599 |
+
const id = $("mp").value; if (!id) return;
|
| 600 |
+
cfg.model = id; saveCfg(); refreshStatus();
|
| 601 |
+
}
|
| 602 |
+
async function doLoad() {
|
| 603 |
+
const id = $("mp").value; if (!id) return;
|
| 604 |
+
toast("⏳ جارٍ تحميل النموذج...");
|
| 605 |
+
startStatusPolling();
|
| 606 |
+
try {
|
| 607 |
+
const r = await call("load", [id]);
|
| 608 |
+
if (!r?.ok) throw new Error(r?.error || "فشل");
|
| 609 |
+
toast("✅ النموذج جاهز");
|
| 610 |
+
await refreshStatus();
|
| 611 |
+
} catch (e) { toast("❌ " + e.message); logDiag("doLoad: " + e.message); }
|
| 612 |
+
finally { setTimeout(stopStatusPolling, 3000); }
|
| 613 |
+
}
|
| 614 |
+
async function doUnload() {
|
| 615 |
+
const id = $("mp").value; if (!id) return;
|
| 616 |
+
try { await call("unload", [id]); toast("🗑️ فُرّغ"); await refreshStatus(); }
|
| 617 |
+
catch (e) { toast("❌ " + e.message); }
|
| 618 |
+
}
|
| 619 |
+
async function ensureLoaded(id) {
|
| 620 |
+
// Retry up to 3 times
|
| 621 |
+
for (let i = 0; i < 3; i++) {
|
| 622 |
+
try {
|
| 623 |
+
if (STATUS[id]?.state === "ready") return true;
|
| 624 |
+
logDiag("ensureLoaded try " + (i + 1) + " for " + id);
|
| 625 |
+
startStatusPolling();
|
| 626 |
+
const r = await call("load", [id]);
|
| 627 |
+
if (r?.ok) { await refreshStatus(); if (STATUS[id]?.state === "ready" || !STATUS[id]) return true; }
|
| 628 |
+
// Wait a bit before retry
|
| 629 |
+
await new Promise(r => setTimeout(r, 1500));
|
| 630 |
+
} catch (e) {
|
| 631 |
+
logDiag("ensureLoaded err: " + e.message);
|
| 632 |
+
if (i === 2) throw e;
|
| 633 |
+
} finally {
|
| 634 |
+
setTimeout(stopStatusPolling, 3000);
|
| 635 |
+
}
|
| 636 |
+
}
|
| 637 |
+
return true; // proceed anyway, generate will retry
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
/* ==================== Send ==================== */
|
| 641 |
+
let busy = false, curReqId = null;
|
| 642 |
+
let files = [], pendingImage = "";
|
| 643 |
+
function setBusy(v) {
|
| 644 |
+
busy = v;
|
| 645 |
+
$("snd").style.display = v ? "none" : "flex";
|
| 646 |
+
$("stp").style.display = v ? "flex" : "none";
|
| 647 |
+
$("mp").disabled = v;
|
| 648 |
+
}
|
| 649 |
+
function chips() {
|
| 650 |
+
$("chips").innerHTML = files.map((f, i) => `<span class="chip">📎 ${esc(f.name)}<button onclick="files.splice(${i},1);chips()">✕</button></span>`).join("");
|
| 651 |
+
}
|
| 652 |
function addFiles(l) {
|
| 653 |
[...l].forEach(f => {
|
| 654 |
const r = new FileReader();
|
| 655 |
r.onload = () => { files.push({ name: f.name, type: f.type, data: r.result }); chips(); };
|
| 656 |
+
if (f.type.startsWith("image/")) r.readAsDataURL(f);
|
| 657 |
+
else r.readAsText(f);
|
| 658 |
});
|
| 659 |
+
$("fi").value = "";
|
| 660 |
}
|
| 661 |
+
|
| 662 |
async function sendMsg() {
|
| 663 |
if (busy) return;
|
| 664 |
+
const text = $("inp").value.trim();
|
| 665 |
if (!text && !files.length) return;
|
| 666 |
const s = cur();
|
| 667 |
+
if (!s.messages.length) { s.title = text.slice(0, 40) || "ملفات"; renderSessions(); }
|
| 668 |
+
const images = files.filter(f => f.type.startsWith("image/"));
|
|
|
|
| 669 |
|
| 670 |
+
// If images, describe each via caption endpoint
|
| 671 |
let imgDescriptions = [];
|
| 672 |
if (images.length) {
|
| 673 |
setBusy(true);
|
|
|
|
| 674 |
for (const img of images) {
|
| 675 |
try {
|
| 676 |
+
const b64 = img.data.split(",")[1];
|
| 677 |
+
const r = await call("caption", [b64]);
|
| 678 |
if (r?.ok && r.text) imgDescriptions.push(r.text);
|
| 679 |
+
else imgDescriptions.push("");
|
| 680 |
+
} catch (e) { imgDescriptions.push(""); }
|
| 681 |
}
|
| 682 |
setBusy(false);
|
| 683 |
}
|
| 684 |
|
| 685 |
let content = text;
|
| 686 |
if (imgDescriptions.length) {
|
| 687 |
+
content = imgDescriptions.map((d, i) => `[صورة ${i + 1}: ${d || "بدون وصف"}]`).join("\n") + (text ? "\n\n" + text : "");
|
| 688 |
}
|
| 689 |
+
const userMsg = { role: "user", content };
|
|
|
|
|
|
|
| 690 |
userMsg._files = files.map(f => f.name);
|
| 691 |
userMsg._images = images.map(f => f.data);
|
| 692 |
s.messages.push(userMsg);
|
| 693 |
files = []; chips();
|
| 694 |
+
$("inp").value = ""; $("inp").style.height = "auto";
|
| 695 |
persist(); renderSessions(); renderChat();
|
| 696 |
await ask(content);
|
| 697 |
}
|
|
|
|
| 700 |
if (busy) return;
|
| 701 |
setBusy(true);
|
| 702 |
const s = cur();
|
| 703 |
+
const bubble = addMsg("assistant", "");
|
| 704 |
+
const status = document.createElement("span");
|
| 705 |
+
status.style.cssText = "color:var(--mu);font-size:12px;display:block;margin-bottom:4px";
|
| 706 |
+
status.textContent = "⏳ تحضير النموذج...";
|
| 707 |
bubble.appendChild(status);
|
| 708 |
curReqId = uid();
|
| 709 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 710 |
try {
|
| 711 |
await ensureLoaded(cfg.model);
|
| 712 |
+
status.textContent = "⏳ جارٍ التوليد...";
|
| 713 |
|
| 714 |
+
const msgs = [{ role: "system", content: cfg.sys }, ...s.messages.map(m => ({ role: m.role, content: m.content }))];
|
| 715 |
+
logDiag("generate: " + cfg.model + " · maxTok=" + cfg.maxTok);
|
| 716 |
|
| 717 |
+
const r = await call("generate", [
|
| 718 |
cfg.model, J(msgs), curReqId,
|
| 719 |
parseInt(cfg.maxTok) || 256,
|
| 720 |
parseFloat(cfg.temp) || 0.7
|
| 721 |
+
]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 722 |
|
| 723 |
status.remove();
|
| 724 |
+
if (!r || r.ok === false) throw new Error((r && r.error) || "فشل التوليد");
|
| 725 |
+
|
| 726 |
+
const answer = (r.text || "").trim();
|
| 727 |
+
if (answer) {
|
| 728 |
+
bubble.innerHTML = md(answer, s) + actions(s.messages.length);
|
| 729 |
+
bubble.dataset.raw = answer;
|
| 730 |
+
s.messages.push({ role: "assistant", content: answer });
|
| 731 |
persist();
|
| 732 |
+
// Auto-open code panel if code found
|
| 733 |
+
const codeMatches = [...answer.matchAll(/```([\w+-]*)\n?([\s\S]*?)```/g)];
|
| 734 |
+
const last = codeMatches[codeMatches.length - 1];
|
| 735 |
+
if (last && qual((last[1] || "text").toLowerCase(), last[2].length)) {
|
| 736 |
+
const id = "a" + hash(last[2]);
|
| 737 |
if (s.artifacts?.find(x => x.id === id)) setTimeout(() => openArtifact(id), 100);
|
| 738 |
}
|
| 739 |
+
if (cfg.autoSpeak && !micOn) ttsSpeak(answer, bubble.querySelector(".spb"));
|
| 740 |
} else {
|
| 741 |
bubble.innerHTML = '<span style="color:var(--mu)">(رد فارغ — جرّب مرة أخرى)</span>';
|
| 742 |
}
|
| 743 |
} catch (e) {
|
| 744 |
bubble.remove();
|
| 745 |
+
addMsg("assistant", "⚠️ " + e.message);
|
| 746 |
+
logDiag("ask: " + e.message);
|
| 747 |
} finally {
|
| 748 |
status.remove();
|
| 749 |
curReqId = null;
|
| 750 |
setBusy(false);
|
| 751 |
+
$("inp").focus();
|
| 752 |
}
|
| 753 |
}
|
| 754 |
+
function stopGen() { if (curReqId) { call("cancel", [curReqId]).catch(() => {}); logDiag("cancel"); } }
|
| 755 |
|
| 756 |
+
/* ==================== TTS ==================== */
|
| 757 |
+
const hasTTS = "speechSynthesis" in window;
|
| 758 |
if (hasTTS) { speechSynthesis.getVoices(); speechSynthesis.onvoiceschanged = () => fillVoices(); }
|
| 759 |
const TTS = { id: 0 };
|
| 760 |
+
function ttsClean(t) {
|
| 761 |
+
return t.replace(/```[\s\S]*?```/g, " ").replace(/`([^`]*)`/g, "$1")
|
| 762 |
+
.replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/https?:\/\/\S+/g, "")
|
| 763 |
+
.replace(/[#*_>~|]+/g, " ").replace(/^\s*[-•]\s+/gm, "").replace(/\s+/g, " ").trim();
|
| 764 |
+
}
|
| 765 |
+
function ttsChunks(t) {
|
| 766 |
+
const o = []; let c = "";
|
| 767 |
+
for (const p of (t.match(/[^.!?؟…\n]+[.!?؟…\n]*/g) || [t])) {
|
| 768 |
+
if (c && (c + " " + p).length > 180) { o.push(c); c = p; } else c = c ? c + " " + p : p;
|
| 769 |
+
}
|
| 770 |
+
if (c) o.push(c);
|
| 771 |
+
return o.flatMap(x => x.length > 220 ? x.match(/.{1,200}(\s|$)/g) : [x]);
|
| 772 |
+
}
|
| 773 |
+
function pickVoice(t) {
|
| 774 |
+
const ar = (t.match(/[\u0600-\u06FF]/g) || []).length > (t.match(/[A-Za-z]/g) || []).length;
|
| 775 |
+
const lg = ar ? "ar" : "en";
|
| 776 |
+
const vs = speechSynthesis.getVoices();
|
| 777 |
+
return { ar, v: vs.find(x => x.name === cfg.ttsVoice && x.lang.toLowerCase().startsWith(lg)) || vs.find(x => x.lang.toLowerCase().startsWith(lg)) || null };
|
| 778 |
+
}
|
| 779 |
+
function ttsStop() {
|
| 780 |
+
if (!hasTTS) return;
|
| 781 |
+
TTS.id++;
|
| 782 |
+
speechSynthesis.cancel();
|
| 783 |
+
document.querySelectorAll(".spb.on").forEach(b => { b.classList.remove("on"); b.textContent = "🔊 استمع"; });
|
| 784 |
+
}
|
| 785 |
function ttsSpeak(text, btn) {
|
| 786 |
+
if (!hasTTS) return toast("⚠️ المتصفح لا يدعم النطق");
|
| 787 |
+
ttsStop();
|
| 788 |
+
const t = ttsClean(text || ""); if (!t) return;
|
| 789 |
+
const my = ++TTS.id;
|
| 790 |
+
const { v } = pickVoice(t);
|
| 791 |
+
const ch = ttsChunks(t); let i = 0;
|
| 792 |
+
if (btn) { btn.classList.add("on"); btn.textContent = "⏹ إيقاف"; }
|
| 793 |
const next = () => {
|
| 794 |
if (my !== TTS.id) return;
|
| 795 |
+
if (i >= ch.length) { if (btn) { btn.classList.remove("on"); btn.textContent = "🔊 استمع"; } return; }
|
| 796 |
const u = new SpeechSynthesisUtterance(ch[i++]);
|
| 797 |
+
u.rate = cfg.ttsRate || 1.5;
|
| 798 |
+
const ar = pickVoice(ch[i - 1]).ar;
|
| 799 |
+
u.lang = v ? v.lang : (ar ? "ar-SA" : "en-US");
|
| 800 |
+
if (v) u.voice = v;
|
| 801 |
+
u.onend = next; u.onerror = next;
|
| 802 |
+
speechSynthesis.speak(u);
|
| 803 |
};
|
| 804 |
next();
|
| 805 |
}
|
| 806 |
+
function speakMsg(b) {
|
| 807 |
+
if (b.classList.contains("on")) return ttsStop();
|
| 808 |
+
ttsSpeak(b.closest(".msg").dataset.raw || "", b);
|
| 809 |
+
}
|
| 810 |
+
function fillVoices() {
|
| 811 |
+
if (!hasTTS) return;
|
| 812 |
+
const vs = speechSynthesis.getVoices();
|
| 813 |
+
const sel = $("cVoice"); if (!sel) return;
|
| 814 |
+
sel.innerHTML = '<option value="">تلقائي (حسب لغة الرد)</option>' +
|
| 815 |
+
vs.map(v => `<option value="${esc(v.name)}" ${v.name === cfg.ttsVoice ? "selected" : ""}>${esc(v.name)} (${esc(v.lang)})</option>`).join("");
|
| 816 |
+
}
|
| 817 |
+
function testVoice() {
|
| 818 |
+
cfg.ttsRate = parseFloat($("cRate").value) || 1.5;
|
| 819 |
+
cfg.ttsVoice = $("cVoice").value;
|
| 820 |
+
ttsSpeak("مرحباً، هذا اختبار للصوت والسرعة.");
|
| 821 |
+
}
|
| 822 |
+
function updSpk() {
|
| 823 |
+
const b = $("spk");
|
| 824 |
+
if (!b) return;
|
| 825 |
+
b.classList.toggle("on", !!cfg.autoSpeak);
|
| 826 |
+
b.textContent = cfg.autoSpeak ? "🔊" : "🔇";
|
| 827 |
+
b.title = cfg.autoSpeak ? "النطق التلقائي: مفعل" : "النطق التلقائي: معطل";
|
| 828 |
+
}
|
| 829 |
+
function toggleAuto() {
|
| 830 |
+
if (!hasTTS) return toast("⚠️ المتصفح لا يدعم النطق");
|
| 831 |
+
cfg.autoSpeak = !cfg.autoSpeak; saveCfg(); updSpk();
|
| 832 |
+
if (cfg.autoSpeak) { const u = new SpeechSynthesisUtterance(" "); u.volume = 0; speechSynthesis.speak(u); }
|
| 833 |
+
else ttsStop();
|
| 834 |
+
toast(cfg.autoSpeak ? "🔊 النطق مفعل" : "🔇 النطق معطل");
|
| 835 |
+
}
|
| 836 |
|
| 837 |
+
/* ==================== STT ==================== */
|
| 838 |
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
| 839 |
+
let rec = null, micOn = false, micBase = "";
|
| 840 |
+
function micUI() {
|
| 841 |
+
const b = $("mic");
|
| 842 |
+
b.classList.toggle("on", micOn);
|
| 843 |
+
b.textContent = micOn ? "⏹" : "🎤";
|
| 844 |
+
b.title = micOn ? "إيقاف التفريغ" : "تفريغ صوتي";
|
| 845 |
+
$("inp").placeholder = micOn ? "🎤 أستمع..." : "اكتب رسالتك...";
|
| 846 |
+
}
|
| 847 |
+
async function toggleMic() {
|
| 848 |
+
if (!SR) return toast("⚠️ المتصفح لا يدعم التفريغ. استخدم Chrome/Edge");
|
| 849 |
if (micOn) { micOn = false; try { rec?.stop(); } catch {} micUI(); return; }
|
| 850 |
+
try { const st = await navigator.mediaDevices.getUserMedia({ audio: true }); st.getTracks().forEach(t => t.stop()); }
|
| 851 |
+
catch (e) { return toast("❌ تعذر الميكروفون: " + e.message); }
|
| 852 |
+
ttsStop();
|
| 853 |
+
micOn = true; micUI();
|
| 854 |
+
micBase = $("inp").value;
|
| 855 |
+
if (micBase && !/\s$/.test(micBase)) micBase += " ";
|
| 856 |
+
const r = rec = new SR();
|
| 857 |
+
r.lang = cfg.sttLang || "ar-SA";
|
| 858 |
+
r.continuous = false; r.interimResults = true; r.maxAlternatives = 1;
|
| 859 |
+
r.onresult = e => {
|
| 860 |
+
if (rec !== r || !micOn) return;
|
| 861 |
+
let t = "";
|
| 862 |
+
for (let i = 0; i < e.results.length; i++) t += e.results[i][0].transcript;
|
| 863 |
+
$("inp").value = micBase + t;
|
| 864 |
+
$("inp").dispatchEvent(new Event("input"));
|
| 865 |
+
};
|
| 866 |
+
r.onerror = e => {
|
| 867 |
+
if (rec !== r) return;
|
| 868 |
+
if (e.error === "no-speech" || e.error === "aborted") return;
|
| 869 |
+
micOn = false; micUI();
|
| 870 |
+
toast("❌ " + (e.error === "not-allowed" ? "الإذن مرفوض" : e.error));
|
| 871 |
+
};
|
| 872 |
+
r.onend = () => {
|
| 873 |
+
if (rec !== r) return;
|
| 874 |
+
if (micOn) setTimeout(() => { if (micOn && rec === r) { try { r.start(); } catch { micOn = false; micUI(); } } }, 150);
|
| 875 |
+
else micUI();
|
| 876 |
+
};
|
| 877 |
+
try { r.start(); } catch (e) { micOn = false; micUI(); toast("❌ " + e.message); }
|
| 878 |
+
}
|
| 879 |
+
|
| 880 |
+
/* ==================== Voice mode ==================== */
|
| 881 |
+
const V = { on: false, state: "", rec: null, text: "", sil: 0, chk: 0, pend: 0, tok: 0, spoken: 0, done: true, muted: false };
|
| 882 |
+
function vSet(st) {
|
| 883 |
+
V.state = st;
|
| 884 |
+
$("vc").className = "on " + st;
|
| 885 |
+
$("vS").textContent = ({ listening: "أستمع إليك...", thinking: "أفكر...", speaking: "أتحدث — المس الدائرة للمقاطعة", muted: "الميكروفون مكتوم" })[st] || "";
|
| 886 |
+
}
|
| 887 |
+
async function startVoice() {
|
| 888 |
+
if (!SR || !hasTTS) return toast("⚠️ المتصفح لا يدعم الصوت");
|
| 889 |
+
if (busy) return toast("⏳ انتظر انتهاء المهمة الحالية");
|
| 890 |
+
const u = new SpeechSynthesisUtterance(" "); u.volume = 0; speechSynthesis.speak(u);
|
| 891 |
+
$("vc").className = "on thinking"; $("vS").textContent = "جارٍ تهيئة الميكروفون...";
|
| 892 |
+
try { const st = await navigator.mediaDevices.getUserMedia({ audio: true }); st.getTracks().forEach(t => t.stop()); }
|
| 893 |
+
catch (e) { $("vc").className = ""; return toast("❌ " + e.message); }
|
| 894 |
if (micOn) { micOn = false; try { rec?.stop(); } catch {} micUI(); }
|
| 895 |
+
ttsStop();
|
| 896 |
+
Object.assign(V, { on: true, muted: false, done: true, pend: 0, spoken: 0, tok: V.tok + 1 });
|
| 897 |
+
vListen();
|
| 898 |
}
|
| 899 |
function vListen() {
|
| 900 |
if (!V.on || V.muted || busy) return;
|
| 901 |
+
V.text = ""; $("vT").textContent = "";
|
| 902 |
+
vSet("listening");
|
| 903 |
+
const r = V.rec = new SR();
|
| 904 |
+
r.lang = cfg.sttLang || "ar-SA";
|
| 905 |
+
r.continuous = false; r.interimResults = true;
|
| 906 |
+
r.onresult = e => {
|
| 907 |
+
if (V.rec !== r || V.state !== "listening") return;
|
| 908 |
+
let t = "", fin = false;
|
| 909 |
+
for (let i = 0; i < e.results.length; i++) { t += e.results[i][0].transcript; if (e.results[i].isFinal) fin = true; }
|
| 910 |
+
V.text = t; $("vT").textContent = t;
|
| 911 |
+
clearTimeout(V.sil);
|
| 912 |
+
if (fin) vSend(); else V.sil = setTimeout(vSend, 1200);
|
| 913 |
+
};
|
| 914 |
+
r.onerror = e => {
|
| 915 |
+
if (V.rec !== r) return;
|
| 916 |
+
if (e.error === "no-speech" || e.error === "aborted") return;
|
| 917 |
+
toast("❌ " + e.error);
|
| 918 |
+
};
|
| 919 |
+
r.onend = () => {
|
| 920 |
+
if (V.rec === r && V.on && V.state === "listening") setTimeout(() => { if (V.rec === r && V.on && V.state === "listening") vListen(); }, 200);
|
| 921 |
+
};
|
| 922 |
try { r.start(); } catch {}
|
| 923 |
}
|
| 924 |
function vSend() {
|
| 925 |
+
clearTimeout(V.sil);
|
| 926 |
+
const t = (V.text || "").trim();
|
| 927 |
+
if (!V.on || V.state !== "listening" || !t || busy) return;
|
| 928 |
const r = V.rec; V.rec = null; try { r?.abort(); } catch {}
|
| 929 |
+
V.done = false; V.spoken = 0; $("vR").textContent = "";
|
| 930 |
+
vSet("thinking");
|
| 931 |
+
$("inp").value = t;
|
| 932 |
+
ask(t).then(() => { V.done = true; vCheck(); });
|
| 933 |
}
|
| 934 |
function vSay(t) {
|
| 935 |
const tok = V.tok;
|
| 936 |
for (const c of ttsChunks(t).filter(Boolean)) {
|
| 937 |
const { v, ar } = pickVoice(c);
|
| 938 |
+
const u = new SpeechSynthesisUtterance(c);
|
| 939 |
+
u.rate = cfg.ttsRate || 1.5;
|
| 940 |
+
u.lang = v ? v.lang : (ar ? "ar-SA" : "en-US");
|
| 941 |
+
if (v) u.voice = v;
|
| 942 |
+
V.pend++;
|
| 943 |
+
u.onstart = () => { if (tok === V.tok && V.on) vSet("speaking"); };
|
| 944 |
u.onend = u.onerror = () => { if (tok !== V.tok) return; V.pend--; vCheck(); };
|
| 945 |
speechSynthesis.speak(u);
|
| 946 |
}
|
| 947 |
}
|
| 948 |
+
function vCheck() {
|
| 949 |
+
if (V.on && V.done && V.pend <= 0 && !V.chk) V.chk = setTimeout(() => { V.chk = 0; if (V.on && V.done && V.pend <= 0) vListen(); }, 300);
|
| 950 |
+
}
|
| 951 |
+
function vTap() {
|
| 952 |
+
if (!V.on) return;
|
| 953 |
+
if (V.state === "listening") return vSend();
|
| 954 |
+
if (V.state === "speaking" || V.state === "thinking") {
|
| 955 |
+
V.tok++; V.pend = 0; speechSynthesis.cancel();
|
| 956 |
+
if (busy && curReqId) call("cancel", [curReqId]).catch(() => {});
|
| 957 |
+
V.done = true; vListen();
|
| 958 |
+
}
|
| 959 |
+
}
|
| 960 |
+
function vMuteTog() {
|
| 961 |
+
if (!V.on) return;
|
| 962 |
+
V.muted = !V.muted;
|
| 963 |
+
$("vMute").textContent = V.muted ? "🔇" : "🎤";
|
| 964 |
+
if (V.muted) { clearTimeout(V.sil); const r = V.rec; V.rec = null; try { r?.abort(); } catch {} if (V.state === "listening") vSet("muted"); }
|
| 965 |
+
else { if (V.state === "muted") V.state = ""; if (!busy && V.pend <= 0) vListen(); }
|
| 966 |
+
}
|
| 967 |
+
function endVoice() {
|
| 968 |
+
if (!V.on && !$("vc").classList.contains("on")) return;
|
| 969 |
+
V.on = false; V.tok++; V.pend = 0;
|
| 970 |
+
clearTimeout(V.sil); clearTimeout(V.chk); V.chk = 0;
|
| 971 |
+
const r = V.rec; V.rec = null; try { r?.abort(); } catch {}
|
| 972 |
+
if (hasTTS) speechSynthesis.cancel();
|
| 973 |
+
$("vc").className = "";
|
| 974 |
+
}
|
| 975 |
|
| 976 |
+
/* ==================== Settings ==================== */
|
| 977 |
+
function openSet() { fillVoices(); $("set").classList.add("open"); closeAll(); }
|
| 978 |
function saveSet() {
|
| 979 |
+
cfg.sys = $("cSys").value;
|
| 980 |
+
cfg.temp = $("cTemp").value;
|
| 981 |
+
cfg.maxTok = Math.min(32000, Math.max(32, parseInt($("cMax").value) || 256));
|
| 982 |
+
cfg.topP = $("cTop").value;
|
| 983 |
+
cfg.ttsRate = parseFloat($("cRate").value) || 1.5;
|
| 984 |
+
cfg.ttsVoice = $("cVoice").value;
|
| 985 |
+
cfg.autoSpeak = $("cAutoSpeak").checked;
|
| 986 |
+
cfg.sttLang = $("cStt").value;
|
| 987 |
+
saveCfg(); updSpk();
|
| 988 |
+
$("set").classList.remove("open");
|
| 989 |
+
toast("✅ تم الحفظ");
|
| 990 |
}
|
| 991 |
|
| 992 |
+
/* ==================== Export ==================== */
|
| 993 |
function exportChat() {
|
| 994 |
+
const s = cur(); if (!s.messages.length) return toast("لا رسائل");
|
| 995 |
+
const t = "# " + s.title + "\n\n" + s.messages.map(m => {
|
| 996 |
+
let c = typeof m.content === "string" ? m.content : (m.content?.find?.(x => x.type === "text")?.text || "");
|
| 997 |
+
return "### " + (m.role === "user" ? "أنت" : "المساعد") + "\n" + c;
|
| 998 |
+
}).join("\n\n");
|
| 999 |
+
const a = document.createElement("a");
|
| 1000 |
+
a.href = URL.createObjectURL(new Blob([t], { type: "text/markdown" }));
|
| 1001 |
+
a.download = "chat-" + cid.slice(0, 8) + ".md"; a.click();
|
| 1002 |
+
toast("⬇ تم التصدير");
|
| 1003 |
+
}
|
| 1004 |
+
|
| 1005 |
+
/* ==================== UI helpers ==================== */
|
| 1006 |
+
function toggleSb() { $("sb").classList.toggle("open"); $("ov").classList.toggle("show", $("sb").classList.contains("open")); }
|
| 1007 |
+
function closeAll() { $("pp").classList.remove("open"); $("sb").classList.remove("open"); $("ov").classList.remove("show"); }
|
| 1008 |
+
document.addEventListener("click", e => {
|
| 1009 |
+
if (!$("pw").contains(e.target)) $("pp").classList.remove("open");
|
| 1010 |
+
if (innerWidth <= 768 && $("sb").classList.contains("open") && !$("sb").contains(e.target) && e.target.id !== "hb") closeAll();
|
| 1011 |
+
});
|
| 1012 |
+
$("inp").addEventListener("input", () => { const i = $("inp"); i.style.height = "auto"; i.style.height = Math.min(i.scrollHeight, 170) + "px"; });
|
| 1013 |
+
addEventListener("keydown", e => {
|
| 1014 |
+
if (e.key === "Escape") {
|
| 1015 |
+
endVoice(); closeAll();
|
| 1016 |
+
document.querySelectorAll(".md.open").forEach(m => m.classList.remove("open"));
|
| 1017 |
+
$("cp").classList.remove("full");
|
| 1018 |
+
}
|
| 1019 |
});
|
| 1020 |
|
| 1021 |
+
/* ==================== Boot ==================== */
|
| 1022 |
function boot() {
|
| 1023 |
+
applyTheme(); updSpk(); fillVoices();
|
| 1024 |
+
$("cSys").value = cfg.sys;
|
| 1025 |
+
$("cTemp").value = cfg.temp;
|
| 1026 |
+
$("cMax").value = cfg.maxTok;
|
| 1027 |
+
$("cMaxRange").value = cfg.maxTok;
|
| 1028 |
+
$("mMax").textContent = cfg.maxTok;
|
| 1029 |
+
$("cTop").value = cfg.topP;
|
| 1030 |
+
$("cRate").value = cfg.ttsRate;
|
| 1031 |
+
$("rV").textContent = cfg.ttsRate;
|
| 1032 |
+
$("cAutoSpeak").checked = !!cfg.autoSpeak;
|
| 1033 |
+
$("cStt").value = cfg.sttLang || "ar-SA";
|
| 1034 |
+
renderSessions();
|
| 1035 |
+
renderChat();
|
| 1036 |
+
setBusy(false);
|
| 1037 |
+
initModels();
|
| 1038 |
+
if (!SR) { $("mic").style.opacity = .4; $("mic").title = "المتصفح لا يدعم STT"; $("vcb").style.opacity = .4; $("vcb").title = "المتصفح لا يدعم الصوت"; }
|
| 1039 |
+
if (!hasTTS) { $("spk").style.opacity = .4; }
|
| 1040 |
}
|
| 1041 |
+
// Sync range <-> number
|
| 1042 |
+
document.addEventListener("DOMContentLoaded", () => {
|
| 1043 |
+
const cMax = $("cMax"), cRange = $("cMaxRange"), mMax = $("mMax");
|
| 1044 |
+
if (cMax) cMax.oninput = () => { const v = Math.min(32000, Math.max(32, parseInt(cMax.value) || 256)); cRange.value = v; mMax.textContent = v; };
|
| 1045 |
+
});
|
| 1046 |
boot();
|
| 1047 |
</script>
|
| 1048 |
</body>
|