File size: 7,350 Bytes
a19df13 f761e54 a19df13 f761e54 a19df13 9f55ce6 07734b3 9f55ce6 8d3c64b a19df13 8d3c64b a19df13 9f55ce6 a19df13 9f55ce6 a19df13 f761e54 a19df13 f761e54 8d3c64b 9f55ce6 a19df13 f761e54 a19df13 8d3c64b a19df13 8d3c64b a19df13 8d3c64b a19df13 8d3c64b a19df13 8d3c64b a19df13 f761e54 a19df13 f761e54 a19df13 8d3c64b a19df13 f761e54 a19df13 8d3c64b a19df13 8d3c64b f761e54 a19df13 79640d7 a19df13 79640d7 a19df13 7256ada |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
import * as transformers from 'https://cdn.jsdelivr.net/npm/@xenova/transformers/+esm';
const $ = (s) => document.querySelector(s);
const messagesEl = $("#messages");
const statusEl = $("#status");
const statusText = $("#status-text");
const modelSel = $("#model");
const promptEl = $("#prompt");
const sendBtn = $("#send");
const form = $("#composer");
// Режими/стан
let busy = false;
let currentModel = modelSel.value || "Xenova/distilgpt2";
const cache = new Map(); // model -> { pipe, task }
const chatHistory = []; // { role: 'user'|'assistant', content: string }
// Зручні хелпери UI
function setStatus(text, isBusy) {
statusText.textContent = text;
messagesEl.setAttribute("aria-busy", isBusy ? "true" : "false");
busy = !!isBusy;
promptEl.disabled = !!isBusy;
sendBtn.disabled = !!isBusy;
modelSel.disabled = !!isBusy;
}
function pushMsg(role, text, details) {
const div = document.createElement("div");
div.className = `msg ${role}`;
if (role === 'sys' && details) {
div.innerHTML = `<span>${text}</span><pre class="error-details">${escapeHtml(details)}</pre>`;
} else {
div.textContent = text;
}
messagesEl.appendChild(div);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
// Захист від XSS у stack trace
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
// Визначення задачі для моделі
function taskForModel(model) {
if ((model || "").toLowerCase().includes("t5")) return "text2text-generation";
return "text-generation";
}
// Побудова простого prompt’а (мінімально універсальний)
function buildPrompt(model, history) {
const task = taskForModel(model);
const lastUser = history.slice().reverse().find(m => m.role === "user");
const userText = lastUser ? lastUser.content : "";
if (task === "text2text-generation") {
return `Instruction: Answer briefly.\nInput: ${userText}\nOutput:`;
} else {
const sys = "You are a helpful assistant. Answer briefly.";
const turns = history.map(m => (m.role === "user" ? `User: ${m.content}` : `Assistant: ${m.content}`));
return `${sys}\n${turns.join("\n")}\nAssistant:`;
}
}
// Динамічний імпорт transformers.js
let transformers = null;
let transformersLoadError = null;
async function loadTransformers() {
if (transformers) return transformers;
try {
pushMsg("sys", "[debug] Завантаження transformers.js...");
transformers = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.1');
pushMsg("sys", "[debug] transformers.js успішно завантажено");
return transformers;
} catch (err) {
transformersLoadError = err;
pushMsg("sys", `Помилка завантаження transformers.js: ${String(err && err.message || err)}`,
err && err.stack ? err.stack : undefined);
throw err;
}
}
// --- DEBUG-AWARE ensurePipeline ---
async function ensurePipeline(model) {
pushMsg("sys", `[debug] ensurePipeline called for ${model}`);
if (cache.has(model)) {
pushMsg("sys", `[debug] ensurePipeline cache hit for ${model}`);
return cache.get(model);
}
const task = taskForModel(model);
setStatus(`Завантаження моделі (${task})…`, true);
let tjs;
try {
tjs = await loadTransformers();
if (!tjs || typeof tjs.pipeline !== 'function') {
const msg = "Transformers.js (ESM) не завантажено або недоступно. Перевірте імпорт.";
const err = new Error(msg);
setStatus("Помилка завантаження моделі", false);
pushMsg("sys", `Помилка при завантаженні '${model}': ${msg}`,
err.stack);
throw err;
}
pushMsg("sys", `[debug] calling transformers.pipeline(${task}, ${model})`);
const pipe = await tjs.pipeline(task, model);
const entry = { pipe, task };
cache.set(model, entry);
setStatus("Готово", false);
return entry;
} catch (err) {
setStatus("Помилка завантаження моделі", false);
pushMsg("sys", `Помилка при завантаженні '${model}': ${String(err && err.message || err)}`,
err && err.stack ? err.stack : undefined);
throw err;
}
}
// --- DEBUG-AWARE generateAndReply ---
async function generateAndReply() {
pushMsg("sys", "[debug] generateAndReply called");
const model = currentModel;
let pipe, task;
try {
pushMsg("sys", `[debug] ensurePipeline for ${model}`);
const pipeObj = await ensurePipeline(model);
pipe = pipeObj.pipe;
task = pipeObj.task;
pushMsg("sys", `[debug] ensurePipeline ok: ${model}, task=${task}`);
} catch (err) {
pushMsg("sys", `[debug] ensurePipeline failed: ${String(err && err.message || err)}`);
throw err;
}
const prompt = buildPrompt(model, chatHistory);
setStatus("Генерація відповіді…", true);
try {
const genOpts = {
max_new_tokens: 64,
temperature: 0.8,
top_p: 0.9,
do_sample: true
};
pushMsg("sys", "[debug] calling pipe");
const out = await pipe(prompt, genOpts);
pushMsg("sys", "[debug] pipe returned");
let fullText = "";
if (Array.isArray(out) && out.length) {
fullText = out[0].generated_text ?? out[0].summary_text ?? String(out[0].text || "");
} else if (typeof out === "string") {
fullText = out;
} else {
fullText = JSON.stringify(out);
}
let reply = fullText;
if (task === "text-generation" && fullText.startsWith(prompt)) {
reply = fullText.slice(prompt.length);
}
reply = (reply || "").trim();
if (!reply) reply = "(порожня відповідь)";
chatHistory.push({ role: "assistant", content: reply });
pushMsg("bot", reply);
} catch (err) {
pushMsg("sys", `Помилка генерації: ${String(err && err.message || err)}`,
err && err.stack ? err.stack : undefined);
throw err;
} finally {
setStatus("Готово", false);
}
}
// --- DEBUG-AWARE form submit ---
form.addEventListener("submit", async (e) => {
e.preventDefault();
if (busy) return;
const text = (promptEl.value || "").trim();
if (!text) return;
chatHistory.push({ role: "user", content: text });
pushMsg("me", text);
promptEl.value = "";
try {
pushMsg("sys", "[debug] form submit: calling generateAndReply");
await generateAndReply();
} catch (err) {
pushMsg("sys", `global unhandled in submit: ${String(err && err.message || err)}`,
err && err.stack ? err.stack : undefined);
}
promptEl.focus();
});
promptEl.focus();
window.onerror = function (msg, url, line, col, error) {
let details = '';
if (error && error.stack) {
details = error.stack;
} else {
details = `${msg} at ${url}:${line}:${col}`;
}
pushMsg('sys', `global unhandled: ${msg}`, details);
return false;
};
// DEBUG: перевірка виконання модуля
try {
const el = document.querySelector('#messages');
if (el) {
const div = document.createElement('div');
div.className = 'msg sys';
div.textContent = '[debug] JS loaded';
el.appendChild(div);
}
} catch (e) {}
|