Update index.html
Browse files123638 unmodified lines64264364464564664739 unmodified lines68768868969069169269369469569669769869918 unmodified lines718719720721722723724725157 unmodified lines883884885886887888889890891892893894895896897898899900901902903904905906907908909204 unmodified lines1114111511161117111811191120112127 unmodified lines114911501151115211531154115511561157115811591160116137 unmodified lines11991200120112021203120412054 unmodified lines12101211121212131214121512167 unmodified lines12241225122612271228122912301231123212336 unmodified lines12401241124212431244124512461247124851 unmodified lines1300130113021303130413051306130713086 unmodified lines131513161317131813191320132117 unmodified lines133913401341134213431344134513462 unmodified lines134913501351135213531354135581 unmodified lines14371438143914401441144214433 unmodified lines1447144814491450145114521453145414551456145714588 unmodified lines146714681469147014711472147333 unmodified lines15071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615378 unmodified lines154615471548154915501551155218 unmodified lines1571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116124 unmodified lines1617161816191620162116221 unmodified line16241625162616271628162916301631163216331634163516361637163816397 unmodified lines16471648164916501651165216531654165511 unmodified lines166716681669167016711672167316741675167617 unmodified lines1694169516961697169816991 unmodified line17011702170317041705170610 unmodified lines1717171817191720172117221723172417251726172717282 unmodified lines1731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317542 unmodified lines175717581759176017611762176322 unmodified lines17861787178817891790179117921793179464 unmodified lines18591860186118621863186410 unmodified lines187518761877187818791880188118821883188411 unmodified lines18961897189818991900190119021903190419051906190719085 unmodified lines191419151916191719181919192019213 unmodified lines19251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194860 unmodified lines20092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205041 unmodified lines209220932094209520962097209812 unmodified lines211121122113211421152116211730 unmodified lines21482149215021512152215386 unmodified lines2240224122422243224422452246116 unmodified lines23632364236523662367236832 unmodified lines2401240224032404<!DOCTYPE html><html lang="ar" dir="rtl" data-theme="dark"><head>638 unmodified linesspk: '<svg class="ic" style="width:13px;height:13px" viewBox="0 0 24 24"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>',file: '<svg class="ic" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',brain: '<svg class="ic" style="width:14px;height:14px" viewBox="0 0 24 24"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 4.44-5.04z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-4.44-5.04z"/></svg>',};/* ---------------- IndexedDB Storage ---------------- */39 unmodified linestemp: 0.7, maxTok: 512, topP: 0.9, autoCont: true, thinking: false,theme: 'dark', hf: '', hfPersist: false, custom: [], web: false, mem: true,asrMode: 'transformers_js', tjsModel: 'Xenova/whisper-tiny',voiceLang: 'auto', ttsMode: 'browser', autoSpeak: false, capModel: 'caption'};let S = [], cid = null, busy = false, reqId = null, stopped = false, activeAbort = null;let MODELS = {}, status = {}, polling = false, progressEl = null, watchId = null, follow = true;let attachments = [];const cur = () => S.find(s => s.id === cid);function toast(t) {const d = document.createElement('div');d.className = 'toast';18 unmodified linesconst clean = S.slice(0, 60).map(s => ({id: s.id, title: s.title,messages: s.messages.map(m => ({role: m.role, content: m.content, skip: m.skip,tools: m.tools, sources: m.sources, stat: m.stat,media: m.media ? { type: m.media.type, src: m.media.src, prompt: m.media.prompt } : undefined}))}));157 unmodified linesfunction fillModels() {const sel = $('mp'), q = ($('mpFilter').value || '').trim().toLowerCase();sel.innerHTML = '';const list = Object.values(MODELS).filter(m => m.mode === cfg.mode && (!q || m.repo.toLowerCase().includes(q) || (m.group || '').toLowerCase().includes(q)));const grp = {};list.forEach(m => {if (!grp[m.group]) { grp[m.group] = document.createElement('optgroup'); grp[m.group].label = m.group; sel.appendChild(grp[m.group]); }const o = document.createElement('option');o.value = m.id;const flags = [m.ar ? 'عربي' : '', m.think ? 'تفكير' : '', m.gated ? 'محمي' : ''].filter(Boolean).join('·');o.textContent = `${m.repo.split('/').pop()} (${m.size})${flags ? ' [' + flags + ']' : ''}`;grp[m.group].appendChild(o);});const w = cfg.sel[cfg.mode];sel.value = list.some(m => m.id === w) ? w : (list[0] ? list[0].id : '');cfg.sel[cfg.mode] = sel.value;saveCfg();renderStatus();syncImgDefaults();}function setMode(m) {if (busy) return;cfg.mode = m;document.querySelectorAll('#modes button').forEach(b => b.classList.toggle('on', b.dataset.m === m));$('imgOpts').classList.toggle('show', m === 'image');$('inp').placeholder = {204 unmodified linesif (L.closed) return;ed.value = code; ed.scrollTop = 1e9; CP.lang = lang;clearTimeout(L.t);const run = () => { L.last = Date.now(); preview(); };Date.now() - L.last > 900 ? run() : (L.t = setTimeout(run, 900));}function liveEnd() {27 unmodified linesreturn `<details class="tools-bar"><summary>${esc(summary)}${tools && tools.length > 2 ? ` (+${tools.length - 2})` : ''}</summary><div class="tb-list">${list}${srcs ? `<div class="src-list">${srcs}</div>` : ''}</div></details>`;}function bubble(role, text, idx, opts = {}) {const w = $('ci');w.querySelector('.welcome')?.remove();const d = document.createElement('div');d.className = 'msg ' + role;d.dataset.raw = text || '';const body = role === 'bot' ? (toolsHtml(opts.tools, opts.sources) + md(text)) : esc(text).replace(/\n/g, '<br>');d.innerHTML = body + (idx != null ? actsHtml(role, idx, opts.stat || '') : '');w.appendChild(d);scrollBottom(role === 'user');37 unmodified liness.messages.forEach((m, i) => {if (m.media) return renderMedia(m.media);if (m.role === 'user') bubble('user', m.content, i);else if (m.content) bubble('bot', m.content, i, { tools: m.tools, sources: m.sources, stat: m.stat });});updCtx();follow = true;4 unmodified linesif (busy) return;const s = cur(), m = s.messages[i];if (!m) return;$('inp').value = m.content;$('inp').dispatchEvent(new Event('input'));s.messages = s.messages.slice(0, i);persistSessions();7 unmodified lineslet u = i;while (u >= 0 && s.messages[u].role !== 'user') u--;if (u < 0) return;s.messages = s.messages.slice(0, u + 1);persistSessions();renderChat();await run(s, s.messages[u].content);}/* ---------------- Browser Speaker Queue (TTS) ---------------- */6 unmodified linesstrip(t) {let s = String(t || '');s = s.replace(/<think>[\s\S]*?<\/think>/gi, ' ').replace(/<think>[\s\S]*$/i, ' ');s = s.replace(/```[\s\S]*?```/g, ' كود برمجي ').replace(/```[\s\S]*$/g, ' ');s = s.replace(/https?:\/\/\S+/g, '').replace(/[#*_`~>\[\]|]/g, ' ');return s.replace(/\s+/g, ' ').trim();},51 unmodified lines},enqueue(sentence) {if (!sentence) return;for (let i = 0; i < sentence.length; i += 200) {const chunk = sentence.slice(i, i + 200).trim();if (chunk) this.queue.push(chunk);}if (!this.speaking) this._next();6 unmodified linesreturn;}this.speaking = true;const text = this.queue.shift();if (vcActive) setVoiceBar('speak', 'يتحدث عبر مكبر الصوت: ' + text.slice(0, 60));if (cfg.ttsMode === 'server') {17 unmodified linesawait new Promise(res => {if (!window.speechSynthesis) return res();const u = new SpeechSynthesisUtterance(text);const isAr = /[\u0600-\u06FF]/.test(text);u.lang = isAr ? 'ar-SA' : 'en-US';const voices = speechSynthesis.getVoices();const v = voices.find(x => x.lang.toLowerCase().startsWith(isAr ? 'ar' : 'en'));2 unmodified linesconst finish = () => { if (!done) { done = true; res(); } };u.onend = finish;u.onerror = finish;setTimeout(finish, Math.max(6000, text.length * 140));speechSynthesis.speak(u);});this._next();81 unmodified linesw.postMessage({ type: 'load', id, model });});} catch {// Fallback على الخيط الرئيسي إذا منع المتصفح Module Workerif (this.fallbackPipe && this.fallbackModel === model) return;onProgress && onProgress('جارٍ تحميل Transformers.js...');const { pipeline, env } = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1');3 unmodified linesprogress_callback: p => { if (p?.status === 'progress' && p.total) onProgress && onProgress(`تنزيل Whisper.js (${Math.round(p.loaded * 100 / p.total)}%)...`); }});this.fallbackModel = model;}},async transcribe(float32Audio, onProgress) {const model = cfg.tjsModel || 'Xenova/whisper-tiny';const lang = cfg.voiceLang || 'auto';if (this.worker) {return new Promise((res, rej) => {const id = uid();8 unmodified linesthis.worker.postMessage({ type: 'transcribe', id, model, audio: float32Audio, lang }, [float32Audio.buffer]);});}await this.ensureLoaded(onProgress);const opts = { task: 'transcribe', chunk_length_s: 28, stride_length_s: 5 };if (lang === 'ar') opts.language = 'arabic';else if (lang === 'en') opts.language = 'english';33 unmodified lines$('stp').style.display = v ? 'inline-flex' : 'none';$('mp').disabled = v;$('ld').disabled = v;}function stopGen() {stopped = true;if (activeAbort) activeAbort.abort();if (reqId) call('cancel', [reqId]).catch(() => {});SpeechQueue.stopAudio();toast('جارٍ الإيقاف...');}function renderChips() {$('attachChips').innerHTML = attachments.map((a, idx) => `<div class="achip">${a.thumb ? `<img src="${esc(a.thumb)}" alt="">` : ''}<span>${esc(a.name)}${a.chunks ? ` (${a.chunks})` : ''}</span><button data-rm-att="${idx}" title="إزالة">×</button></div>`).join('');}async function sendMsg(overrideText = null) {if (busy) return;const rawText = (overrideText !== null ? overrideText : $('inp').value).trim();const inlineParts = attachments.filter(a => a.text).map(a => a.text);const docIds = attachments.filter(a => a.docId).map(a => a.docId);const fullDisplay = rawText || (attachments.length ? `تحليل المرفقات: ${attachments.map(a => a.name).join('، ')}` : '');if (!fullDisplay) return;if (!$('mp').value) return toast('اختر نموذجاً من الأعلى أولاً');8 unmodified linesattachments = [];renderChips();s.messages.push({ role: 'user', content: userContent, skip: cfg.mode !== 'chat' });bubble('user', userContent, s.messages.length - 1);persistSessions();updCtx();18 unmodified liness.messages.push({ role: 'assistant', content: '', media: x, skip: true });}async function callGenerateCompat(id, msgs, reqId_, roundOpts, onChunk, signal) {// 1. نرسل التجهيز (بحث/ويب) عبر prepare إذا كانت الميزة مفعّلةlet prepared = null;let finalMsgs = msgs;try {const q = msgs[msgs.length - 1].content;prepared = await call('prepare', [q,J(roundOpts.doc_ids || []),!!roundOpts.web,roundOpts.sid || '',roundOpts.user_sys || '',roundOpts.mem !== false,roundOpts.idx ?? -1], null, signal);if (prepared && prepared.ok) {if (prepared.prefix) {// دمج السياق (البحث/المصادر) في رسالة النظامfinalMsgs = msgs.map(m =>m.role === 'system' ? { role: 'system', content: m.content + '\n\n' + prepared.prefix } : m);}// نرسل المصادر والأدوات للواجهة ليتم عرضهاif (onChunk) onChunk({ tools: prepared.tools || [], sources: prepared.sources || [] });}} catch (e) {console.warn('prepare failed, falling back to raw generate', e);}// 2. نرسل التوليد النهائي عبر generateconst args = [id, J(finalMsgs), reqId_, cfg.maxTok, cfg.temp, cfg.topP, cfg.thinking];return await call('generate', args, onChunk, signal);}async function run(s, text, docIds = []) {setBusy(true);follow = true;L.closed = false;4 unmodified linesconst st = document.createElement('span');const out = document.createElement('span');const toolsWrap = document.createElement('div');st.className = 'stt';st.textContent = 'جارٍ التحضير...';b.appendChild(st);1 unmodified lineSpeechQueue.reset();let answer = '', lastRes = null, rafPending = false, latestLiveText = '', firstPainted = false;const paintLive = () => {rafPending = false;out.innerHTML = mdLive(latestLiveText);scrollBottom();};try {await ensure(id);progressEl = null;st.textContent = {chat: cfg.computeMode === 'cpu' ? 'يكتب على المعالج (CPU)...' : 'جارٍ التوليد...',7 unmodified lines}reqId = uid();const baseMsgs = s.messages.filter(m => !m.skip && m.content).map(({ role, content }) => ({ role, content }));let prefix = '', res, rounds = 0;const opts = {sid: s.id,uid: cfg.uid,11 unmodified linesconst msgs = pre? [...baseMsgs, { role: 'assistant', content: pre }, { role: 'user', content: 'تابع من الحرف الذي توقفت عنده تماماً دون تكرار أو مقدمة.' }]: baseMsgs;const roundOpts = rounds === 0 ? opts : { ...opts, doc_ids: [], web: false, idx: -1 };res = await callGenerateCompat(id, msgs, reqId, roundOpts, d => {if (!d) return;if (typeof d === 'object' && d.ok === false) return;if (d.tools && !toolsWrap.dataset.rendered) {toolsWrap.dataset.rendered = '1';17 unmodified lines}}, activeAbort.signal);if (res && res.ok === false) throw new Error(res.error || 'فشل التوليد');lastRes = res;if (res && res.text != null) answer = pre + res.text;1 unmodified linerounds++;} while (res && res.finish === 'length' && cfg.autoCont && MODELS[id]?.kind === 'chat' && rounds < 4 && !stopped);st.remove();if (!out.isConnected) b.appendChild(out);liveEnd();10 unmodified linesif (answer.trim()) {out.innerHTML = md(answer);b.dataset.raw = answer;s.messages.push({ role: 'assistant', content: answer, tools, sources, stat });b.insertAdjacentHTML('beforeend', actsHtml('bot', s.messages.length - 1, stat));SpeechQueue.flushStream(answer);return answer;} else {out.textContent = stopped ? '(تم إيقاف التوليد)' : '(رد فارغ من النموذج)';return '';}} catch (e) {2 unmodified linesif (!out.isConnected) b.appendChild(out);out.innerHTML = md(answer);b.dataset.raw = answer;s.messages.push({ role: 'assistant', content: answer });b.insertAdjacentHTML('beforeend', actsHtml('bot', s.messages.length - 1, 'متوقف'));return answer;}b.remove();const d = bubble('bot', '');d.classList.add('err');d.textContent = 'تنبيه: ' + e.message;return '';} finally {liveEnd();progressEl = null;reqId = null;activeAbort = null;setBusy(false);persistSessions();updCtx();if (!vcActive) $('inp').focus();}}2 unmodified linesconst SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition;async function toggleDictation() {if (vcActive) { stopVoiceChat(); return; } // إيقاف الدردشة الصوتية إذا كانت مفعلةif (speechRec) { speechRec.stop(); return; }if (rec) { rec.stop(); return; }if (busy) return;22 unmodified linesreturn;}// Transformers.js Whisper in Browsertry {const stream = await navigator.mediaDevices.getUserMedia({ audio: true });rec = new MediaRecorder(stream);recChunks = [];rec.ondataavailable = e => { if (e.data.size) recChunks.push(e.data); };64 unmodified linesif (!vcActive) return;stopVcMedia();if (cfg.asrMode === 'browser' && SpeechRec) {setVoiceBar('listen', 'يستمع الآن (متصفح)... تكلّم وسيرسل عند الصمت', false);vcSpeech = new SpeechRec();10 unmodified linesstopVcMedia();handleVoiceUtterance(t);}}, 1400);}};vcSpeech.onresult = e => {let fin = '', inter = '';for (let i = e.resultIndex; i < e.results.length; i++) {if (e.results[i].isFinal) fin += e.results[i][0].transcript + ' ';11 unmodified linestry { vcSpeech.start(); return; } catch {}}// Transformers.js Whisper مع VAD حساس + مؤشر مستوى صوتtry {setVoiceBar('load', 'جارٍ تجهيز Whisper.js في المتصفح (يحفظ محلياً)...');await TJS.ensureLoaded(msg => vcActive && setVoiceBar('load', msg));if (!vcActive) return;vcStream = await navigator.mediaDevices.getUserMedia({ audio: true });vcRec = new MediaRecorder(vcStream);vcChunks = [];vcRec.ondataavailable = e => { if (e.data.size) vcChunks.push(e.data); };5 unmodified linesan.fftSize = 1024;src.connect(an);const buf = new Uint8Array(an.frequencyBinCount);let spoke = false, silentSince = Date.now();const listenStart = Date.now();const checkVad = () => {if (!vcActive || !vcRec || vcRec.state !== 'recording') return;3 unmodified linesconst rms = Math.sqrt(sum / buf.length);$('vbMeterBar').style.width = Math.min(100, Math.round(rms * 650)) + '%';if (rms > 0.009) {if (!spoke) setVoiceBar('listen', 'تم التقاط صوتك... تكلّم (اضغط أرسل الآن أو اصمت)', true);spoke = true;silentSince = Date.now();} else if (spoke && Date.now() - silentSince > 1350) {vcRec.stop();return;} else if (!spoke && Date.now() - listenStart > 30000) {silentSince = Date.now();}requestAnimationFrame(checkVad);};vcRec.onstop = async () => {const blob = new Blob(vcChunks);stopVcMedia();if (!vcActive) return;if (blob.size < 1500) return vcListenLoop();try {setVoiceBar('think', 'Whisper.js يكتب كلامك الآن...');const f32 = await decodeTo16kFloat32(await blob.arrayBuffer());60 unmodified linesreturn;}if (f.type.startsWith('image/')) {const url = await new Promise(r => { const fr = new FileReader(); fr.onload = () => r(fr.result); fr.readAsDataURL(f); });const capId = cfg.capModel === 'blip_caption' && MODELS.blip_caption ? 'blip_caption' : 'caption';if (busy) return;setBusy(true); watchId = capId; toast('جارٍ تحليل الصورة...');try {await ensure(capId);const r = await call('caption', [url.split(',')[1], capId]);if (r && r.ok && r.text) {attachments.push({ id: uid(), name: f.name, kind: 'image', thumb: url, text: `[وصف الصورة المرفقة (${f.name}): ${r.text}]` });renderChips();} else throw new Error(r?.error || 'فشل وصف الصورة');} catch (err) { toast('خطأ: ' + err.message); }finally { watchId = null; setBusy(false); renderStatus(); }return;}const ext = (f.name.split('.').pop() || '').toLowerCase();if (DOC_EXTS.has(ext) || f.size > 4000) {try {toast('جارٍ معالجة وفهرسة الملف...');const r = await call('ingest_doc', [f.name, b64(await f.arrayBuffer()), cur()?.id || '']);if (r && r.ok && Array.isArray(r.docs)) {r.docs.forEach(d => attachments.push({ id: uid(), name: d.name, kind: 'doc', docId: d.id, chunks: d.chunks }));renderChips();toast(`تمت فهرسة ${r.docs.length} مستند جاهز للبحث`);return;}throw new Error(r?.error || 'تعذرت قراءة الملف');} catch (err) {if (DOC_EXTS.has(ext)) return toast('خطأ: ' + err.message);}}const txt = (await f.text()).slice(0, 20000);attachments.push({ id: uid(), name: f.name, kind: 'text', text: `--- ملف: ${f.name} ---\n${txt}` });renderChips();};41 unmodified lines$('cThink').checked = cfg.thinking;$('cAsrMode').value = cfg.asrMode;$('cTjsModel').value = cfg.tjsModel;$('cVoiceLang').value = cfg.voiceLang;$('cTtsMode').value = cfg.ttsMode;$('cCapModel').value = cfg.capModel;$('cSys').value = cfg.sys;12 unmodified linescfg.thinking = $('cThink').checked;cfg.asrMode = $('cAsrMode').value;cfg.tjsModel = $('cTjsModel').value;cfg.voiceLang = $('cVoiceLang').value;cfg.ttsMode = $('cTtsMode').value;cfg.capModel = $('cCapModel').value;cfg.sys = $('cSys').value;30 unmodified linesMODELS[r.model.id] = r.model;if (!cfg.custom.some(c => c.repo === repo)) cfg.custom.push({ repo, kind });cfg.sel.chat = r.model.id;$('cOwner').value = '';$('cRepoName').value = '';await refresh();86 unmodified lines$('stp').onclick = stopGen;$('pl').onclick = e => { e.stopPropagation(); $('pp').classList.toggle('open'); };$('pp').onclick = e => e.stopPropagation();$('actAttachFile').onclick = () => { $('fi').click(); closeAll(); };$('attachChips').addEventListener('click', e => {const b = e.target.closest('[data-rm-att]');116 unmodified linesif (!cfg.hfPersist) cfg.hf = sessionStorage.getItem(SS_HF) || cfg.hf || '';} catch {}if (!cfg.uid) cfg.uid = 'u_' + uid();cfg.sel = cfg.sel || {};cfg.custom = cfg.custom || [];saveCfg();32 unmodified lines})();</script></body></html>12345638 unmodified lines64464564664764864965039 unmodified lines69069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372418 unmodified lines743744745746747748749750751752157 unmodified lines910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950204 unmodified lines1155115611571158115911601161116227 unmodified lines1190119111921193119411951196119711981199120012011202120312041205120612071208120937 unmodified lines12471248124912501251125212534 unmodified lines12581259126012611262126312647 unmodified lines127212731274127512761277127812791280128112826 unmodified lines1289129012911292129312941295129612971298129913001301130251 unmodified lines13541355135613571358135913601361136213636 unmodified lines1370137113721373137413751376137717 unmodified lines13951396139713981399140014011402140314042 unmodified lines140714081409141014111412141381 unmodified lines14951496149714981499150015013 unmodified lines150515061507150815091510151115121513151415151516151715188 unmodified lines15271528152915301531153233 unmodified lines156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416158 unmodified lines1624162516261627162816291630163116321633163416351636163718 unmodified lines16561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017314 unmodified lines17361737173817391740174117421 unmodified line1744174517461747174817491750175117521753175417551756175717581759176017617 unmodified lines1769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180311 unmodified lines181518161817181818191820182118221823182417 unmodified lines1842184318441845184618471848184918501851185218531854185518561 unmodified line185818591860186118621863186410 unmodified lines1875187618771878187918801881188218831884188518861887188818891890189118922 unmodified lines1895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619272 unmodified lines193019311932193319341935193622 unmodified lines195919601961196219631964196519661967196864 unmodified lines20332034203520362037203820392040204120422043204410 unmodified lines2055205620572058205920602061206220632064206511 unmodified lines2077207820792080208120822083208420852086208720882089209020915 unmodified lines2097209820992100210121022103210421052106210721083 unmodified lines2112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215260 unmodified lines22132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231141 unmodified lines235323542355235623572358235912 unmodified lines237223732374237523762377237830 unmodified lines240924102411241224132414241586 unmodified lines25022503250425052506250725082509251025112512116 unmodified lines262926302631263226332634263532 unmodified lines26682669267026712672<!DOCTYPE html><html lang="ar" dir="rtl" data-theme="dark"><head>638 unmodified linesspk: '<svg class="ic" style="width:13px;height:13px" viewBox="0 0 24 24"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>',file: '<svg class="ic" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',brain: '<svg class="ic" style="width:14px;height:14px" viewBox="0 0 24 24"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 4.44-5.04z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-4.44-5.04z"/></svg>',spin: '<svg class="ic" style="width:14px;height:14px;color:var(--ac)" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-opacity=".25" stroke-width="2.5" fill="none"/><path d="M12 3a9 9 0 0 1 9 9" stroke="currentColor" stroke-width="2.5" fill="none"><animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="0.8s" repeatCount="indefinite"/></path></svg>'};/* ---------------- IndexedDB Storage ---------------- */39 unmodified linestemp: 0.7, maxTok: 512, topP: 0.9, autoCont: true, thinking: false,theme: 'dark', hf: '', hfPersist: false, custom: [], web: false, mem: true,asrMode: 'transformers_js', tjsModel: 'Xenova/whisper-tiny',voiceLang: 'ar', ttsMode: 'browser', autoSpeak: false, capModel: 'caption'};let S = [], cid = null, busy = false, reqId = null, stopped = false, activeAbort = null, runToken = 0;let MODELS = {}, status = {}, polling = false, progressEl = null, watchId = null, follow = true;let attachments = [], uploadingCount = 0;const cur = () => S.find(s => s.id === cid);const MAX_ATTACHMENTS = 5;const MAX_MESSAGES_WARN = 30;function isVisionModel(m) {if (!m) return false;if (m.mode === 'vision' || m.vision === true) return true;return /(?:^|[\/\-_])(vl|llava|idefics|vision|pixtral|internvl|molmo|qwen2\.5-vl|qwen2-vl)(?:$|[\/\-_])/i.test(m.repo || '');}function checkMemoryQuotaForUpload() {const msgCount = cur()?.messages?.length || 0;if (attachments.length > MAX_ATTACHMENTS || attachments.length >= MAX_ATTACHMENTS || msgCount > MAX_MESSAGES_WARN) {toast('الذاكرة تقترب من الامتلاء. فكّر في بدء محادثة جديدة أو مسح المرفقات.');return false;}return true;}function updSendReady() {$('snd').disabled = uploadingCount > 0;}function toast(t) {const d = document.createElement('div');d.className = 'toast';18 unmodified linesconst clean = S.slice(0, 60).map(s => ({id: s.id, title: s.title,messages: s.messages.map(m => ({role: m.role, content: m.content, rawText: m.rawText, skip: m.skip,tools: m.tools, sources: m.sources, stat: m.stat, warn: m.warn,docIds: m.docIds,images: m.images,media: m.media ? { type: m.media.type, src: m.media.src, prompt: m.media.prompt } : undefined}))}));157 unmodified linesfunction fillModels() {const sel = $('mp'), q = ($('mpFilter').value || '').trim().toLowerCase();sel.innerHTML = '';const modeMatches = m => cfg.mode === 'chat' ? (m.mode === 'chat' || m.mode === 'vision') : m.mode === cfg.mode;const allForMode = Object.values(MODELS).filter(modeMatches);const list = allForMode.filter(m => !q || m.repo.toLowerCase().includes(q) || (m.group || '').toLowerCase().includes(q));const grp = {};list.forEach(m => {const grpName = m.group || (m.mode === 'vision' ? 'نماذج الرؤية (Vision)' : 'أخرى');if (!grp[grpName]) { grp[grpName] = document.createElement('optgroup'); grp[grpName].label = grpName; sel.appendChild(grp[grpName]); }const o = document.createElement('option');o.value = m.id;const flags = [m.ar ? 'عربي' : '', m.think ? 'تفكير' : '', isVisionModel(m) ? 'رؤية' : '', m.gated ? 'محمي' : ''].filter(Boolean).join('·');o.textContent = `${m.repo.split('/').pop()} (${m.size || '—'})${flags ? ' [' + flags + ']' : ''}`;grp[grpName].appendChild(o);});const w = cfg.sel[cfg.mode];if (list.some(m => m.id === w)) {sel.value = w;} else if (list[0]) {sel.value = list[0].id;// لا نُفسد الاختيار المحفوظ للوضع أثناء التصفية البحثية أو قبل تحميل النماذجif (!q && allForMode.length && !w) {cfg.sel[cfg.mode] = sel.value;saveCfg();}} else {sel.value = '';}renderStatus();syncImgDefaults();}function setMode(m) {if (busy) return;if (cfg.mode !== m) $('mpFilter').value = '';cfg.mode = m;saveCfg();document.querySelectorAll('#modes button').forEach(b => b.classList.toggle('on', b.dataset.m === m));$('imgOpts').classList.toggle('show', m === 'image');$('inp').placeholder = {204 unmodified linesif (L.closed) return;ed.value = code; ed.scrollTop = 1e9; CP.lang = lang;clearTimeout(L.t);const runPrev = () => { L.last = Date.now(); preview(); };Date.now() - L.last > 900 ? runPrev() : (L.t = setTimeout(runPrev, 900));}function liveEnd() {27 unmodified linesreturn `<details class="tools-bar"><summary>${esc(summary)}${tools && tools.length > 2 ? ` (+${tools.length - 2})` : ''}</summary><div class="tb-list">${list}${srcs ? `<div class="src-list">${srcs}</div>` : ''}</div></details>`;}function warnHtml(warn) {if (!warn) return '';return `<div style="color:var(--wr);border:1px solid var(--wr);border-radius:10px;padding:7px 11px;margin-bottom:8px;font-size:12.5px;background:rgba(251,191,36,.08)">${esc(warn)}</div>`;}function bubble(role, text, idx, opts = {}) {const w = $('ci');w.querySelector('.welcome')?.remove();const d = document.createElement('div');d.className = 'msg ' + role;d.dataset.raw = text || '';const body = role === 'bot'? (warnHtml(opts.warn) + toolsHtml(opts.tools, opts.sources) + md(text)): esc(text).replace(/\n/g, '<br>');d.innerHTML = body + (idx != null ? actsHtml(role, idx, opts.stat || '') : '');w.appendChild(d);scrollBottom(role === 'user');37 unmodified liness.messages.forEach((m, i) => {if (m.media) return renderMedia(m.media);if (m.role === 'user') bubble('user', m.content, i);else if (m.content || m.warn) bubble('bot', m.content || '', i, { tools: m.tools, sources: m.sources, stat: m.stat, warn: m.warn });});updCtx();follow = true;4 unmodified linesif (busy) return;const s = cur(), m = s.messages[i];if (!m) return;$('inp').value = m.rawText || m.content;$('inp').dispatchEvent(new Event('input'));s.messages = s.messages.slice(0, i);persistSessions();7 unmodified lineslet u = i;while (u >= 0 && s.messages[u].role !== 'user') u--;if (u < 0) return;const um = s.messages[u];s.messages = s.messages.slice(0, u + 1);persistSessions();renderChat();await run(s, um.content, um.docIds || []);}/* ---------------- Browser Speaker Queue (TTS) ---------------- */6 unmodified linesstrip(t) {let s = String(t || '');s = s.replace(/<think>[\s\S]*?<\/think>/gi, ' ').replace(/<think>[\s\S]*$/gi, ' ');s = s.replace(/```[\s\S]*?```/g, ' كود برمجي ').replace(/```[\s\S]*$/g, ' ');s = s.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');s = s.replace(/https?:\/\/\S+/g, '');s = s.replace(/[#*_`~>|]/g, ' ');s = s.replace(/<[^>]+>/g, ' ');s = s.replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu, '');s = s.replace(/\|/g, ' ');return s.replace(/\s+/g, ' ').trim();},51 unmodified lines},enqueue(sentence) {const cleaned = this.strip(sentence);if (!cleaned) return;for (let i = 0; i < cleaned.length; i += 200) {const chunk = cleaned.slice(i, i + 200).trim();if (chunk) this.queue.push(chunk);}if (!this.speaking) this._next();6 unmodified linesreturn;}this.speaking = true;const text = this.strip(this.queue.shift());if (!text) return this._next();if (vcActive) setVoiceBar('speak', 'يتحدث عبر مكبر الصوت: ' + text.slice(0, 60));if (cfg.ttsMode === 'server') {17 unmodified linesawait new Promise(res => {if (!window.speechSynthesis) return res();const safeText = this.strip(text);if (!safeText) return res();const u = new SpeechSynthesisUtterance(safeText);const isAr = /[\u0600-\u06FF]/.test(safeText);u.lang = isAr ? 'ar-SA' : 'en-US';const voices = speechSynthesis.getVoices();const v = voices.find(x => x.lang.toLowerCase().startsWith(isAr ? 'ar' : 'en'));2 unmodified linesconst finish = () => { if (!done) { done = true; res(); } };u.onend = finish;u.onerror = finish;setTimeout(finish, Math.max(6000, safeText.length * 140));speechSynthesis.speak(u);});this._next();81 unmodified linesw.postMessage({ type: 'load', id, model });});} catch {if (this.worker) { try { this.worker.terminate(); } catch {} this.worker = null; }if (this.fallbackPipe && this.fallbackModel === model) return;onProgress && onProgress('جارٍ تحميل Transformers.js...');const { pipeline, env } = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1');3 unmodified linesprogress_callback: p => { if (p?.status === 'progress' && p.total) onProgress && onProgress(`تنزيل Whisper.js (${Math.round(p.loaded * 100 / p.total)}%)...`); }});this.fallbackModel = model;this.readyModel = model;}},async transcribe(float32Audio, onProgress) {const model = cfg.tjsModel || 'Xenova/whisper-tiny';const lang = cfg.voiceLang || 'ar';await this.ensureLoaded(onProgress);if (this.worker) {return new Promise((res, rej) => {const id = uid();8 unmodified linesthis.worker.postMessage({ type: 'transcribe', id, model, audio: float32Audio, lang }, [float32Audio.buffer]);});}const opts = { task: 'transcribe', chunk_length_s: 28, stride_length_s: 5 };if (lang === 'ar') opts.language = 'arabic';else if (lang === 'en') opts.language = 'english';33 unmodified lines$('stp').style.display = v ? 'inline-flex' : 'none';$('mp').disabled = v;$('ld').disabled = v;updSendReady();}function stopGen() {const rid = reqId;stopped = true;runToken++;if (activeAbort) activeAbort.abort();if (rid) call('cancel', [rid]).catch(() => {});SpeechQueue.stopAudio();liveEnd();progressEl = null;reqId = null;activeAbort = null;setBusy(false);toast('تم إيقاف التوليد');}function renderChips() {$('attachChips').innerHTML = attachments.map((a, idx) => `<div class="achip">${a.loading ? SVG.spin : (a.thumb ? `<img src="${esc(a.thumb)}" alt="">` : '')}<span>${esc(a.name)}${a.loading ? ' · جارٍ المعالجة...' : (a.chunks ? ` (${a.chunks})` : '')}</span>${a.loading ? '' : `<button data-rm-att="${idx}" title="إزالة">×</button>`}</div>`).join('');updSendReady();}async function sendMsg(overrideText = null) {if (busy) return;if (uploadingCount > 0) return toast('انتظر اكتمال معالجة وفهرسة المرفقات أولاً');const rawText = (overrideText !== null ? overrideText : $('inp').value).trim();const readyAtts = attachments.filter(a => !a.loading);const inlineParts = readyAtts.filter(a => a.text).map(a => a.text);const docIds = readyAtts.filter(a => a.docId).map(a => a.docId);const imgAtts = readyAtts.filter(a => a.kind === 'image' && a.base64).map(a => ({name: a.name,base64: a.base64,mime: a.mime || 'image/jpeg',caption: a.caption || ''}));const fullDisplay = rawText || (readyAtts.length ? `تحليل المرفقات: ${readyAtts.map(a => a.name).join('، ')}` : '');if (!fullDisplay) return;if (!$('mp').value) return toast('اختر نموذجاً من الأعلى أولاً');8 unmodified linesattachments = [];renderChips();s.messages.push({role: 'user',content: userContent,rawText: rawText || fullDisplay,docIds,images: imgAtts,skip: cfg.mode !== 'chat'});bubble('user', userContent, s.messages.length - 1);persistSessions();updCtx();18 unmodified liness.messages.push({ role: 'assistant', content: '', media: x, skip: true });}function msgTextForPrepare(m) {if (!m) return '';if (typeof m.content === 'string') return m.content;if (Array.isArray(m.content)) {return m.content.filter(p => p && p.type === 'text').map(p => p.text).join(' ');}return '';}async function callGenerateCompat(id, msgs, reqId_, roundOpts, onChunk, signal) {let prepared = null;let finalMsgs = msgs;let prepareWarning = '';const needsPrepare = !!roundOpts.web || (Array.isArray(roundOpts.doc_ids) && roundOpts.doc_ids.length > 0) || !!roundOpts.user_sys || roundOpts.mem !== false;if (needsPrepare || roundOpts.cachedPrefix === undefined) {try {const q = msgTextForPrepare(msgs[msgs.length - 1]);const docIdsJson = typeof roundOpts.doc_ids === 'string'? roundOpts.doc_ids: J(roundOpts.doc_ids || []);prepared = await call('prepare', [q,docIdsJson,!!roundOpts.web,roundOpts.sid || '',roundOpts.user_sys || '',roundOpts.mem !== false,roundOpts.idx ?? -1], null, signal);if (prepared && prepared.ok) {if (prepared.prefix) {const hasSys = msgs.some(m => m.role === 'system');if (hasSys) {finalMsgs = msgs.map(m =>m.role === 'system'? { ...m, content: (m.content ? m.content + '\n\n' : '') + prepared.prefix }: m);} else {finalMsgs = [{ role: 'system', content: prepared.prefix }, ...msgs];}}if (onChunk) onChunk({ tools: prepared.tools || [], sources: prepared.sources || [] });} else if (prepared && prepared.ok === false) {const reason = prepared.error || 'تعذّر تجهيز السياق';prepareWarning = `⚠️ [فشل بحث الويب: ${reason}. الإجابة بدون مصادر.]`;}} catch (e) {if (e.name === 'AbortError') throw e;console.warn('prepare failed:', e);prepareWarning = `⚠️ [فشل بحث الويب: ${e.message || 'تعذر الاتصال'}. الإجابة بدون مصادر.]`;}} else if (roundOpts.cachedPrefix) {finalMsgs = [{ role: 'system', content: roundOpts.cachedPrefix }, ...msgs];}if (!prepared?.ok && roundOpts.user_sys && !finalMsgs.some(m => m.role === 'system')) {finalMsgs = [{ role: 'system', content: roundOpts.user_sys }, ...finalMsgs];}const args = [id, J(finalMsgs), reqId_, cfg.maxTok, cfg.temp, cfg.topP, cfg.thinking];const res = await call('generate', args, onChunk, signal);return { res, prepared, prepareWarning };}async function run(s, text, docIds = []) {const myToken = ++runToken;setBusy(true);follow = true;L.closed = false;4 unmodified linesconst st = document.createElement('span');const out = document.createElement('span');const toolsWrap = document.createElement('div');const warnWrap = document.createElement('div');st.className = 'stt';st.textContent = 'جارٍ التحضير...';b.appendChild(st);1 unmodified lineSpeechQueue.reset();let answer = '', lastRes = null, rafPending = false, latestLiveText = '', firstPainted = false, runWarn = '';const paintLive = () => {rafPending = false;if (myToken !== runToken) return;out.innerHTML = mdLive(latestLiveText);scrollBottom();};try {await ensure(id);if (stopped || myToken !== runToken) return '';progressEl = null;st.textContent = {chat: cfg.computeMode === 'cpu' ? 'يكتب على المعالج (CPU)...' : 'جارٍ التوليد...',7 unmodified lines}reqId = uid();const activeModel = MODELS[id];const visionSupported = isVisionModel(activeModel);const baseMsgs = s.messages.filter(m => !m.skip && (m.content || (m.images && m.images.length))).map(m => {if (visionSupported && m.images && m.images.length) {return {role: m.role,content: [{ type: 'text', text: m.rawText || m.content || 'صف هذه الصورة' },...m.images.map(im => ({type: 'image_url',image_url: { url: `data:${im.mime || 'image/jpeg'};base64,${im.base64}` }}))]};}let contentText = m.content || '';if (m.images && m.images.length) {const extra = m.images.filter(im => im.caption && !contentText.includes(im.caption)).map(im => `[سياق الصورة: ${im.caption}]`);if (extra.length) contentText = (contentText ? contentText + '\n\n' : '') + extra.join('\n');}return { role: m.role, content: contentText };});let prefix = '', res, rounds = 0, cachedPrefix = '';const opts = {sid: s.id,uid: cfg.uid,11 unmodified linesconst msgs = pre? [...baseMsgs, { role: 'assistant', content: pre }, { role: 'user', content: 'تابع من الحرف الذي توقفت عنده تماماً دون تكرار أو مقدمة.' }]: baseMsgs;const roundOpts = rounds === 0 ? opts : { ...opts, doc_ids: [], web: false, idx: -1, cachedPrefix };const compatOut = await callGenerateCompat(id, msgs, reqId, roundOpts, d => {if (!d || myToken !== runToken) return;if (typeof d === 'object' && d.ok === false) return;if (d.tools && !toolsWrap.dataset.rendered) {toolsWrap.dataset.rendered = '1';17 unmodified lines}}, activeAbort.signal);if (myToken !== runToken) return '';if (rounds === 0 && compatOut.prepared?.prefix) cachedPrefix = compatOut.prepared.prefix;if (compatOut.prepareWarning && !runWarn) {runWarn = compatOut.prepareWarning;warnWrap.innerHTML = warnHtml(runWarn);if (!warnWrap.isConnected) b.insertBefore(warnWrap, st.isConnected ? st : out);}res = compatOut.res;if (res && res.ok === false) throw new Error(res.error || 'فشل التوليد');lastRes = res;if (res && res.text != null) answer = pre + res.text;1 unmodified linerounds++;} while (res && res.finish === 'length' && cfg.autoCont && MODELS[id]?.kind === 'chat' && rounds < 4 && !stopped);if (myToken !== runToken) return '';st.remove();if (!out.isConnected) b.appendChild(out);liveEnd();10 unmodified linesif (answer.trim()) {out.innerHTML = md(answer);b.dataset.raw = answer;s.messages.push({ role: 'assistant', content: answer, tools, sources, stat, warn: runWarn || undefined });b.insertAdjacentHTML('beforeend', actsHtml('bot', s.messages.length - 1, stat));SpeechQueue.flushStream(answer);return answer;} else {const emptyMsg = stopped? '(تم إيقاف التوليد)': '(النموذج لم يُرجع محتوى. جرّب إعادة التوليد أو نموذجاً أصغر.)';out.textContent = emptyMsg;if (runWarn) {s.messages.push({ role: 'assistant', content: emptyMsg, warn: runWarn });}return '';}} catch (e) {2 unmodified linesif (!out.isConnected) b.appendChild(out);out.innerHTML = md(answer);b.dataset.raw = answer;s.messages.push({ role: 'assistant', content: answer, warn: runWarn || undefined });b.insertAdjacentHTML('beforeend', actsHtml('bot', s.messages.length - 1, 'متوقف'));return answer;}if (e.name === 'AbortError' && stopped) {b.remove();return '';}b.remove();const d = bubble('bot', '');d.classList.add('err');d.textContent = 'تنبيه: ' + e.message;return '';} finally {if (myToken === runToken) {liveEnd();progressEl = null;reqId = null;activeAbort = null;setBusy(false);persistSessions();updCtx();if (!vcActive) $('inp').focus();} else {persistSessions();updCtx();}}}2 unmodified linesconst SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition;async function toggleDictation() {if (vcActive) { stopVoiceChat(); return; }if (speechRec) { speechRec.stop(); return; }if (rec) { rec.stop(); return; }if (busy) return;22 unmodified linesreturn;}try {const stream = await navigator.mediaDevices.getUserMedia({audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }});rec = new MediaRecorder(stream);recChunks = [];rec.ondataavailable = e => { if (e.data.size) recChunks.push(e.data); };64 unmodified linesif (!vcActive) return;stopVcMedia();if (SpeechQueue.speaking) {setVoiceBar('speak', 'يتحدث عبر مكبر الصوت...');await new Promise(resolve => { SpeechQueue.onIdle = resolve; });if (!vcActive) return;}if (cfg.asrMode === 'browser' && SpeechRec) {setVoiceBar('listen', 'يستمع الآن (متصفح)... تكلّم وسيرسل عند الصمت', false);vcSpeech = new SpeechRec();10 unmodified linesstopVcMedia();handleVoiceUtterance(t);}}, 1100);}};vcSpeech.onresult = e => {if (SpeechQueue.speaking) return;let fin = '', inter = '';for (let i = e.resultIndex; i < e.results.length; i++) {if (e.results[i].isFinal) fin += e.results[i][0].transcript + ' ';11 unmodified linestry { vcSpeech.start(); return; } catch {}}// Transformers.js Whisper مع معايرة الضوضاء التكيفية (500ms) + حماية ضد سماع TTS لنفسهtry {setVoiceBar('load', 'جارٍ تجهيز Whisper.js في المتصفح (يحفظ محلياً)...');await TJS.ensureLoaded(msg => vcActive && setVoiceBar('load', msg));if (!vcActive) return;vcStream = await navigator.mediaDevices.getUserMedia({audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }});vcRec = new MediaRecorder(vcStream);vcChunks = [];vcRec.ondataavailable = e => { if (e.data.size) vcChunks.push(e.data); };5 unmodified linesan.fftSize = 1024;src.connect(an);const buf = new Uint8Array(an.frequencyBinCount);let spoke = false, silentSince = Date.now();const listenStart = Date.now();const noiseSamples = [];let calibrated = false;let adaptiveThreshold = 0.015;const checkVad = () => {if (!vcActive || !vcRec || vcRec.state !== 'recording') return;3 unmodified linesconst rms = Math.sqrt(sum / buf.length);$('vbMeterBar').style.width = Math.min(100, Math.round(rms * 650)) + '%';const elapsed = Date.now() - listenStart;if (!calibrated) {if (!SpeechQueue.speaking) noiseSamples.push(rms);if (elapsed >= 500) {calibrated = true;const noiseAvg = noiseSamples.length? noiseSamples.reduce((a, b) => a + b, 0) / noiseSamples.length: 0.004;adaptiveThreshold = Math.min(0.15, noiseAvg * 2.5 + 0.005);}}// أثناء تحدث TTS نرفع العتبة إلى 0.5 لتجاهل صوت المتصفح ومنع الصدىconst vadThreshold = SpeechQueue.speaking ? 0.5 : adaptiveThreshold;if (rms > vadThreshold) {if (!spoke) setVoiceBar('listen', 'تم التقاط صوتك... تكلّم (اضغط أرسل الآن أو اصمت)', true);spoke = true;silentSince = Date.now();} else if (spoke && Date.now() - silentSince > 1100) {vcRec.stop();return;} else if (!spoke && elapsed > 30000) {vcRec.stop();return;}requestAnimationFrame(checkVad);};vcRec.onstop = async () => {const hadSpeech = spoke;const blob = new Blob(vcChunks);stopVcMedia();if (!vcActive) return;if (!hadSpeech || blob.size < 1500) return vcListenLoop();try {setVoiceBar('think', 'Whisper.js يكتب كلامك الآن...');const f32 = await decodeTo16kFloat32(await blob.arrayBuffer());60 unmodified linesreturn;}if (!checkMemoryQuotaForUpload()) return;if (f.type.startsWith('image/')) {if (busy) return toast('انتظر انتهاء الرد الحالي');const pendingId = uid();const url = await new Promise(r => { const fr = new FileReader(); fr.onload = () => r(fr.result); fr.readAsDataURL(f); });const imgBase64 = (url.split(',')[1] || '').trim();const imgMime = f.type || 'image/jpeg';const activeModel = MODELS[$('mp').value];const visionReady = isVisionModel(activeModel);const capId = cfg.capModel === 'blip_caption' && MODELS.blip_caption ? 'blip_caption' : 'caption';attachments.push({ id: pendingId, name: f.name, kind: 'image', thumb: url, base64: imgBase64, mime: imgMime, loading: true });uploadingCount++;renderChips();watchId = capId;toast('جارٍ معالجة الصورة...');try {let captionText = '';if (!visionReady || MODELS[capId]) {try {await ensure(capId);const r = await call('caption', [imgBase64, capId]);if (r && r.ok && (r.text || r.caption)) {captionText = (r.text || r.caption).trim();} else if (!visionReady) {throw new Error(r?.error || 'فشل وصف الصورة');}} catch (capErr) {if (!visionReady) throw capErr;}}const idx = attachments.findIndex(a => a.id === pendingId);if (idx >= 0) {attachments[idx] = {id: pendingId,name: f.name,kind: 'image',thumb: url,base64: imgBase64,mime: imgMime,caption: captionText,text: captionText ? `[سياق الصورة: ${captionText}]` : '',loading: false};}renderChips();} catch (err) {attachments = attachments.filter(a => a.id !== pendingId);renderChips();toast('خطأ: ' + err.message);} finally {watchId = null;uploadingCount = Math.max(0, uploadingCount - 1);renderChips();renderStatus();}return;}const ext = (f.name.split('.').pop() || '').toLowerCase();if (DOC_EXTS.has(ext) || f.size > 4000) {const pendingId = uid();attachments.push({ id: pendingId, name: f.name, kind: 'doc', loading: true });uploadingCount++;renderChips();try {toast('جارٍ معالجة وفهرسة الملف...');const r = await call('ingest_doc', [f.name, b64(await f.arrayBuffer()), cur()?.id || '']);attachments = attachments.filter(a => a.id !== pendingId);if (r && r.ok && Array.isArray(r.docs)) {r.docs.forEach(d => attachments.push({ id: uid(), name: d.name, kind: 'doc', docId: d.id, chunks: d.chunks, loading: false }));renderChips();toast(`تمت فهرسة ${r.docs.length} مستند جاهز للبحث`);return;}throw new Error(r?.error || 'تعذرت قراءة الملف');} catch (err) {attachments = attachments.filter(a => a.id !== pendingId);renderChips();if (DOC_EXTS.has(ext)) { toast('خطأ: ' + err.message); return; }} finally {uploadingCount = Math.max(0, uploadingCount - 1);renderChips();}}const txt = (await f.text()).slice(0, 20000);attachments.push({ id: uid(), name: f.name, kind: 'text', text: `--- ملف: ${f.name} ---\n${txt}`, loading: false });renderChips();};41 unmodified lines$('cThink').checked = cfg.thinking;$('cAsrMode').value = cfg.asrMode;$('cTjsModel').value = cfg.tjsModel;$('cVoiceLang').value = cfg.voiceLang || 'ar';$('cTtsMode').value = cfg.ttsMode;$('cCapModel').value = cfg.capModel;$('cSys').value = cfg.sys;12 unmodified linescfg.thinking = $('cThink').checked;cfg.asrMode = $('cAsrMode').value;cfg.tjsModel = $('cTjsModel').value;cfg.voiceLang = $('cVoiceLang').value || 'ar';cfg.ttsMode = $('cTtsMode').value;cfg.capModel = $('cCapModel').value;cfg.sys = $('cSys').value;30 unmodified linesMODELS[r.model.id] = r.model;if (!cfg.custom.some(c => c.repo === repo)) cfg.custom.push({ repo, kind });cfg.sel.chat = r.model.id;saveCfg();$('cOwner').value = '';$('cRepoName').value = '';await refresh();86 unmodified lines$('stp').onclick = stopGen;$('pl').onclick = e => { e.stopPropagation(); $('pp').classList.toggle('open'); };$('pp').onclick = e => e.stopPropagation();$('actAttachFile').onclick = () => {closeAll();if (!checkMemoryQuotaForUpload()) return;$('fi').click();};$('attachChips').addEventListener('click', e => {const b = e.target.closest('[data-rm-att]');116 unmodified linesif (!cfg.hfPersist) cfg.hf = sessionStorage.getItem(SS_HF) || cfg.hf || '';} catch {}if (!cfg.uid) cfg.uid = 'u_' + uid();if (!cfg.voiceLang) cfg.voiceLang = 'ar';cfg.sel = cfg.sel || {};cfg.custom = cfg.custom || [];saveCfg();32 unmodified lines})();</script></body></html>
index.html+378-110