Spaces:
Running
Running
File size: 11,842 Bytes
1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a dd1b723 1ddfd0a |
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 |
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0';
// Configure environment
env.allowLocalModels = false;
// State
let generator = null;
let currentModel = null;
let isVisionModel = false;
let currentImage = null;
let isGenerating = false;
let conversationHistory = [];
// DOM Elements
const modelSelect = document.getElementById('model-select');
const loadModelBtn = document.getElementById('load-model-btn');
const loadingContainer = document.getElementById('loading-container');
const loadingStatus = document.getElementById('loading-status');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const chatContainer = document.getElementById('chat-container');
const chatMessages = document.getElementById('chat-messages');
const imageInput = document.getElementById('image-input');
const attachImageBtn = document.getElementById('attach-image-btn');
const imageUrlInput = document.getElementById('image-url-input');
const loadUrlBtn = document.getElementById('load-url-btn');
const imagePreviewContainer = document.getElementById('image-preview-container');
const imagePreview = document.getElementById('image-preview');
const removeImageBtn = document.getElementById('remove-image-btn');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const errorContainer = document.getElementById('error-container');
const errorMessage = document.getElementById('error-message');
const dismissErrorBtn = document.getElementById('dismiss-error-btn');
// Settings
const maxTokensSlider = document.getElementById('max-tokens');
const maxTokensValue = document.getElementById('max-tokens-value');
const temperatureSlider = document.getElementById('temperature');
const temperatureValue = document.getElementById('temperature-value');
const topPSlider = document.getElementById('top-p');
const topPValue = document.getElementById('top-p-value');
// Vision model identifiers
const VISION_MODELS = ['SmolVLM', 'Fara', 'llava', 'vision'];
function isVisionModelSelected(modelId) {
return VISION_MODELS.some(vm => modelId.toLowerCase().includes(vm.toLowerCase()));
}
// Progress callback for model loading
function progressCallback(progress) {
if (progress.status === 'initiate') {
loadingStatus.textContent = `Loading ${progress.file || 'model'}...`;
} else if (progress.status === 'download') {
loadingStatus.textContent = `Downloading ${progress.file || 'model'}...`;
} else if (progress.status === 'progress') {
const percent = Math.round(progress.progress || 0);
progressBar.style.width = `${percent}%`;
progressText.textContent = `${percent}%`;
loadingStatus.textContent = `Downloading ${progress.file || 'model'}...`;
} else if (progress.status === 'done') {
loadingStatus.textContent = `Loaded ${progress.file || 'model'}`;
} else if (progress.status === 'ready') {
loadingStatus.textContent = 'Model ready!';
progressBar.style.width = '100%';
progressText.textContent = '100%';
}
}
// Load model
async function loadModel() {
const modelId = modelSelect.value;
if (currentModel === modelId && generator) {
showError('Model already loaded!');
return;
}
try {
loadModelBtn.disabled = true;
loadingContainer.classList.remove('hidden');
chatContainer.classList.add('hidden');
progressBar.style.width = '0%';
progressText.textContent = '0%';
loadingStatus.textContent = 'Initializing...';
isVisionModel = isVisionModelSelected(modelId);
// Clean up previous model
if (generator) {
generator = null;
}
// Determine device - try WebGPU first
let device = 'wasm';
if (navigator.gpu) {
try {
const adapter = await navigator.gpu.requestAdapter();
if (adapter) {
device = 'webgpu';
loadingStatus.textContent = 'Using WebGPU acceleration...';
}
} catch (e) {
console.log('WebGPU not available, falling back to WASM');
}
}
loadingStatus.textContent = `Loading model on ${device.toUpperCase()}...`;
// Create pipeline based on model type
if (isVisionModel) {
generator = await pipeline('image-text-to-text', modelId, {
device: device,
dtype: 'q4f16',
progress_callback: progressCallback,
});
} else {
generator = await pipeline('text-generation', modelId, {
device: device,
dtype: 'q4f16',
progress_callback: progressCallback,
});
}
currentModel = modelId;
conversationHistory = [];
// Update UI
loadingContainer.classList.add('hidden');
chatContainer.classList.remove('hidden');
sendBtn.disabled = false;
// Update attach button visibility
attachImageBtn.style.display = isVisionModel ? 'block' : 'none';
imageUrlInput.style.display = isVisionModel ? 'block' : 'none';
loadUrlBtn.style.display = isVisionModel ? 'block' : 'none';
// Clear chat and show ready message
chatMessages.innerHTML = `
<div class="welcome-message">
<p>✅ <strong>${modelId.split('/').pop()}</strong> loaded successfully!</p>
<p class="hint">${isVisionModel ? 'This is a vision model. You can attach images to your messages.' : 'This is a
text-only model for conversation.'}</p>
</div>
`;
} catch (error) {
console.error('Error loading model:', error);
showError(`Failed to load model: ${error.message}`);
loadingContainer.classList.add('hidden');
} finally {
loadModelBtn.disabled = false;
}
}
// Handle image upload
function handleImageUpload(file) {
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
currentImage = e.target.result;
imagePreview.src = currentImage;
imagePreviewContainer.classList.remove('hidden');
};
reader.readAsDataURL(file);
}
// Load image from URL
async function loadImageFromUrl() {
const url = imageUrlInput.value.trim();
if (!url) return;
try {
currentImage = url;
imagePreview.src = url;
imagePreviewContainer.classList.remove('hidden');
imageUrlInput.value = '';
} catch (error) {
showError('Failed to load image from URL');
}
}
// Remove attached image
function removeImage() {
currentImage = null;
imagePreview.src = '';
imagePreviewContainer.classList.add('hidden');
imageInput.value = '';
}
// Add message to chat
function addMessage(role, content, imageUrl = null) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role}`;
const label = document.createElement('div');
label.className = 'message-label';
label.textContent = role === 'user' ? 'You' : 'Assistant';
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
if (imageUrl) {
const img = document.createElement('img');
img.src = imageUrl;
img.className = 'message-image';
contentDiv.appendChild(img);
}
const textSpan = document.createElement('span');
textSpan.textContent = content;
contentDiv.appendChild(textSpan);
messageDiv.appendChild(label);
messageDiv.appendChild(contentDiv);
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
return contentDiv;
}
// Add typing indicator
function addTypingIndicator() {
const messageDiv = document.createElement('div');
messageDiv.className = 'message assistant';
messageDiv.id = 'typing-indicator';
const label = document.createElement('div');
label.className = 'message-label';
label.textContent = 'Assistant';
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
const typingDiv = document.createElement('div');
typingDiv.className = 'typing-indicator';
typingDiv.innerHTML = '<span></span><span></span><span></span>';
contentDiv.appendChild(typingDiv);
messageDiv.appendChild(label);
messageDiv.appendChild(contentDiv);
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Remove typing indicator
function removeTypingIndicator() {
const indicator = document.getElementById('typing-indicator');
if (indicator) {
indicator.remove();
}
}
// Send message
async function sendMessage() {
const text = userInput.value.trim();
if (!text || !generator || isGenerating) return;
isGenerating = true;
sendBtn.disabled = true;
userInput.disabled = true;
try {
// Add user message
addMessage('user', text, currentImage);
// Clear input
userInput.value = '';
const imageForMessage = currentImage;
removeImage();
// Show typing indicator
addTypingIndicator();
// Get generation settings
const maxTokens = parseInt(maxTokensSlider.value);
const temperature = parseFloat(temperatureSlider.value);
const topP = parseFloat(topPSlider.value);
let response;
if (isVisionModel && imageForMessage) {
// Vision model with image
const messages = [
{
role: 'user',
content: [
{ type: 'image', image: imageForMessage },
{ type: 'text', text: text }
]
}
];
const output = await generator(messages, {
max_new_tokens: maxTokens,
temperature: temperature,
top_p: topP,
do_sample: temperature > 0,
});
response = output[0].generated_text.at(-1).content;
} else if (isVisionModel) {
// Vision model without image - text only
const messages = [
{
role: 'user',
content: [
{ type: 'text', text: text }
]
}
];
const output = await generator(messages, {
max_new_tokens: maxTokens,
temperature: temperature,
top_p: topP,
do_sample: temperature > 0,
});
response = output[0].generated_text.at(-1).content;
} else {
// Text-only model
conversationHistory.push({ role: 'user', content: text });
const output = await generator(conversationHistory, {
max_new_tokens: maxTokens,
temperature: temperature,
top_p: topP,
do_sample: temperature > 0,
});
const generatedMessages = output[0].generated_text;
const assistantMessage = generatedMessages[generatedMessages.length - 1];
response = assistantMessage.content;
conversationHistory.push({ role: 'assistant', content: response });
}
// Remove typing indicator and add response
removeTypingIndicator();
addMessage('assistant', response);
} catch (error) {
console.error('Error generating response:', error);
removeTypingIndicator();
showError(`Generation error: ${error.message}`);
} finally {
isGenerating = false;
sendBtn.disabled = false;
userInput.disabled = false;
userInput.focus();
}
}
// Show error
function showError(message) {
errorMessage.textContent = message;
errorContainer.classList.remove('hidden');
}
// Hide error
function hideError() {
errorContainer.classList.add('hidden');
}
// Event Listeners
loadModelBtn.addEventListener('click', loadModel);
attachImageBtn.addEventListener('click', () => {
if (isVisionModel) {
imageInput.click();
}
});
imageInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
handleImageUpload(e.target.files[0]);
}
});
loadUrlBtn.addEventListener('click', loadImageFromUrl);
imageUrlInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
loadImageFromUrl();
}
});
removeImageBtn.addEventListener('click', removeImage);
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
dismissErrorBtn.addEventListener('click', hideError);
// Settings sliders
maxTokensSlider.addEventListener('input', () => {
maxTokensValue.textContent = maxTokensSlider.value;
});
temperatureSlider.addEventListener('input', () => {
temperatureValue.textContent = temperatureSlider.value;
});
topPSlider.addEventListener('input', () => {
topPValue.textContent = topPSlider.value;
});
// Drag and drop for images
chatContainer.addEventListener('dragover', (e) => {
if (isVisionModel) {
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
}
});
chatContainer.addEventListener('drop', (e) => {
if (isVisionModel) {
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length > 0 && files[0].type.startsWith('image/')) {
handleImageUpload(files[0]);
}
}
});
// Initialize
document.addEventListener('DOMContentLoaded', () => {
// Hide image controls initially
attachImageBtn.style.display = 'none';
imageUrlInput.style.display = 'none';
loadUrlBtn.style.display = 'none';
}); |