-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalAI.html
More file actions
540 lines (512 loc) · 21.1 KB
/
LocalAI.html
File metadata and controls
540 lines (512 loc) · 21.1 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="referrer" content="strict-origin">
<title>Enhanced AI Interface (Debug Logging)</title>
<style>
/* Global App Styling */
#app {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
h1, h2 {
color: #333;
text-align: center;
}
.section {
margin-bottom: 20px;
}
textarea, input, select {
width: 100%;
margin-bottom: 10px;
padding: 8px;
box-sizing: border-box;
}
button {
padding: 10px 15px;
margin-right: 10px;
margin-bottom: 10px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#response, #predict-output, #logs {
background-color: #f0f0f0;
padding: 10px;
min-height: 50px;
border-radius: 5px;
}
canvas {
margin-top: 10px;
}
#progress-container {
width: 100%;
background-color: #eee;
border-radius: 5px;
overflow: hidden;
margin-bottom: 10px;
height: 25px;
}
#progress-bar {
height: 100%;
width: 0%;
background-color: #007BFF;
transition: width 0.3s;
}
</style>
<!-- Load external libraries from CDN -->
<script defer src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.20.0/dist/tf.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/@tensorflow-models/universal-sentence-encoder"></script>
<script defer src="https://cdn.jsdelivr.net/npm/papaparse@5.3.2/papaparse.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.js"></script>
</head>
<body>
<div id="app">
<h1>Enhanced AI Interface (Debug Logging)</h1>
<!-- Language Model Section -->
<div id="language-model-section" class="section">
<h2>Language Model</h2>
<textarea id="text-input" placeholder="Enter text..."></textarea>
<input type="file" id="image-input" accept="image/*">
<input type="number" id="label-input" min="0" max="99" placeholder="Label (0-99)">
<div>
<button id="pretrain-btn">Pre-train</button>
<button id="finetune-btn">Fine-tune</button>
<button id="generate-btn">Generate Response</button>
<button id="save-language-btn">Save Language Model</button>
<button id="load-language-btn">Load Language Model</button>
</div>
<div id="response"></div>
</div>
<!-- Tabular Data Training Section -->
<div id="tabular-section" class="section">
<h2>Tabular Data Training</h2>
<input type="file" id="csv-input" accept=".csv">
<select id="task-type">
<option value="classification">Classification</option>
<option value="regression">Regression</option>
</select>
<input type="number" id="epochs" value="10" min="1" placeholder="Epochs">
<input type="number" id="batch-size" value="32" min="1" placeholder="Batch Size">
<input type="number" id="learning-rate" value="0.001" step="0.0001" placeholder="Learning Rate">
<input type="number" id="val-split" value="0.2" step="0.1" min="0" max="1" placeholder="Validation Split">
<div>
<button id="train-tabular-btn">Train Tabular Model</button>
<button id="predict-tabular-btn">Predict</button>
<button id="save-tabular-btn">Save Tabular Model</button>
<button id="load-tabular-btn">Load Tabular Model</button>
</div>
<input type="text" id="predict-input" placeholder="Enter features (comma-separated)">
<div id="predict-output"></div>
<canvas id="loss-chart" width="400" height="200"></canvas>
<div id="progress-container">
<div id="progress-bar"></div>
</div>
</div>
<!-- Logs Section -->
<div id="logs-section" class="section">
<h2>Logs</h2>
<div id="logs"></div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', async function() {
try {
console.log("Script started");
// Append log messages to the logs container
window.appendLog = function(msg) {
const logContainer = document.getElementById("logs");
const t = new Date().toLocaleTimeString();
logContainer.innerHTML += "[" + t + "] " + msg + "<br>";
logContainer.scrollTop = logContainer.scrollHeight;
};
appendLog("Script started");
// Check if external libraries are loaded
if (typeof tf === "undefined") {
throw new Error("TensorFlow.js not loaded. Check if the CDN script is blocked or if there's a network issue.");
}
if (typeof Papa === "undefined") {
throw new Error("PapaParse not loaded. Check if the CDN script is blocked or if there's a network issue.");
}
if (typeof Chart === "undefined") {
throw new Error("Chart.js not loaded. Check if the CDN script is blocked or if there's a network issue.");
}
if (typeof use === "undefined") {
throw new Error("Universal Sentence Encoder not loaded. Check if the CDN script is blocked or if there's a network issue.");
}
await tf.ready();
appendLog("TensorFlow.js ready");
// Global model variables
let languageModel = null;
let textEncoder = null;
let mobilenetBase = null;
let lossChart = null;
// Process image: resize, normalize and expand dims
async function processImage(imageElement) {
return tf.browser.fromPixels(imageElement)
.resizeNearestNeighbor([224, 224])
.toFloat()
.div(tf.scalar(255))
.expandDims();
}
// Load and prepare the dual-input language model (text + image)
async function buildLanguageModel() {
// Load Universal Sentence Encoder if not already loaded
if (!textEncoder) {
appendLog("Loading Universal Sentence Encoder...");
textEncoder = await use.load();
appendLog("Universal Sentence Encoder loaded.");
}
// Load MobileNet and truncate for image feature extraction if not already done
if (!mobilenetBase) {
appendLog("Loading MobileNet...");
const mobilenet = await tf.loadLayersModel('https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json');
mobilenet.trainable = false;
let layer = mobilenet.getLayer('conv_pw_13_relu');
if (!layer) {
layer = mobilenet.layers[mobilenet.layers.length - 1];
}
mobilenetBase = tf.model({inputs: mobilenet.inputs, outputs: layer.output});
appendLog("MobileNet loaded and truncated.");
}
// Build dual input model
// Text branch: Input is 512-d embedding from USE
const textInput = tf.input({shape: [512]});
const textDense = tf.layers.dense({units: 128, activation: 'relu'}).apply(textInput);
// Image branch: Input shape [224,224,3]
const imageInput = tf.input({shape: [224,224,3]});
const imageFeatures = mobilenetBase.apply(imageInput);
const flatImage = tf.layers.flatten().apply(imageFeatures);
const imageDense = tf.layers.dense({units: 128, activation: 'relu'}).apply(flatImage);
// Concatenate both features
const concatenated = tf.layers.concatenate().apply([textDense, imageDense]);
const output = tf.layers.dense({units: 1}).apply(concatenated);
languageModel = tf.model({inputs: [textInput, imageInput], outputs: output});
languageModel.compile({optimizer: tf.train.adam(), loss: 'meanSquaredError'});
appendLog("Dual-input language model built and compiled.");
}
// Pre-train: load models if needed, embed text and process image, then train on one example
async function pretrainLanguageModel() {
appendLog("Pre-training language model...");
const text = document.getElementById("text-input").value;
const imageFile = document.getElementById("image-input").files[0];
const label = parseFloat(document.getElementById("label-input").value);
if (!text || !imageFile || isNaN(label)) {
appendLog("Please provide text, an image, and a valid label.");
return;
}
// Build language model if not built
if (!languageModel) {
await buildLanguageModel();
}
// Process text input using USE
const textEmbedding = await textEncoder.embed(text); // shape [1,512]
// Process image input
const imageElement = new Image();
imageElement.src = URL.createObjectURL(imageFile);
await new Promise(resolve => imageElement.onload = resolve);
const imageTensor = await processImage(imageElement);
// Create label tensor
const labelTensor = tf.tensor2d([label], [1, 1]);
appendLog("Training language model on provided example...");
await languageModel.fit([textEmbedding, imageTensor], labelTensor, {
epochs: 5,
callbacks: {
onEpochEnd: async (epoch, logs) => {
appendLog(`Language model training - Epoch ${epoch+1}: Loss = ${logs.loss.toFixed(4)}`);
}
}
});
appendLog("Language model pre-training completed.");
}
// Fine-tune language model with additional training on the same sample (for demo purposes)
async function finetuneLanguageModel() {
appendLog("Starting language model fine-tuning...");
if (!languageModel) {
appendLog("Language model not pre-trained yet.");
return;
}
const text = document.getElementById("text-input").value;
const imageFile = document.getElementById("image-input").files[0];
const label = parseFloat(document.getElementById("label-input").value);
if (!text || !imageFile || isNaN(label)) {
appendLog("Please provide text, an image, and a valid label.");
return;
}
const textEmbedding = await textEncoder.embed(text);
const imageElement = new Image();
imageElement.src = URL.createObjectURL(imageFile);
await new Promise(resolve => imageElement.onload = resolve);
const imageTensor = await processImage(imageElement);
const labelTensor = tf.tensor2d([label], [1, 1]);
await languageModel.fit([textEmbedding, imageTensor], labelTensor, {
epochs: 3,
callbacks: {
onEpochEnd: async (epoch, logs) => {
appendLog(`Fine-tuning - Epoch ${epoch+1}: Loss = ${logs.loss.toFixed(4)}`);
}
}
});
appendLog("Language model fine-tuning completed.");
}
// Generate response: use the model to predict and display a result with a DALL-E style placeholder
async function generateResponse() {
appendLog("Generating response...");
const text = document.getElementById("text-input").value;
if (!text) {
appendLog("Please enter text to generate a response.");
return;
}
let predictionText = "";
const imageFile = document.getElementById("image-input").files[0];
if (languageModel && imageFile) {
const textEmbedding = await textEncoder.embed(text);
const imageElement = new Image();
imageElement.src = URL.createObjectURL(imageFile);
await new Promise(resolve => imageElement.onload = resolve);
const imageTensor = await processImage(imageElement);
const pred = languageModel.predict([textEmbedding, imageTensor]);
const predVal = (await pred.data())[0];
predictionText = "Predicted value: " + predVal.toFixed(2);
} else {
predictionText = "No image/model available. Echo: " + text;
}
const responseDiv = document.getElementById("response");
responseDiv.innerHTML = "<p>" + predictionText + "</p>" +
"<img src='https://via.placeholder.com/300x200.png?text=DALL-E+Generated' alt='DALL-E Generated Image'>";
appendLog("Response generated.");
}
// Save language model to IndexedDB
async function saveLanguageModel() {
if (!languageModel) {
appendLog("No language model to save.");
return;
}
await languageModel.save('indexeddb://language-model');
appendLog("Language model saved to IndexedDB.");
}
// Load language model from IndexedDB
async function loadLanguageModel() {
try {
languageModel = await tf.loadLayersModel('indexeddb://language-model');
appendLog("Language model loaded from IndexedDB.");
} catch (error) {
appendLog("Failed to load language model: " + error.message);
}
}
// --- Tabular Model Functions (unchanged) ---
async function trainTabularModel() {
const file = document.getElementById("csv-input").files[0];
if (!file) {
appendLog("Please upload a CSV file.");
return;
}
Papa.parse(file, {
header: true,
skipEmptyLines: true,
complete: async function(results) {
appendLog("CSV parsed successfully.");
const data = results.data;
// Assume the CSV: all columns except last are features, last column is label.
const keys = Object.keys(data[0]);
const featureKeys = keys.slice(0, -1);
const labelKey = keys.slice(-1)[0];
const features = data.map(row => featureKeys.map(key => parseFloat(row[key])));
const labels = data.map(row => parseFloat(row[labelKey]));
const xs = tf.tensor2d(features);
const taskType = document.getElementById("task-type").value;
let model;
if (taskType === "classification") {
const uniqueClasses = Array.from(new Set(labels));
const numClasses = uniqueClasses.length;
const labelIndices = labels.map(l => uniqueClasses.indexOf(l));
const ys = tf.tensor1d(labelIndices, 'int32');
model = tf.sequential();
model.add(tf.layers.dense({units: 16, activation: 'relu', inputShape: [xs.shape[1]]}));
model.add(tf.layers.dense({units: numClasses, activation: 'softmax'}));
model.compile({
optimizer: tf.train.adam(parseFloat(document.getElementById("learning-rate").value)),
loss: 'sparseCategoricalCrossentropy',
metrics: ['accuracy']
});
tabularModel = model;
appendLog("Tabular classification model compiled.");
const epochs = parseInt(document.getElementById("epochs").value);
const batchSize = parseInt(document.getElementById("batch-size").value);
const valSplit = parseFloat(document.getElementById("val-split").value);
await model.fit(xs, ys, {
epochs: epochs,
batchSize: batchSize,
validationSplit: valSplit,
callbacks: {
onEpochEnd: async (epoch, logs) => {
const acc = logs.acc || logs.accuracy;
appendLog(`Tabular model training - Epoch ${epoch+1}: Loss = ${logs.loss.toFixed(4)}, Accuracy = ${acc.toFixed(4)}`);
updateProgressBar(((epoch+1) / epochs) * 100);
updateLossChart(epoch+1, logs.loss);
}
}
});
appendLog("Tabular model training completed.");
} else {
const ys = tf.tensor2d(labels, [labels.length, 1]);
model = tf.sequential();
model.add(tf.layers.dense({units: 16, activation: 'relu', inputShape: [xs.shape[1]]}));
model.add(tf.layers.dense({units: 1}));
model.compile({
optimizer: tf.train.adam(parseFloat(document.getElementById("learning-rate").value)),
loss: 'meanSquaredError'
});
tabularModel = model;
appendLog("Tabular regression model compiled.");
const epochs = parseInt(document.getElementById("epochs").value);
const batchSize = parseInt(document.getElementById("batch-size").value);
const valSplit = parseFloat(document.getElementById("val-split").value);
await model.fit(xs, ys, {
epochs: epochs,
batchSize: batchSize,
validationSplit: valSplit,
callbacks: {
onEpochEnd: async (epoch, logs) => {
appendLog(`Tabular model training - Epoch ${epoch+1}: Loss = ${logs.loss.toFixed(4)}`);
updateProgressBar(((epoch+1) / epochs) * 100);
updateLossChart(epoch+1, logs.loss);
}
}
});
appendLog("Tabular model training completed.");
}
}
});
}
async function predictTabular() {
if (!tabularModel) {
appendLog("No tabular model available for prediction.");
return;
}
const inputText = document.getElementById("predict-input").value;
if (!inputText) {
appendLog("Please enter comma-separated features for prediction.");
return;
}
const features = inputText.split(',').map(s => parseFloat(s.trim()));
const inputTensor = tf.tensor2d([features]);
const prediction = tabularModel.predict(inputTensor);
const predictionData = await prediction.data();
const taskType = document.getElementById("task-type").value;
let output;
if (taskType === "classification") {
const maxIndex = predictionData.indexOf(Math.max(...predictionData));
output = "Predicted class: " + maxIndex;
} else {
output = "Predicted value: " + predictionData[0].toFixed(2);
}
document.getElementById("predict-output").innerText = output;
appendLog("Tabular model prediction completed.");
}
async function saveTabularModel() {
if (!tabularModel) {
appendLog("No tabular model to save.");
return;
}
await tabularModel.save('indexeddb://tabular-model');
appendLog("Tabular model saved to IndexedDB.");
}
async function loadTabularModel() {
try {
tabularModel = await tf.loadLayersModel('indexeddb://tabular-model');
appendLog("Tabular model loaded from IndexedDB.");
} catch (error) {
appendLog("Failed to load tabular model: " + error.message);
}
}
function updateProgressBar(percentage) {
const progressBar = document.getElementById("progress-bar");
progressBar.style.width = percentage + "%";
}
function updateLossChart(epoch, loss) {
const ctx = document.getElementById('loss-chart').getContext('2d');
if (!lossChart) {
lossChart = new Chart(ctx, {
type: 'line',
data: {
labels: [epoch],
datasets: [{
label: 'Loss',
data: [loss],
borderColor: 'blue',
fill: false
}]
},
options: {
scales: {
x: {
title: { display: true, text: 'Epoch' }
},
y: {
title: { display: true, text: 'Loss' }
}
}
}
});
} else {
lossChart.data.labels.push(epoch);
lossChart.data.datasets[0].data.push(loss);
lossChart.update();
}
}
// --- Event Listeners ---
document.getElementById('pretrain-btn').addEventListener('click', pretrainLanguageModel);
document.getElementById('finetune-btn').addEventListener('click', finetuneLanguageModel);
document.getElementById('generate-btn').addEventListener('click', generateResponse);
document.getElementById('save-language-btn').addEventListener('click', saveLanguageModel);
document.getElementById('load-language-btn').addEventListener('click', loadLanguageModel);
document.getElementById('train-tabular-btn').addEventListener('click', trainTabularModel);
document.getElementById('predict-tabular-btn').addEventListener('click', predictTabular);
document.getElementById('save-tabular-btn').addEventListener('click', saveTabularModel);
document.getElementById('load-tabular-btn').addEventListener('click', loadTabularModel);
appendLog("Event listeners attached");
/*
// Maya/HeuristicMeshReduction snippet (non-executable in browser; provided for reference)
import maya.cmds as cmds
import json
import os
import numpy as np
class HeuristicMeshReduction:
def __init__(self, mesh_name, target_face_count):
\"\"\"
Heuristic-based adaptive mesh reduction to mimic ML-based prediction.
Parameters:
mesh_name (str): Name of the mesh to reduce.
target_face_count (int): Desired face count after reduction.
\"\"\"
self.mesh_name = mesh_name
self.target_face_count = target_face_count
def extract_mesh_features(self):
\"\"\"
Extracts basic mesh features used to determine reduction parameters.
\"\"\"
face_count = cmds.polyEvaluate(self.mesh_name, face=True)
edge_count = cmds.polyEvaluate(self.mesh_name, edge=True)
uv_count = len(cmds.polyListComponentConversion(self.mesh_name, tuv=True))
*/
} catch (error) {
console.error("Error in script:", error);
if (window.appendLog) {
appendLog("Error in script: " + error.message);
} else {
document.body.innerHTML += "<p style='color:red;'>Error in script: " + error.message + "</p>";
}
}
});
</script>
</body>
</html>