File size: 17,852 Bytes
bc9f3e6 | 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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | // Thin HTTP + WebSocket client for the LocalAiLab FastAPI backend.
export function getSessionToken() {
if (typeof window !== "undefined" && window.__SESSION_TOKEN__) {
return window.__SESSION_TOKEN__;
}
return "";
}
function authHeaders(extra = {}) {
const token = getSessionToken();
const headers = { ...extra };
if (token) {
headers["X-Session-Token"] = token;
}
return headers;
}
export async function getJSON(path) {
const r = await fetch(path, { headers: authHeaders({ Accept: "application/json" }) });
if (!r.ok) throw new Error(`HTTP ${r.status} β ${path}`);
return r.json();
}
export async function postForm(path, formData) {
const r = await fetch(path, { method: "POST", headers: authHeaders(), body: formData });
if (!r.ok) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
return r.json();
}
export async function postJSON(path, payload) {
const r = await fetch(path, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify(payload),
});
if (!r.ok) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
const ct = r.headers.get("content-type") || "";
return ct.includes("json") ? r.json() : r.text();
}
export function fetchMeta() {
return getJSON("/api/meta");
}
export function fetchI18n(lang) {
return getJSON(`/api/i18n?lang=${encodeURIComponent(lang)}`);
}
export function saveSettings(payload) {
return postJSON("/api/settings", payload);
}
export function saveReport(payload) {
return postJSON("/api/reports", payload);
}
export function resetAgent(payload) {
return postJSON("/api/agent/reset", payload);
}
/**
* POST a raw image File to /api/upload; returns { ok, path } β the temp
* path is sent through the chat WS and deleted server-side after the run.
*/
export async function uploadImage(file) {
const r = await fetch("/api/upload", { method: "POST", headers: authHeaders(), body: file });
if (!r.ok) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
return r.json();
}
/** mmproj (vision projector) choices for the current VLM + provider. */
export function fetchMmproj(vlm, provider) {
return getJSON(
`/api/mmproj?vlm=${encodeURIComponent(vlm)}&provider=${encodeURIComponent(provider)}`
);
}
/** The 'already downloaded?' notice for a provider/model pair β the header
* model-status chip reads this (web port of the Gradio model-status card). */
export function fetchModelNotice(provider, model, type = "llm", lang = "kh") {
return getJSON(
`/api/model-notice?provider=${encodeURIComponent(provider)}&model=${encodeURIComponent(model)}&type=${encodeURIComponent(type)}&lang=${encodeURIComponent(lang)}`
);
}
/** Check if a model is cached, needs download, its download size, and resolved id. */
export function fetchModelCheck(provider, model, type = "llm", lang = "kh") {
return getJSON(
`/api/model-check?provider=${encodeURIComponent(provider)}&model=${encodeURIComponent(model)}&type=${encodeURIComponent(type)}&lang=${encodeURIComponent(lang)}`
);
}
// ββ Model pre-download ββββββββββββββββββββββββββββββββββββββββββββββββ
/** Trigger a background download of a HuggingFace model (repo id). */
export function startModelDownload(modelId, modelLabel = "") {
return postJSON("/api/model-download", { model_id: modelId, model_label: modelLabel });
}
/** Poll model download progress. */
export function modelDownloadStatus() {
return getJSON("/api/model-download");
}
/** Signal an in-flight model download to abort. */
export function cancelModelDownload() {
return postJSON("/api/model-download-cancel", {});
}
/** Available disk space on the user_data drive. */
export function fetchDiskSpace() {
return getJSON("/api/disk-space");
}
/** Delete a downloaded model from disk. */
export function deleteModel(modelId) {
return postJSON("/api/model-delete", { model_id: modelId });
}
// ββ STT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export function sttTranscribe(file, { sttLabel = "", language = "auto" } = {}) {
const fd = new FormData();
fd.append("audio", file);
fd.append("stt_label", sttLabel);
fd.append("language", language);
return postForm("/api/stt/transcribe", fd);
}
/** Upload audio for WebSocket-based STT β returns {path} for /ws/stt/transcribe. */
export function sttUpload(file) {
const fd = new FormData();
fd.append("audio", file);
return postForm("/api/stt/upload", fd);
}
export const sttAnalyse = (payload) => postJSON("/api/stt/analyse", payload);
export const sttSaveTxt = (payload) => postJSON("/api/stt/save-txt", payload);
export const sttLoad = (modelLabel, lang = "kh") => postJSON("/api/stt/load", { model_label: modelLabel, lang });
export const sttUnload = () => postJSON("/api/stt/unload", {});
/** Save the current audio File into user_data/outputs/ (the STT tab's
* "πΎ Save Audio" button). The client always sends WAV, the format every
* STT backend reads. Returns { ok, path }.
*/
export async function sttSaveAudio(file, filename = "") {
const fd = new FormData();
fd.append("audio", file);
fd.append("filename", filename);
return postForm("/api/stt/save-audio", fd);
}
/** Open user_data/outputs/ in the OS file explorer. */
export const sttOpenOutputs = () => postJSON("/api/stt/open-outputs", {});
/** Reduce background noise in the audio and return the cleaned WAV as a
* Blob (the endpoint answers audio/wav, not JSON β the STT tab swaps the
* result in as the current audio). JSON error bodies still throw with their
* message. */
export async function sttDenoise(file, strength = "aggressive") {
const fd = new FormData();
fd.append("audio", file);
fd.append("strength", strength);
const r = await fetch("/api/stt/denoise", { method: "POST", headers: authHeaders(), body: fd });
const ct = r.headers.get("content-type") || "";
if (!r.ok || !ct.includes("audio/")) {
let detail = `HTTP ${r.status}`;
try {
const j = await r.json();
if (j?.message) detail = j.message;
} catch {
/* ignore */
}
throw new Error(detail);
}
return r.blob();
}
// ββ Data Analysis ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export function analyzeData({
files,
question = "",
modelLabel = "",
useMemory = true,
maxSteps = "",
executionTimeout = "",
lang = "kh",
} = {}) {
const fd = new FormData();
for (const f of files || []) fd.append("files", f);
fd.append("question", question);
fd.append("model_label", modelLabel);
fd.append("use_memory", useMemory ? "true" : "false");
fd.append("lang", lang);
if (maxSteps) fd.append("max_steps", maxSteps);
if (executionTimeout) fd.append("execution_timeout", executionTimeout);
return postForm("/api/data/analyze", fd);
}
/** Upload data files (CSV/XLSX) to temp storage for the Data Analysis chat
* tab β the WS payload then carries the returned paths (like Vision's
* image upload). Returns { paths }. */
export async function dataUpload(files) {
const fd = new FormData();
for (const f of files || []) fd.append("files", f);
return postForm("/api/data/upload", fd);
}
export const resetData = () => postJSON("/api/data/reset", {});
/** Chart image URL for a saved PNG basename. The backend guards every
* /api/* route with the session token (X-Session-Token header on fetch
* calls; `?token=` query param for WebSockets). An <img src> tag cannot
* send headers, so the token travels as a query param here β otherwise
* every chart 401s and renders as a broken image. */
export const dataChartUrl = (name) => {
const base = `/api/data/chart/${encodeURIComponent(name)}`;
const token = getSessionToken();
return token ? `${base}?token=${encodeURIComponent(token)}` : base;
};
/** The Data Analysis charts folder: its full path (display) + open it in
* the OS file explorer (mirrors the STT outputs folder). */
export const dataOutputDir = () => getJSON("/api/data/output-dir");
export const dataOpenOutputs = () => postJSON("/api/data/open-outputs", {});
// ββ Knowledge Base βββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Indexing streams live progress as Server-Sent Events (text/event-stream):
// each `log` event carries one terminal status line ([RAG] embedding load,
// [transformers] model warnings β¦) and a final `done` event carries the
// result message. `onLog(line)` is called for every streamed line so the KB
// tab can render + copy the same text the console showed.
export async function kbIndex({ files, theme = [], subtheme = [], visualRetriever = "", lang = "kh", embedProvider = "", embedModel = "", onLog } = {}) {
const fd = new FormData();
for (const f of files || []) fd.append("files", f);
// theme/subtheme are arrays (the multi-select tag dropdowns) β send each
// value as a repeated form field so the backend sees every selected tag.
for (const v of [].concat(theme || [])) if (v) fd.append("theme", v);
for (const v of [].concat(subtheme || [])) if (v) fd.append("subtheme", v);
fd.append("visualRetriever", visualRetriever);
fd.append("lang", lang);
if (embedProvider) fd.append("embed_provider", embedProvider);
if (embedModel) fd.append("embed_model", embedModel);
const res = await fetch("/api/kb/index", { method: "POST", headers: authHeaders(), body: fd });
if (!res.ok || !res.body) {
throw new Error(`kb/index failed: ${res.status}`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
let finalMsg = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let idx;
while ((idx = buf.indexOf("\n\n")) !== -1) {
const chunk = buf.slice(0, idx);
buf = buf.slice(idx + 2);
const dataLine = chunk.split("\n").find((l) => l.startsWith("data: "));
if (!dataLine) continue;
let data;
try {
data = JSON.parse(dataLine.slice(6));
} catch {
continue;
}
if (data.type === "log") {
if (onLog) onLog(data.line);
} else if (data.type === "done") {
finalMsg = data.message || "";
}
}
}
if (!finalMsg && onLog) onLog("β Indexing finished.");
return { ok: true, message: finalMsg };
}
export const kbDocs = (refresh = false) => getJSON(`/api/kb/docs?refresh=${refresh ? 1 : 0}`);
export const kbThemes = (theme = "") => getJSON(`/api/kb/themes?theme=${encodeURIComponent(theme)}`);
export const kbDelete = (selected, rows, lang = "kh") => postJSON("/api/kb/delete", { selected, rows, lang });
export const kbClear = (lang = "kh") => postJSON("/api/kb/clear", { lang });
export const kbVisualDocs = () => getJSON("/api/kb/visual-docs");
export const kbVisualDelete = (selected, rows, lang = "kh") => postJSON("/api/kb/visual-delete", { selected, rows, lang });
export const kbVisualClear = (lang = "kh") => postJSON("/api/kb/visual-clear", { lang });
// ββ Settings βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export const fetchSettings = (lang = "kh") => getJSON(`/api/settings?lang=${encodeURIComponent(lang)}`);
export const saveSetting = (key, value, tab) => postJSON("/api/settings/save", { key, value, tab });
export const freeVram = (lang = "kh") => postJSON("/api/settings/free-vram", { lang });
export const restartApp = (lang = "kh") => postJSON("/api/restart", { lang });
export const fetchMemory = () => getJSON("/api/settings/memory");
export const clearReports = (days) => postJSON("/api/settings/clear-reports", { days });
export const openReports = (tab = "", path = "") => postJSON("/api/settings/open-reports", { tab, path });
export const refreshReports = () => postJSON("/api/settings/refresh-reports", {});
export const deleteReport = (rel) => postJSON("/api/settings/delete-report", { rel });
export const startDownload = (component) => postJSON("/api/settings/download", { component });
export const downloadStatus = () => getJSON("/api/settings/download");
/** llama-cpp-python detection report ({ detected, options }) β fetched when
* the Settings install button is clicked so the popup can show the user
* every build available on this PC instead of silently installing CPU. */
export const llmCppInfo = () => getJSON("/api/settings/llm-cpp-info");
/** Install a user-chosen llama-cpp-python build (auto / cpu / cuda /
* vulkan). Reuses the shared download job β same poll/status/stream. */
export const llmCppInstall = (choice) => postJSON("/api/settings/llm-cpp-install", { choice });
/** llama-server download plan ({ detected, options }) β fetched when the
* Settings download button is clicked so the popup can show the user every
* build available on this PC (CPU / CUDA 12.4 / CUDA 13.3) instead of
* silently auto-picking one. */
export const llamaServerInfo = () => getJSON("/api/settings/llama-server-info");
/** Download a user-chosen llama-server build (auto / cpu / cuda12 /
* cuda13). Reuses the shared download job β same poll/status/stream. */
export const llamaServerInstall = (choice) => postJSON("/api/settings/llama-server-install", { choice });
/** whisper-server download plan ({ detected, options }) β fetched when the
* Settings download button is clicked so the popup can show the user every
* build available on this PC (CPU / cuBLAS 11.8 / cuBLAS 12.4) instead of
* silently downloading the CPU build. */
export const whisperServerInfo = () => getJSON("/api/settings/whisper-server-info");
/** Download a user-chosen whisper-server build (auto / cpu / cuda11 /
* cuda12). Reuses the shared download job β same poll/status/stream. */
export const whisperServerInstall = (choice) => postJSON("/api/settings/whisper-server-install", { choice });
/** PyTorch install plan ({ detected, options }) β fetched when the Settings
* "Detect & Install GPU PyTorch" button is clicked so the popup can show
* the user every build available on this PC (CPU / CUDA / Intel XPU /
* AMD ROCm) instead of silently installing the recommended path. */
export const pytorchInfo = () => getJSON("/api/settings/pytorch-info");
/** Install a user-chosen PyTorch build (auto / cpu / cuda / xpu / rocm).
* Reuses the shared download job β same poll/status/stream. */
export const pytorchInstall = (choice) => postJSON("/api/settings/pytorch-install", { choice });
// ββ About & Feedback ββββββββββββββββββββββββββββββββββββββββββββββββββ
export const fetchAbout = (lang = "kh") => getJSON(`/api/about?lang=${encodeURIComponent(lang)}`);
export const fetchDiagnostics = (lang = "kh") => getJSON(`/api/feedback/diagnostics?lang=${encodeURIComponent(lang)}`);
export const submitFeedback = (payload) => postJSON("/api/feedback", payload);
/**
* Open a backend WebSocket. onMessage receives every server event object.
* `path` defaults to the chat socket (/ws/chat) β pass e.g. "/ws/stt/analyse"
* for the STT report-analysis stream, which speaks the same event protocol
* (live / update / final / error). Returns { send(payload), close() } β
* send() queues until the socket opens.
*/
export function openChatSocket(onMessage, path = "/ws/chat") {
const proto = location.protocol === "https:" ? "wss" : "ws";
const token = getSessionToken();
const tokenQuery = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`${proto}://${location.host}${path}${tokenQuery}`);
const queue = [];
let closedNormally = false;
ws.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === "final" || data.type === "error") {
closedNormally = true;
}
onMessage(data);
} catch {
/* ignore */
}
};
ws.onerror = () => {
if (!closedNormally) {
onMessage({ type: "error", message: "WebSocket connection error" });
}
};
ws.onclose = (e) => {
if (!closedNormally && !e.wasClean) {
onMessage({ type: "error", message: "Server connection lost" });
}
};
ws.onopen = () => {
while (queue.length) ws.send(queue.shift());
};
return {
send(payload) {
const raw = JSON.stringify(payload);
if (ws.readyState === WebSocket.OPEN) ws.send(raw);
else queue.push(raw);
},
close() {
closedNormally = true;
try {
ws.close();
} catch {
/* already closed */
}
},
};
}
|