Update index.html
Browse files- index.html +400 -680
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,6 +16,7 @@ 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 |
.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,8 +104,6 @@ code.in{background:var(--s2);padding:1px 6px;border-radius:6px;font-size:.9em;di
|
|
| 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,51 +125,49 @@ code.in{background:var(--s2);padding:1px 6px;border-radius:6px;font-size:.9em;di
|
|
| 126 |
<body>
|
| 127 |
<div id="ov" onclick="closeAll()"></div>
|
| 128 |
<aside id="sb">
|
| 129 |
-
<div class="top"><button class="btn" onclick="newChat()">
|
| 130 |
<div id="ss"></div>
|
| 131 |
-
<div class="ft"><span>محفوظة محلياً</span><button class="ib" id="thb" onclick="toggleTheme()">
|
| 132 |
</aside>
|
| 133 |
<main>
|
| 134 |
<div id="tb">
|
| 135 |
-
<button class="ib" id="hb" onclick="event.stopPropagation();toggleSb()">
|
| 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="تحميل النموذج">
|
| 140 |
-
<button class="ib" onclick="doUnload()" title="تفريغ النموذج">
|
| 141 |
<button class="ib" id="spk" onclick="toggleAuto()" title="النطق التلقائي"></button>
|
| 142 |
-
<button class="ib" onclick="openDiag()" title="التشخيص">
|
| 143 |
-
<button class="ib" onclick="openSet()" title="الإعدادات">
|
| 144 |
-
<button class="ib" onclick="exportChat()" title="تصدير">
|
| 145 |
-
<button class="ib" onclick="clearChat()" title="مسح">
|
| 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')">
|
| 153 |
<div id="pp" onclick="event.stopPropagation()"><div class="sc">
|
| 154 |
-
<button class="pi" onclick="$('fi').click();closeAll()">
|
| 155 |
</div></div>
|
| 156 |
</div>
|
| 157 |
-
<button class="ib" id="mic" onclick="toggleMic()" title="تفريغ صوتي">
|
| 158 |
-
<button class="ib" id="vcb" onclick="startVoice()" title="محادثة صوتية">
|
| 159 |
<div class="sp"></div>
|
| 160 |
-
<button id="stp" onclick="stopGen()">
|
| 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()">
|
| 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="تحديث">
|
| 170 |
-
<button class="ib" onclick="
|
| 171 |
-
<button class="ib" onclick="
|
| 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,520 +175,381 @@ code.in{background:var(--s2);padding:1px 6px;border-radius:6px;font-size:.9em;di
|
|
| 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">
|
| 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')">
|
| 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
|
| 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"
|
|
|
|
| 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"
|
| 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="
|
| 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')">
|
| 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
|
| 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 |
-
/* ============
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 !==
|
| 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 =
|
| 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 =
|
| 248 |
for (const l of p.split(/\r?\n/)) {
|
| 249 |
-
if (l.startsWith(
|
| 250 |
-
else if (l.startsWith(
|
| 251 |
}
|
| 252 |
let j = null; try { j = JSON.parse(data); } catch {}
|
| 253 |
-
if (ev ===
|
| 254 |
-
if (ev ===
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
}
|
| 257 |
}
|
| 258 |
-
if (last === undefined) throw new Error("انتهى الاتصال دون رد");
|
| 259 |
return last;
|
| 260 |
}
|
| 261 |
|
| 262 |
-
/* ============
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
}
|
| 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
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
cid = uid();
|
| 294 |
-
S = [{ id: cid, title: "دردشة جديدة", messages: [], ts: Date.now() }];
|
| 295 |
}
|
| 296 |
-
|
| 297 |
-
function persist() {
|
| 298 |
try {
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
}
|
|
|
|
|
|
|
| 306 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
function renderSessions() {
|
| 308 |
-
$(
|
| 309 |
-
<div class="se ${s.id === cid ?
|
| 310 |
-
|
| 311 |
-
<button class="x" onclick="delSession(event,'${s.id}')">
|
| 312 |
-
</div>`).join(
|
| 313 |
}
|
| 314 |
function openSession(id) { cid = id; persist(); renderSessions(); renderChat(); closeAll(); }
|
| 315 |
-
function delSession(e, id) {
|
| 316 |
-
|
| 317 |
-
|
| 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,
|
| 347 |
-
.replace(/^
|
| 348 |
-
.replace(/^
|
| 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,
|
| 355 |
-
.replace(/<br>(?=<(?:div|h\d|ul|li|pre|blockquote|button))/g,
|
| 356 |
-
.replace(/(<\/(?:div|h\d|ul|li|pre|blockquote|button)>)<br>/g,
|
| 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 =
|
| 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">
|
| 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} حرف · اضغط للعرض
|
| 370 |
-
</button>`;
|
| 371 |
}
|
| 372 |
-
|
|
|
|
| 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(
|
| 381 |
-
const
|
| 382 |
-
const
|
| 383 |
-
|
| 384 |
-
if (
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
}
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
$(
|
| 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)">
|
| 414 |
-
<button onclick="regenFrom(${idx})">
|
| 415 |
-
<button class="spb" onclick="speakMsg(this)"
|
| 416 |
</div>`;
|
| 417 |
}
|
| 418 |
-
function copyMsg(b) { navigator.clipboard.writeText(b.closest(
|
| 419 |
function renderChat() {
|
| 420 |
-
const s = cur(); $(
|
| 421 |
if (!s || !s.messages.length) {
|
| 422 |
-
$(
|
| 423 |
return;
|
| 424 |
}
|
| 425 |
s.messages.forEach((m, i) => {
|
| 426 |
-
if (m.role ===
|
| 427 |
-
let txt =
|
| 428 |
-
if (typeof m.content ===
|
| 429 |
-
else if (Array.isArray(m.content)) {
|
| 430 |
-
|
| 431 |
-
|
| 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 |
-
|
| 445 |
-
|
| 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 |
-
/* ============
|
| 453 |
-
|
| 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 ===
|
| 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(
|
| 468 |
-
|
| 469 |
-
|
| 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.
|
| 482 |
-
|
| 483 |
-
$(
|
| 484 |
-
|
| 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 |
-
|
| 509 |
-
|
| 510 |
-
$(
|
| 511 |
-
$(
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
function
|
| 521 |
-
function
|
| 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(
|
| 657 |
-
else r.readAsText(f);
|
| 658 |
});
|
| 659 |
-
$(
|
| 660 |
}
|
| 661 |
-
|
| 662 |
async function sendMsg() {
|
| 663 |
if (busy) return;
|
| 664 |
-
const text = $(
|
| 665 |
if (!text && !files.length) return;
|
| 666 |
const s = cur();
|
| 667 |
-
if (!s.messages.length) { s.title = text.slice(0, 40) ||
|
| 668 |
-
const images = files.filter(f => f.type.startsWith(
|
|
|
|
| 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(
|
| 677 |
-
const r = await call(
|
| 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 ||
|
| 688 |
}
|
| 689 |
-
|
|
|
|
|
|
|
| 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 |
-
$(
|
| 695 |
persist(); renderSessions(); renderChat();
|
| 696 |
await ask(content);
|
| 697 |
}
|
|
@@ -700,349 +558,211 @@ async function ask(text) {
|
|
| 700 |
if (busy) return;
|
| 701 |
setBusy(true);
|
| 702 |
const s = cur();
|
| 703 |
-
const bubble = addMsg(
|
| 704 |
-
const status = document.createElement(
|
| 705 |
-
status.style.cssText =
|
| 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:
|
| 715 |
-
logDiag(
|
| 716 |
|
| 717 |
-
const
|
| 718 |
cfg.model, J(msgs), curReqId,
|
| 719 |
parseInt(cfg.maxTok) || 256,
|
| 720 |
parseFloat(cfg.temp) || 0.7
|
| 721 |
-
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 722 |
|
| 723 |
status.remove();
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
bubble.dataset.raw = answer;
|
| 730 |
-
s.messages.push({ role: "assistant", content: answer });
|
| 731 |
persist();
|
| 732 |
-
|
| 733 |
-
const
|
| 734 |
-
|
| 735 |
-
|
| 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(
|
| 740 |
} else {
|
| 741 |
bubble.innerHTML = '<span style="color:var(--mu)">(رد فارغ — جرّب مرة أخرى)</span>';
|
| 742 |
}
|
| 743 |
} catch (e) {
|
| 744 |
bubble.remove();
|
| 745 |
-
addMsg(
|
| 746 |
-
logDiag(
|
| 747 |
} finally {
|
| 748 |
status.remove();
|
| 749 |
curReqId = null;
|
| 750 |
setBusy(false);
|
| 751 |
-
$(
|
| 752 |
}
|
| 753 |
}
|
| 754 |
-
function stopGen() { if (curReqId) { call(
|
| 755 |
|
| 756 |
-
/* ============
|
| 757 |
-
const hasTTS =
|
| 758 |
if (hasTTS) { speechSynthesis.getVoices(); speechSynthesis.onvoiceschanged = () => fillVoices(); }
|
| 759 |
const TTS = { id: 0 };
|
| 760 |
-
function ttsClean(t) {
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 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
|
| 789 |
-
|
| 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(
|
| 796 |
const u = new SpeechSynthesisUtterance(ch[i++]);
|
| 797 |
-
u.rate = cfg.ttsRate || 1.5;
|
| 798 |
-
|
| 799 |
-
u.
|
| 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 |
-
|
| 808 |
-
|
| 809 |
-
}
|
| 810 |
-
function
|
| 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 |
-
/* ============
|
| 838 |
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
| 839 |
-
|
| 840 |
-
function
|
| 841 |
-
|
| 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 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
if (
|
| 856 |
-
|
| 857 |
-
r.
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 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 |
-
|
| 897 |
-
vListen();
|
| 898 |
}
|
| 899 |
function vListen() {
|
| 900 |
if (!V.on || V.muted || busy) return;
|
| 901 |
-
V.text =
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
r.
|
| 905 |
-
r.
|
| 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 |
-
|
| 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; $(
|
| 930 |
-
|
| 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.
|
| 940 |
-
u.
|
| 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 |
-
|
| 950 |
-
}
|
| 951 |
-
function
|
| 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 |
-
/* ============
|
| 977 |
-
function openSet() { fillVoices(); $(
|
| 978 |
function saveSet() {
|
| 979 |
-
cfg.sys = $(
|
| 980 |
-
cfg.
|
| 981 |
-
cfg.
|
| 982 |
-
cfg.
|
| 983 |
-
cfg.ttsRate = parseFloat($(
|
| 984 |
-
cfg.
|
| 985 |
-
|
| 986 |
-
cfg.sttLang = $("cStt").value;
|
| 987 |
-
saveCfg(); updSpk();
|
| 988 |
-
$("set").classList.remove("open");
|
| 989 |
-
toast("✅ تم الحفظ");
|
| 990 |
}
|
| 991 |
|
| 992 |
-
/* ============
|
| 993 |
function exportChat() {
|
| 994 |
-
const s = cur(); if (!s.messages.length) return toast(
|
| 995 |
-
const t =
|
| 996 |
-
|
| 997 |
-
return
|
| 998 |
-
}).join(
|
| 999 |
-
const a = document.createElement(
|
| 1000 |
-
a.
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
}
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
$("cp").classList.remove("full");
|
| 1018 |
-
}
|
| 1019 |
});
|
| 1020 |
|
| 1021 |
-
/* ============
|
| 1022 |
function boot() {
|
| 1023 |
-
applyTheme(); updSpk(); fillVoices();
|
| 1024 |
-
$(
|
| 1025 |
-
$(
|
| 1026 |
-
$(
|
| 1027 |
-
$(
|
| 1028 |
-
$(
|
| 1029 |
-
$(
|
| 1030 |
-
|
| 1031 |
-
$(
|
| 1032 |
-
$(
|
| 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>
|
|
|
|
| 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 Lite</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 |
+
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 |
.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 |
<body>
|
| 126 |
<div id="ov" onclick="closeAll()"></div>
|
| 127 |
<aside id="sb">
|
| 128 |
+
<div class="top"><button class="btn" onclick="newChat()"><i data-i="plus"></i> محادثة جديدة</button></div>
|
| 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()"><i data-i="menu"></i></button>
|
| 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="تحميل النموذج"><i data-i="down"></i></button>
|
| 139 |
+
<button class="ib" onclick="doUnload()" title="تفريغ النموذج"><i data-i="trash"></i></button>
|
| 140 |
<button class="ib" id="spk" onclick="toggleAuto()" title="النطق التلقائي"></button>
|
| 141 |
+
<button class="ib" onclick="openDiag()" title="التشخيص"><i data-i="pulse"></i></button>
|
| 142 |
+
<button class="ib" onclick="openSet()" title="الإعدادات"><i data-i="set"></i></button>
|
| 143 |
+
<button class="ib" onclick="exportChat()" title="تصدير"><i data-i="down"></i></button>
|
| 144 |
+
<button class="ib" onclick="clearChat()" title="مسح"><i data-i="trash"></i></button>
|
| 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')"><i data-i="plus" data-z="22"></i></button>
|
| 152 |
<div id="pp" onclick="event.stopPropagation()"><div class="sc">
|
| 153 |
+
<button class="pi" onclick="$('fi').click();closeAll()"><i data-i="clip"></i> إرفاق صور وملفات</button>
|
| 154 |
</div></div>
|
| 155 |
</div>
|
| 156 |
+
<button class="ib" id="mic" onclick="toggleMic()" title="تفريغ صوتي"><i data-i="mic"></i></button>
|
| 157 |
+
<button class="ib" id="vcb" onclick="startVoice()" title="محادثة صوتية"><i data-i="wave"></i></button>
|
| 158 |
<div class="sp"></div>
|
| 159 |
+
<button id="stp" onclick="stopGen()"><i data-i="stop"></i></button><button id="snd" onclick="sendMsg()"><i data-i="send" data-z="20"></i></button>
|
| 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()"><i data-i="x"></i></button><span class="tt" id="cpT"></span>
|
| 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="تحديث"><i data-i="refresh"></i></button><button class="ib" onclick="newTab()" title="تبويب جديد"><i data-i="ext"></i></button>
|
| 169 |
+
<button class="ib" onclick="copyArt()" title="نسخ"><i data-i="copy"></i></button><button class="ib" onclick="dlArt()" title="تنزيل"><i data-i="down"></i></button>
|
| 170 |
+
<button class="ib" onclick="$('cp').classList.toggle('full')" title="ملء الشاشة"><i data-i="full"></i></button>
|
|
|
|
|
|
|
| 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 |
</div>
|
| 176 |
</div>
|
| 177 |
<div id="vc">
|
| 178 |
+
<button class="ib vx" onclick="endVoice()" title="إنهاء">✕</button>
|
| 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()" title="كتم الميكروفون" style="border:1px solid var(--bd);width:46px;height:46px"><i data-i="mic" data-z="22"></i></button><button class="btn" onclick="endVoice()">إنهاء المحادثة</button></div>
|
| 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')"><i data-i="x"></i></button></h2>
|
| 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><option value="ar-MA">العربية (المغرب)</option><option value="ar-EG">العربية (مصر)</option>
|
| 203 |
+
<option value="en-US">English</option><option value="fr-FR">Français</option>
|
|
|
|
|
|
|
|
|
|
| 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')"><i data-i="x"></i></button></span></h2>
|
| 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 esc = s => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
|
|
|
|
|
|
|
|
| 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 |
+
/* ============ Theme ============ */
|
| 263 |
+
function applyTheme() { document.documentElement.dataset.theme = cfg.theme; $('thb').innerHTML = svg(cfg.theme === 'dark' ? 'sun' : 'moon'); }
|
| 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}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: J({ data: args }) });
|
|
|
|
|
|
|
| 270 |
let r = await post();
|
| 271 |
+
if (r.status === 404 && base !== '/call') { base = '/call'; r = await post(); }
|
| 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 = '', last = '', lastText = '';
|
| 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 = 'message', data = '';
|
| 285 |
for (const l of p.split(/\r?\n/)) {
|
| 286 |
+
if (l.startsWith('event:')) ev = l.slice(6).trim();
|
| 287 |
+
else if (l.startsWith('data:')) data += l.slice(5).trim();
|
| 288 |
}
|
| 289 |
let j = null; try { j = JSON.parse(data); } catch {}
|
| 290 |
+
if (ev === 'error') throw new Error(typeof j === 'string' ? j : 'خطأ من الخادم');
|
| 291 |
+
if (ev === 'generating' && Array.isArray(j) && j[0]) {
|
| 292 |
+
const obj = j[0];
|
| 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 |
+
/* ============ Models ============ */
|
| 308 |
+
async function initModels() {
|
| 309 |
+
try {
|
| 310 |
+
const r = await call('models');
|
| 311 |
+
const list = r.models || [];
|
| 312 |
+
list.forEach(m => MODELS[m.id] = m);
|
| 313 |
+
renderModelSelect();
|
| 314 |
+
await refreshStatus();
|
| 315 |
+
} catch (e) { toast('⚠️ تعذر جلب النماذج: ' + e.message); logDiag('initModels: ' + e.message); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
}
|
| 317 |
+
function renderModelSelect() {
|
| 318 |
+
const sel = $('mp'), groups = {};
|
| 319 |
+
Object.values(MODELS).forEach(m => { const g = m.group || 'أخرى'; (groups[g] = groups[g] || []).push(m); });
|
| 320 |
+
sel.innerHTML = '';
|
| 321 |
+
for (const [g, list] of Object.entries(groups)) {
|
| 322 |
+
const og = document.createElement('optgroup'); og.label = g;
|
| 323 |
+
list.forEach(m => {
|
| 324 |
+
const o = document.createElement('option');
|
| 325 |
+
o.value = m.id;
|
| 326 |
+
o.textContent = `${m.repo.split('/').pop()} (${m.size || ''})`;
|
| 327 |
+
og.appendChild(o);
|
| 328 |
+
});
|
| 329 |
+
sel.appendChild(og);
|
| 330 |
+
}
|
| 331 |
+
sel.value = MODELS[cfg.model] ? cfg.model : (Object.keys(MODELS).find(k => MODELS[k].group !== 'aux') || '');
|
|
|
|
|
|
|
| 332 |
}
|
| 333 |
+
async function refreshStatus() {
|
|
|
|
| 334 |
try {
|
| 335 |
+
STATUS = await call('status') || {};
|
| 336 |
+
const id = $('mp').value, st = STATUS[id];
|
| 337 |
+
const led = $('led'), lt = $('ledT');
|
| 338 |
+
if (st?.state === 'ready') { led.className = 'led on'; lt.textContent = 'جاهز'; }
|
| 339 |
+
else if (st?.state === 'loading' || st?.state === 'downloading') { led.className = 'led wr'; lt.textContent = (st.state === 'downloading' ? 'تنزيل ' : 'تحميل ') + Math.round(st.pct || 0) + '%'; }
|
| 340 |
+
else if (st?.state === 'error') { led.className = 'led'; led.style.background = 'var(--er)'; lt.textContent = 'خطأ'; }
|
| 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 |
+
$('ss').innerHTML = S.slice().sort((a, b) => b.ts - a.ts).map(s => `
|
| 371 |
+
<div class="se ${s.id === cid ? 'on' : ''}" onclick="openSession('${s.id}')">
|
| 372 |
+
${svg('chat', 15)} <span>${esc(s.title)}</span>
|
| 373 |
+
<button class="x" onclick="delSession(event,'${s.id}')">${svg('trash', 15)}</button>
|
| 374 |
+
</div>`).join('');
|
| 375 |
}
|
| 376 |
function openSession(id) { cid = id; persist(); renderSessions(); renderChat(); closeAll(); }
|
| 377 |
+
function delSession(e, id) { e.stopPropagation(); if (!confirm('حذف؟')) return; S = S.filter(s => s.id !== id); if (cid === id) { cid = S[0]?.id; if (!cid) return newChat(); } persist(); renderSessions(); renderChat(); }
|
| 378 |
+
function newChat() { const s = { id: uid(), title: 'دردشة جديدة', messages: [], artifacts: [], ts: Date.now() }; S.unshift(s); cid = s.id; persist(); renderSessions(); renderChat(); closeAll(); }
|
| 379 |
+
function clearChat() { if (!confirm('مسح المحادثة؟')) return; const s = cur(); if (!s) return; s.messages = []; s.artifacts = []; s.title = 'دردشة جديدة'; persist(); renderSessions(); renderChat(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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) => { cb.push({ l: (l || 'text').toLowerCase(), c }); return '\u0000' + (cb.length - 1) + '\u0000'; });
|
|
|
|
|
|
|
|
|
|
| 388 |
let h = esc(t);
|
| 389 |
h = h.replace(/`([^`\n]+)`/g, '<code class="in">$1</code>')
|
| 390 |
+
.replace(/^### (.*)$/gm, '<h3>$1</h3>').replace(/^## (.*)$/gm, '<h2>$1</h2>').replace(/^# (.*)$/gm, '<h1>$1</h1>')
|
| 391 |
+
.replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>').replace(/^> (.*)$/gm, '<blockquote>$1</blockquote>')
|
| 392 |
+
.replace(/^[-*] (.*)$/gm, '<li>$1</li>').replace(/(?:<li>.*<\/li>\n?)+/g, m => '<ul>' + m.trim() + '</ul>')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
|
| 394 |
+
.replace(/\n/g, '<br>')
|
| 395 |
+
.replace(/<br>(?=<(?:div|h\d|ul|li|pre|blockquote|button))/g, '')
|
| 396 |
+
.replace(/(<\/(?:div|h\d|ul|li|pre|blockquote|button)>)<br>/g, '$1');
|
| 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 = 'a' + hash(c);
|
| 401 |
let art = (s.artifacts = s.artifacts || []).find(x => x.id === id);
|
| 402 |
+
if (!art) { art = { id, lang: l, content: c, title: l === 'html' ? 'index.html' : l === 'svg' ? 'image.svg' : 'file.' + l }; s.artifacts.push(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">${svg('file', 20)}</span>
|
| 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></button>`;
|
|
|
|
| 406 |
}
|
| 407 |
+
const isP = prevable(l);
|
| 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) { const code = b.closest('.cw').querySelector('pre').textContent; navigator.clipboard.writeText(code).then(() => toast('📋 تم')); }
|
|
|
|
|
|
|
|
|
|
| 412 |
function openCodePanel(b) {
|
| 413 |
+
const cw = b.closest('.cw'); const code = cw.querySelector('pre').textContent; const lang = b.dataset.lang || 'html';
|
| 414 |
+
const s = cur(); if (!s) return;
|
| 415 |
+
const id = 'a' + hash(code);
|
| 416 |
+
let art = (s.artifacts = s.artifacts || []).find(x => x.id === id);
|
| 417 |
+
if (!art) { art = { id, lang, content: code, title: lang === 'html' ? 'index.html' : 'image.svg' }; s.artifacts.push(art); }
|
| 418 |
+
persist(); openArtifact(id);
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
/* ============ Render ============ */
|
| 422 |
+
function addMsg(role, text = '', fnames = [], idx = null, images = []) {
|
| 423 |
+
$('ci').querySelector('.welcome')?.remove();
|
| 424 |
+
const d = document.createElement('div');
|
| 425 |
+
d.className = 'msg ' + role; d.dataset.raw = text || '';
|
| 426 |
+
const body = role === 'bot' ? md(text, cur()) : esc(text).replace(/\n/g, '<br>');
|
| 427 |
+
d.innerHTML = images.map(src => `<img class="chat-img" src="${esc(src)}" alt="صورة">`).join('') + body
|
| 428 |
+
+ (fnames?.length ? `<div class="files">📎 ${fnames.map(esc).join('، ')}</div>` : '')
|
| 429 |
+
+ (idx != null && role === 'bot' ? actions(idx) : '');
|
| 430 |
+
$('ci').appendChild(d);
|
| 431 |
+
const c = $('chat'); c.scrollTop = c.scrollHeight;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
return d;
|
| 433 |
}
|
| 434 |
function actions(idx) {
|
| 435 |
return `<div class="ma">
|
| 436 |
+
<button onclick="copyMsg(this)">${svg('copy', 14)} نسخ</button>
|
| 437 |
+
<button onclick="regenFrom(${idx})">${svg('refresh', 14)} إعادة</button>
|
| 438 |
+
<button class="spb" onclick="speakMsg(this)">${svg('spk', 14)} استمع</button>
|
| 439 |
</div>`;
|
| 440 |
}
|
| 441 |
+
function copyMsg(b) { navigator.clipboard.writeText(b.closest('.msg').dataset.raw || '').then(() => toast('📋 تم')); }
|
| 442 |
function renderChat() {
|
| 443 |
+
const s = cur(); $('ci').innerHTML = '';
|
| 444 |
if (!s || !s.messages.length) {
|
| 445 |
+
$('ci').innerHTML = '<div class="welcome"><h2>كيف يمكنني مساعدتك اليوم؟</h2><p>اختر النموذج ثم اكتب رسالتك.</p></div>';
|
| 446 |
return;
|
| 447 |
}
|
| 448 |
s.messages.forEach((m, i) => {
|
| 449 |
+
if (m.role === 'user') {
|
| 450 |
+
let txt = '', imgs = [];
|
| 451 |
+
if (typeof m.content === 'string') txt = m.content;
|
| 452 |
+
else if (Array.isArray(m.content)) m.content.forEach(c => { if (c.type === 'text') txt = c.text; if (c.type === 'image_url') imgs.push(c.image_url.url); });
|
| 453 |
+
addMsg('user', txt, m._files, i, imgs);
|
| 454 |
+
} else if (m.role === 'assistant' && m.content) addMsg('bot', m.content, null, i);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
});
|
|
|
|
| 456 |
}
|
| 457 |
async function regenFrom(i) {
|
| 458 |
+
if (busy) return; const s = cur(); let u = i; while (u >= 0 && s.messages[u].role !== 'user') u--;
|
| 459 |
+
if (u < 0) return; s.messages = s.messages.slice(0, u + 1); persist(); renderChat();
|
| 460 |
+
const m = s.messages[u]; const txt = typeof m.content === 'string' ? m.content : '';
|
|
|
|
|
|
|
|
|
|
| 461 |
await ask(txt);
|
| 462 |
}
|
| 463 |
|
| 464 |
+
/* ============ Code Panel ============ */
|
| 465 |
+
const L = { t: 0, last: 0, code: '', lang: 'html', on: false, closed: false };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 === '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;
|
| 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('message', e => { if (e.data && e.data.__pe) { const b = $('pe'); b.textContent = '⚠ ' + e.data.m + ' (اضغط للإخفاء)'; b.style.display = 'block'; } });
|
| 474 |
+
const prev = (code, lang) => { $('pe').style.display = 'none'; $('cf').srcdoc = wrap(code, lang); };
|
| 475 |
+
function setView(v) { $('cp').dataset.v = v; document.querySelectorAll('.tabs button').forEach(b => b.classList.toggle('on', b.dataset.v === v)); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
function liveWrite(lang, code) {
|
| 477 |
+
const st = !L.on; L.on = true; L.code = code; L.lang = lang;
|
| 478 |
+
if (st) { L.closed = false; L.last = 0; $('cp').classList.add('open'); setView(prevable(lang) ? 'split' : 'code'); }
|
| 479 |
+
$('cpT').textContent = '✍ يكتب (' + lang + ')...';
|
| 480 |
+
const el = $('cpS'), near = el.scrollTop + el.clientHeight >= el.scrollHeight - 40;
|
| 481 |
+
$('cpC').textContent = code; if (near) el.scrollTop = el.scrollHeight;
|
|
|
|
|
|
|
| 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() { clearTimeout(L.t); if (L.on && prevable(L.lang) && L.code && !L.closed) prev(L.code, L.lang); L.on = false; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
function parseLive(f) {
|
| 489 |
+
const p = f.split('```');
|
| 490 |
+
if (p.length % 2 === 0) { const g = p[p.length - 1], n = g.indexOf('\n'); if (n < 0) return { inside: true, lang: 'text', code: '' }; return { inside: true, lang: (g.slice(0, n).trim() || 'text').toLowerCase(), code: g.slice(n + 1) }; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
return { inside: false };
|
| 492 |
}
|
| 493 |
function openArtifact(id) {
|
| 494 |
+
const a = cur()?.artifacts?.find(x => x.id === id); if (!a) return toast('❌ العنصر غير موجود');
|
| 495 |
+
liveEnd(); curArt = a; $('cpT').textContent = a.title; $('cpC').textContent = a.content;
|
| 496 |
+
if (prevable(a.lang)) { prev(a.content, a.lang); setView('split'); }
|
| 497 |
+
else { $('cf').srcdoc = '<body style="font-family:sans-serif;color:#888;display:flex;align-items:center;justify-content:center;height:100vh">لا معاينة لهذا النوع</body>'; setView('code'); }
|
| 498 |
+
$('cp').classList.add('open');
|
| 499 |
+
}
|
| 500 |
+
function closePanel() { $('cp').classList.remove('open', 'full'); if (L.on) L.closed = true; clearTimeout(L.t); }
|
| 501 |
+
function reloadPrev() { const c = curArt ? curArt.content : L.code, l = curArt ? curArt.lang : L.lang; c ? prev(c, l) : toast('لا محتوى'); }
|
| 502 |
+
function newTab() { const c = curArt ? curArt.content : L.code, l = curArt ? curArt.lang : L.lang; if (!c) return toast('لا محتوى'); const w = open('about:blank', '_blank'); if (w) { w.document.write(wrap(c, l)); w.document.close(); } }
|
| 503 |
+
function copyArt() { const c = curArt ? curArt.content : L.code; if (!c) return toast('لا كود'); navigator.clipboard.writeText(c).then(() => toast('📋 تم')); }
|
| 504 |
+
function dlArt() { if (!curArt) return toast('لا ملف'); const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([curArt.content], { type: 'text/plain;charset=utf-8' })); a.download = curArt.title; a.click(); }
|
| 505 |
+
|
| 506 |
+
/* ============ Chat Send with Smart Streaming ============ */
|
| 507 |
+
function setBusy(v) { busy = v; $('snd').style.display = v ? 'none' : 'flex'; $('stp').style.display = v ? 'flex' : 'none'; $('mp').disabled = v; }
|
| 508 |
+
function chips() { $('chips').innerHTML = files.map((f, i) => `<span class="chip">${f.type.startsWith('image/') ? '🖼' : '📎'} ${esc(f.name)}<button onclick="files.splice(${i},1);chips()">✕</button></span>`).join(''); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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('image/')) r.readAsDataURL(f); else r.readAsText(f);
|
|
|
|
| 514 |
});
|
| 515 |
+
$('fi').value = '';
|
| 516 |
}
|
|
|
|
| 517 |
async function sendMsg() {
|
| 518 |
if (busy) return;
|
| 519 |
+
const text = $('inp').value.trim();
|
| 520 |
if (!text && !files.length) return;
|
| 521 |
const s = cur();
|
| 522 |
+
if (!s.messages.length) { s.title = text.slice(0, 40) || 'ملفات'; renderSessions(); }
|
| 523 |
+
const images = files.filter(f => f.type.startsWith('image/'));
|
| 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(',')[1];
|
| 533 |
+
const r = await call('caption', [b64]);
|
| 534 |
if (r?.ok && r.text) imgDescriptions.push(r.text);
|
| 535 |
+
else imgDescriptions.push('');
|
| 536 |
+
} catch (e) { imgDescriptions.push(''); logDiag('caption fail: ' + e.message); }
|
| 537 |
}
|
| 538 |
setBusy(false);
|
| 539 |
}
|
| 540 |
|
| 541 |
let content = text;
|
| 542 |
if (imgDescriptions.length) {
|
| 543 |
+
content = imgDescriptions.map((d, i) => `[صورة ${i + 1}: ${d || 'بدون وصف'}]`).join('\n') + (text ? '\n\n' + text : '');
|
| 544 |
}
|
| 545 |
+
if (texts.length) content += '\n\n' + texts.map(f => `--- ${f.name} ---\n${f.data}`).join('\n');
|
| 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 |
+
$('inp').value = ''; $('inp').style.height = 'auto';
|
| 553 |
persist(); renderSessions(); renderChat();
|
| 554 |
await ask(content);
|
| 555 |
}
|
|
|
|
| 558 |
if (busy) return;
|
| 559 |
setBusy(true);
|
| 560 |
const s = cur();
|
| 561 |
+
const bubble = addMsg('bot', '');
|
| 562 |
+
const status = document.createElement('span');
|
| 563 |
+
status.style.cssText = 'color:var(--mu);font-size:12px;display:block;margin-bottom:4px';
|
| 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: 'system', content: cfg.sys }, ...s.messages.map(m => ({ role: m.role, content: m.content }))];
|
| 577 |
+
logDiag('generate: ' + cfg.model + ' maxTok=' + cfg.maxTok);
|
| 578 |
|
| 579 |
+
const answer = await call('generate', [
|
| 580 |
cfg.model, J(msgs), curReqId,
|
| 581 |
parseInt(cfg.maxTok) || 256,
|
| 582 |
parseFloat(cfg.temp) || 0.7
|
| 583 |
+
], (partial) => {
|
| 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 |
+
const finalText = (answer || totalText || '').trim();
|
| 596 |
+
if (finalText) {
|
| 597 |
+
bubble.innerHTML = md(finalText, s) + actions(s.messages.length);
|
| 598 |
+
bubble.dataset.raw = finalText;
|
| 599 |
+
s.messages.push({ role: 'assistant', content: finalText });
|
|
|
|
|
|
|
| 600 |
persist();
|
| 601 |
+
const codeMatches = [...finalText.matchAll(/```([\w+-]*)\n?([\s\S]*?)```/g)];
|
| 602 |
+
const lastCode = codeMatches[codeMatches.length - 1];
|
| 603 |
+
if (lastCode && qual((lastCode[1] || 'text').toLowerCase(), lastCode[2].length)) {
|
| 604 |
+
const id = 'a' + hash(lastCode[2]);
|
|
|
|
| 605 |
if (s.artifacts?.find(x => x.id === id)) setTimeout(() => openArtifact(id), 100);
|
| 606 |
}
|
| 607 |
+
if (cfg.autoSpeak && !micOn) ttsSpeak(finalText, bubble.querySelector('.spb'));
|
| 608 |
} else {
|
| 609 |
bubble.innerHTML = '<span style="color:var(--mu)">(رد فارغ — جرّب مرة أخرى)</span>';
|
| 610 |
}
|
| 611 |
} catch (e) {
|
| 612 |
bubble.remove();
|
| 613 |
+
addMsg('bot', '⚠️ ' + e.message);
|
| 614 |
+
logDiag('ask: ' + e.message);
|
| 615 |
} finally {
|
| 616 |
status.remove();
|
| 617 |
curReqId = null;
|
| 618 |
setBusy(false);
|
| 619 |
+
$('inp').focus();
|
| 620 |
}
|
| 621 |
}
|
| 622 |
+
function stopGen() { if (curReqId) { call('cancel', [curReqId]).catch(() => {}); logDiag('cancel'); } }
|
| 623 |
|
| 624 |
+
/* ============ TTS ============ */
|
| 625 |
+
const hasTTS = 'speechSynthesis' in window;
|
| 626 |
if (hasTTS) { speechSynthesis.getVoices(); speechSynthesis.onvoiceschanged = () => fillVoices(); }
|
| 627 |
const TTS = { id: 0 };
|
| 628 |
+
function ttsClean(t) { return t.replace(/```[\s\S]*?```/g, ' ').replace(/`([^`]*)`/g, '$1').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/https?:\/\/\S+/g, '').replace(/[#*_>~|]+/g, ' ').replace(/^\s*[-•]\s+/gm, '').replace(/\s+/g, ' ').trim(); }
|
| 629 |
+
function ttsChunks(t) { const o = []; let c = ''; for (const p of (t.match(/[^.!?؟…\n]+[.!?؟…\n]*/g) || [t])) { if (c && (c + ' ' + p).length > 180) { o.push(c); c = p; } else c = c ? c + ' ' + p : p; } if (c) o.push(c); return o.flatMap(x => x.length > 220 ? x.match(/.{1,200}(\s|$)/g) : [x]); }
|
| 630 |
+
function pickVoice(t) { const ar = (t.match(/[\u0600-\u06FF]/g) || []).length > (t.match(/[A-Za-z]/g) || []).length; const lg = ar ? 'ar' : 'en'; const vs = speechSynthesis.getVoices(); return { ar, v: vs.find(x => x.name === cfg.ttsVoice && x.lang.toLowerCase().startsWith(lg)) || vs.find(x => x.lang.toLowerCase().startsWith(lg)) || null }; }
|
| 631 |
+
function ttsStop() { if (!hasTTS) return; TTS.id++; speechSynthesis.cancel(); document.querySelectorAll('.spb.on').forEach(b => { b.classList.remove('on'); b.innerHTML = svg('spk', 14) + ' استمع'; }); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
function ttsSpeak(text, btn) {
|
| 633 |
+
if (!hasTTS) return toast('⚠️ لا يدعم النطق');
|
| 634 |
+
ttsStop(); const t = ttsClean(text || ''); if (!t) return;
|
| 635 |
+
const my = ++TTS.id; const { v } = pickVoice(t); const ch = ttsChunks(t); let i = 0;
|
| 636 |
+
if (btn) { btn.classList.add('on'); btn.innerHTML = svg('stop', 14) + ' إيقاف'; }
|
|
|
|
|
|
|
|
|
|
| 637 |
const next = () => {
|
| 638 |
if (my !== TTS.id) return;
|
| 639 |
+
if (i >= ch.length) { if (btn) { btn.classList.remove('on'); btn.innerHTML = svg('spk', 14) + ' استمع'; } return; }
|
| 640 |
const u = new SpeechSynthesisUtterance(ch[i++]);
|
| 641 |
+
u.rate = cfg.ttsRate || 1.5; const ar = pickVoice(ch[i - 1]).ar;
|
| 642 |
+
u.lang = v ? v.lang : (ar ? 'ar-SA' : 'en-US'); if (v) u.voice = v;
|
| 643 |
+
u.onend = next; u.onerror = next; speechSynthesis.speak(u);
|
|
|
|
|
|
|
|
|
|
| 644 |
};
|
| 645 |
next();
|
| 646 |
}
|
| 647 |
+
function speakMsg(b) { if (b.classList.contains('on')) return ttsStop(); ttsSpeak(b.closest('.msg').dataset.raw || '', b); }
|
| 648 |
+
function fillVoices() { if (!hasTTS) return; const vs = speechSynthesis.getVoices(); const sel = $('cVoice'); if (!sel) return; sel.innerHTML = '<option value="">تلقائي</option>' + vs.map(v => `<option value="${esc(v.name)}" ${v.name === cfg.ttsVoice ? 'selected' : ''}>${esc(v.name)} (${esc(v.lang)})</option>`).join(''); }
|
| 649 |
+
function testVoice() { cfg.ttsRate = parseFloat($('cRate').value) || 1.5; cfg.ttsVoice = $('cVoice').value; ttsSpeak('مرحباً، هذا اختبار للصوت.'); }
|
| 650 |
+
function updSpk() { const b = $('spk'); if (!b) return; b.classList.toggle('on', !!cfg.autoSpeak); b.innerHTML = svg(cfg.autoSpeak ? 'spk' : 'spkoff'); b.title = cfg.autoSpeak ? 'النطق: مفعل' : 'النطق: معطل'; }
|
| 651 |
+
function toggleAuto() { if (!hasTTS) return toast('⚠️ لا يدعم النطق'); cfg.autoSpeak = !cfg.autoSpeak; saveCfg(); updSpk(); if (cfg.autoSpeak) { const u = new SpeechSynthesisUtterance(' '); u.volume = 0; speechSynthesis.speak(u); } else ttsStop(); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
|
| 653 |
+
/* ============ STT ============ */
|
| 654 |
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
| 655 |
+
function micUI() { const b = $('mic'); b.classList.toggle('on', micOn); b.innerHTML = svg(micOn ? 'stop' : 'mic'); $('inp').placeholder = micOn ? '🎤 أستمع...' : 'اكتب رسالتك...'; }
|
| 656 |
+
function toggleMic() {
|
| 657 |
+
if (!SR) return toast('⚠️ المتصفح لا يدعم STT');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 658 |
if (micOn) { micOn = false; try { rec?.stop(); } catch {} micUI(); return; }
|
| 659 |
+
navigator.mediaDevices.getUserMedia({ audio: true }).then(st => st.getTracks().forEach(t => t.stop())).catch(e => { toast('❌ ' + e.message); return; });
|
| 660 |
+
ttsStop(); micOn = true; micUI();
|
| 661 |
+
micBase = $('inp').value; if (micBase && !/\s$/.test(micBase)) micBase += ' ';
|
| 662 |
+
const r = rec = new SR(); r.lang = cfg.sttLang || 'ar-SA'; r.continuous = false; r.interimResults = true;
|
| 663 |
+
r.onresult = e => { if (rec !== r || !micOn) return; let t = ''; for (let i = 0; i < e.results.length; i++) t += e.results[i][0].transcript; $('inp').value = micBase + t; };
|
| 664 |
+
r.onerror = e => { if (rec !== r) return; if (e.error === 'no-speech' || e.error === 'aborted') return; micOn = false; micUI(); toast('❌ ' + e.error); };
|
| 665 |
+
r.onend = () => { if (rec !== r) return; if (micOn) setTimeout(() => { if (micOn && rec === r) try { r.start(); } catch { micOn = false; micUI(); } }, 150); else micUI(); };
|
| 666 |
+
try { r.start(); } catch (e) { micOn = false; micUI(); }
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
/* ============ Voice Mode ============ */
|
| 670 |
+
const V = { on: false, state: '', rec: null, text: '', sil: 0, chk: 0, pend: 0, tok: 0, spoken: 0, done: true, muted: false };
|
| 671 |
+
function vSet(st) { V.state = st; $('vc').className = 'on ' + st; $('vS').textContent = ({ listening: 'أستمع...', thinking: 'أفكر...', speaking: 'أتحدث — المس للمقاطعة', muted: 'مكتوم' })[st] || ''; }
|
| 672 |
+
function startVoice() {
|
| 673 |
+
if (!SR || !hasTTS) return toast('⚠️ المتصفح لا يدعم الصوت');
|
| 674 |
+
if (busy) return toast('⏳ انتظر');
|
| 675 |
+
const u = new SpeechSynthesisUtterance(' '); u.volume = 0; speechSynthesis.speak(u);
|
| 676 |
+
$('vc').className = 'on thinking'; $('vS').textContent = 'جارٍ التهيئة...';
|
| 677 |
+
navigator.mediaDevices.getUserMedia({ audio: true }).then(st => st.getTracks().forEach(t => t.stop())).catch(e => { $('vc').className = ''; return toast('❌ ' + e.message); });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
if (micOn) { micOn = false; try { rec?.stop(); } catch {} micUI(); }
|
| 679 |
+
ttsStop(); Object.assign(V, { on: true, muted: false, done: true, pend: 0, spoken: 0, tok: V.tok + 1 });
|
| 680 |
+
setTimeout(vListen, 300);
|
|
|
|
| 681 |
}
|
| 682 |
function vListen() {
|
| 683 |
if (!V.on || V.muted || busy) return;
|
| 684 |
+
V.text = ''; $('vT').textContent = ''; vSet('listening');
|
| 685 |
+
const r = V.rec = new SR(); r.lang = cfg.sttLang || 'ar-SA'; r.continuous = false; r.interimResults = true;
|
| 686 |
+
r.onresult = e => { if (V.rec !== r || V.state !== 'listening') return; let t = '', fin = false; for (let i = 0; i < e.results.length; i++) { t += e.results[i][0].transcript; if (e.results[i].isFinal) fin = true; } V.text = t; $('vT').textContent = t; clearTimeout(V.sil); if (fin) vSend(); else V.sil = setTimeout(vSend, 1200); };
|
| 687 |
+
r.onerror = e => { if (V.rec !== r) return; if (e.error === 'no-speech' || e.error === 'aborted') return; toast('❌ ' + e.error); };
|
| 688 |
+
r.onend = () => { if (V.rec === r && V.on && V.state === 'listening') setTimeout(() => { if (V.rec === r && V.on && V.state === 'listening') vListen(); }, 200); };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
try { r.start(); } catch {}
|
| 690 |
}
|
| 691 |
function vSend() {
|
| 692 |
+
clearTimeout(V.sil); const t = (V.text || '').trim();
|
| 693 |
+
if (!V.on || V.state !== 'listening' || !t || busy) return;
|
|
|
|
| 694 |
const r = V.rec; V.rec = null; try { r?.abort(); } catch {}
|
| 695 |
+
V.done = false; V.spoken = 0; $('vR').textContent = ''; vSet('thinking'); $('inp').value = t;
|
| 696 |
+
ask(t).then(() => { V.done = true; setTimeout(() => { const s = cur(); const last = s.messages.filter(m => m.role === 'assistant').pop(); if (last) vSay(last.content); }, 100); });
|
|
|
|
|
|
|
| 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); u.rate = cfg.ttsRate || 1.5;
|
| 703 |
+
u.lang = v ? v.lang : (ar ? 'ar-SA' : 'en-US'); if (v) u.voice = v;
|
| 704 |
+
V.pend++; u.onstart = () => { if (tok === V.tok && V.on) vSet('speaking'); };
|
|
|
|
|
|
|
|
|
|
| 705 |
u.onend = u.onerror = () => { if (tok !== V.tok) return; V.pend--; vCheck(); };
|
| 706 |
speechSynthesis.speak(u);
|
| 707 |
}
|
| 708 |
}
|
| 709 |
+
function vCheck() { 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); }
|
| 710 |
+
function vTap() { if (!V.on) return; if (V.state === 'listening') return vSend(); if (V.state === 'speaking' || V.state === 'thinking') { V.tok++; V.pend = 0; speechSynthesis.cancel(); if (busy && curReqId) call('cancel', [curReqId]).catch(() => {}); V.done = true; vListen(); } }
|
| 711 |
+
function vMuteTog() { if (!V.on) return; V.muted = !V.muted; $('vMute').innerHTML = svg(V.muted ? 'spkoff' : 'mic', 22); if (V.muted) { clearTimeout(V.sil); const r = V.rec; V.rec = null; try { r?.abort(); } catch {} if (V.state === 'listening') vSet('muted'); } else { if (V.state === 'muted') V.state = ''; if (!busy && V.pend <= 0) vListen(); } }
|
| 712 |
+
function endVoice() { if (!V.on && !$('vc').classList.contains('on')) return; V.on = false; V.tok++; V.pend = 0; clearTimeout(V.sil); clearTimeout(V.chk); V.chk = 0; const r = V.rec; V.rec = null; try { r?.abort(); } catch {} if (hasTTS) speechSynthesis.cancel(); $('vc').className = ''; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 713 |
|
| 714 |
+
/* ============ Settings ============ */
|
| 715 |
+
function openSet() { fillVoices(); $('set').classList.add('open'); closeAll(); }
|
| 716 |
function saveSet() {
|
| 717 |
+
cfg.sys = $('cSys').value; cfg.temp = $('cTemp').value;
|
| 718 |
+
cfg.maxTok = Math.min(32000, Math.max(32, parseInt($('cMax').value) || 256));
|
| 719 |
+
cfg.topP = $('cTop').value;
|
| 720 |
+
cfg.streamChunk = parseInt($('cChunk').value) || 8;
|
| 721 |
+
cfg.ttsRate = parseFloat($('cRate').value) || 1.5; cfg.ttsVoice = $('cVoice').value;
|
| 722 |
+
cfg.autoSpeak = $('cAutoSpeak').checked; cfg.sttLang = $('cStt').value;
|
| 723 |
+
saveCfg(); updSpk(); $('set').classList.remove('open'); toast('✅ حفظ');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
}
|
| 725 |
|
| 726 |
+
/* ============ Export / UI Helpers ============ */
|
| 727 |
function exportChat() {
|
| 728 |
+
const s = cur(); if (!s.messages.length) return toast('لا رسائل');
|
| 729 |
+
const t = '# ' + s.title + '\n\n' + s.messages.map(m => {
|
| 730 |
+
const c = typeof m.content === 'string' ? m.content : (m.content?.find?.(x => x.type === 'text')?.text || '');
|
| 731 |
+
return '### ' + (m.role === 'user' ? 'أنت' : 'المساعد') + '\n' + c;
|
| 732 |
+
}).join('\n\n');
|
| 733 |
+
const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([t], { type: 'text/markdown' }));
|
| 734 |
+
a.download = 'chat-' + cid.slice(0, 8) + '.md'; a.click();
|
| 735 |
+
}
|
| 736 |
+
function toggleSb() { $('sb').classList.toggle('open'); $('ov').classList.toggle('show', $('sb').classList.contains('open')); }
|
| 737 |
+
function closeAll() { $('pp').classList.remove('open'); $('sb').classList.remove('open'); $('ov').classList.remove('show'); }
|
| 738 |
+
document.addEventListener('click', e => { if (!$('pw').contains(e.target)) $('pp').classList.remove('open'); if (innerWidth <= 768 && $('sb').classList.contains('open') && !$('sb').contains(e.target) && e.target.id !== 'hb') closeAll(); });
|
| 739 |
+
$('inp').addEventListener('input', () => { const i = $('inp'); i.style.height = 'auto'; i.style.height = Math.min(i.scrollHeight, 170) + 'px'; });
|
| 740 |
+
addEventListener('keydown', e => { if (e.key === 'Escape') { endVoice(); closeAll(); document.querySelectorAll('.md.open').forEach(m => m.classList.remove('open')); $('cp').classList.remove('full'); } });
|
| 741 |
+
|
| 742 |
+
/* ============ Sync sliders ============ */
|
| 743 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 744 |
+
const cMax = $('cMax'), cMaxR = $('cMaxRange'), mMax = $('mMax');
|
| 745 |
+
cMax.oninput = () => { const v = Math.min(32000, Math.max(32, parseInt(cMax.value) || 256)); cMaxR.value = v; mMax.textContent = v; };
|
| 746 |
+
cMaxR.oninput = () => { cMax.value = cMaxR.value; mMax.textContent = cMaxR.value; };
|
| 747 |
+
const cChunk = $('cChunk'), rChunk = $('rChunk');
|
| 748 |
+
cChunk.oninput = () => rChunk.textContent = cChunk.value;
|
| 749 |
+
const cRate = $('cRate'), rV = $('rV');
|
| 750 |
+
cRate.oninput = () => rV.textContent = cRate.value;
|
|
|
|
|
|
|
| 751 |
});
|
| 752 |
|
| 753 |
+
/* ============ Boot ============ */
|
| 754 |
function boot() {
|
| 755 |
+
hydrate(); applyTheme(); updSpk(); fillVoices();
|
| 756 |
+
$('cSys').value = cfg.sys; $('cTemp').value = cfg.temp;
|
| 757 |
+
$('cMax').value = cfg.maxTok; $('cMaxRange').value = cfg.maxTok; $('mMax').textContent = cfg.maxTok;
|
| 758 |
+
$('cTop').value = cfg.topP;
|
| 759 |
+
$('cChunk').value = cfg.streamChunk; $('rChunk').textContent = cfg.streamChunk;
|
| 760 |
+
$('cRate').value = cfg.ttsRate; $('rV').textContent = cfg.ttsRate;
|
| 761 |
+
$('cAutoSpeak').checked = !!cfg.autoSpeak; $('cStt').value = cfg.sttLang || 'ar-SA';
|
| 762 |
+
renderSessions(); renderChat(); setBusy(false); initModels();
|
| 763 |
+
if (!SR) { $('mic').style.opacity = .4; $('vcb').style.opacity = .4; }
|
| 764 |
+
if (!hasTTS) { $('spk').style.opacity = .4; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
boot();
|
| 767 |
</script>
|
| 768 |
</body>
|