-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat-lfm.html
More file actions
211 lines (183 loc) · 10.5 KB
/
chat-lfm.html
File metadata and controls
211 lines (183 loc) · 10.5 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
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Liquid LFM 2.5 - WebGPU Mobile</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
.dot-pulse { animation: pulse 1.5s infinite; }
@keyframes pulse { 0%, 100% { opacity: 0.4; } 50% { opacity: 1; } }
#chat-container::-webkit-scrollbar { width: 6px; }
#chat-container::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
</style>
</head>
<body class="bg-slate-50 h-screen flex flex-col font-sans">
<!-- Header -->
<header class="bg-white border-b p-4 flex justify-between items-center shadow-sm">
<div>
<h1 class="font-bold text-slate-800 text-lg">Liquid LFM 2.5</h1>
<p id="status-text" class="text-xs text-slate-500 italic font-medium">Verificando WebGPU...</p>
</div>
<div id="gpu-badge" class="px-2 py-1 rounded text-[10px] font-bold uppercase tracking-wider bg-slate-200 text-slate-600">
OFFLINE
</div>
</header>
<!-- Chat Area -->
<main id="chat-container" class="flex-1 overflow-y-auto p-4 space-y-4">
<div class="bg-blue-50 border border-blue-100 p-3 rounded-lg text-sm text-blue-800">
<strong>Dica:</strong> O primeiro carregamento pode baixar algumas centenas de MB. Recomendamos Wi‑Fi. O modelo roda localmente no navegador.
</div>
</main>
<!-- Progress Overlay (Only during load) -->
<div id="loading-overlay" class="hidden fixed inset-0 bg-white/90 z-50 flex flex-col items-center justify-center p-6 text-center">
<div class="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mb-4"></div>
<h2 class="text-xl font-bold text-slate-800 mb-2">Baixando Inteligência...</h2>
<div class="w-full max-w-xs bg-slate-200 h-2 rounded-full overflow-hidden">
<div id="progress-bar" class="bg-blue-600 h-full w-0 transition-all duration-300"></div>
</div>
<p id="progress-text" class="text-sm text-slate-500 mt-2 italic">Preparando arquivos...</p>
</div>
<!-- Input Area -->
<footer class="p-4 bg-white border-t">
<div class="flex gap-2">
<input type="text" id="user-input" placeholder="Digite sua mensagem..."
class="flex-1 border border-slate-300 rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-slate-100"
disabled>
<button id="send-btn" class="bg-blue-600 text-white p-2 rounded-full hover:bg-blue-700 disabled:bg-slate-300 shadow-lg transition-all" disabled>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
</svg>
</button>
</div>
<p class="text-[10px] text-center text-slate-400 mt-2 uppercase tracking-widest">Processamento Local via WebGPU</p>
</footer>
<script type="module">
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.2.1/+esm';
// Configuração para usar WebGPU
env.allowLocalModels = false;
const chatContainer = document.getElementById('chat-container');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const statusText = document.getElementById('status-text');
const gpuBadge = document.getElementById('gpu-badge');
const loadingOverlay = document.getElementById('loading-overlay');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
let generator = null;
let runtimeDevice = 'wasm';
let isGenerating = false;
const history = [];
// 1. Verificar WebGPU
async function checkWebGPU() {
try {
const adapter = navigator.gpu ? await navigator.gpu.requestAdapter() : null;
if (!adapter) {
gpuBadge.innerText = 'CPU/WASM';
gpuBadge.className = 'px-2 py-1 rounded text-[10px] font-bold uppercase bg-amber-100 text-amber-700';
statusText.innerText = 'WebGPU indisponível, usando CPU (mais lento)';
statusText.className = 'text-xs text-amber-600 font-bold';
addMessage('Sistema', 'Seu navegador não expôs WebGPU. Vou usar modo CPU/WASM (mais lento, mas funciona).', 'bg-amber-50 text-amber-800');
} else {
// WebGPU pode existir mas ainda falhar em alguns devices/models.
// Mantemos WASM como padrão para estabilidade.
gpuBadge.innerText = 'WEBGPU DISPONÍVEL';
gpuBadge.className = 'px-2 py-1 rounded text-[10px] font-bold uppercase bg-green-100 text-green-700';
statusText.innerText = 'Modo estável ativo (CPU/WASM)';
addMessage('Sistema', 'WebGPU está disponível, mas este demo usa modo estável CPU/WASM para evitar erros no mobile.', 'bg-green-50 text-green-800');
}
userInput.disabled = false;
userInput.placeholder = 'Clique em carregar primeiro...';
const loadBtn = document.createElement('button');
loadBtn.innerText = 'Carregar Modelo Local';
loadBtn.className = 'w-full py-3 bg-blue-600 text-white rounded-lg font-bold shadow-md mt-2';
loadBtn.onclick = () => initModel();
chatContainer.appendChild(loadBtn);
} catch (e) {
statusText.innerText = 'Falha ao verificar aceleração local.';
statusText.className = 'text-xs text-red-500 font-bold';
return false;
}
}
// 2. Inicializar Modelo
async function initModel() {
loadingOverlay.classList.remove('hidden');
try {
// Modelo ONNX público e compatível com transformers.js no navegador
const modelId = 'onnx-community/Qwen2.5-0.5B-Instruct';
generator = await pipeline('text-generation', modelId, {
device: runtimeDevice,
dtype: 'q4', // Quantização 4-bit para reduzir uso de memória
progress_callback: (data) => {
if (data.status === 'progress') {
const p = Math.round(data.progress);
progressBar.style.width = `${p}%`;
progressText.innerText = `Baixando ${data.file}: ${p}%`;
}
}
});
loadingOverlay.classList.add('hidden');
statusText.innerText = "Modelo Carregado e Pronto";
userInput.disabled = false;
userInput.placeholder = "Pergunte algo ao LFM...";
sendBtn.disabled = false;
addMessage("Sistema", "Modelo carregado com sucesso! O processamento está ocorrendo totalmente no seu celular.", "bg-slate-100 text-slate-600");
// Remove o botão de carga
const btns = chatContainer.querySelectorAll('button');
btns.forEach(b => b.remove());
} catch (err) {
loadingOverlay.innerHTML = `<div class="p-4 bg-red-100 text-red-700 rounded-lg">Erro ao carregar: ${err.message}<br>Tente recarregar a página.</div>`;
console.error(err);
}
}
// 3. Gerenciar Mensagens
function addMessage(sender, text, classes = "") {
const msgDiv = document.createElement('div');
msgDiv.className = `p-3 rounded-2xl max-w-[85%] ${sender === 'Você' ? 'bg-blue-600 text-white self-end ml-auto' : 'bg-white border border-slate-200 text-slate-800 self-start'} ${classes}`;
msgDiv.innerHTML = `<p class="text-[10px] opacity-70 mb-1 font-bold uppercase tracking-tighter">${sender}</p><p class="text-sm leading-relaxed">${text.replace(/\n/g, '<br>')}</p>`;
chatContainer.appendChild(msgDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
return msgDiv;
}
// 4. Fluxo de Chat
async function handleChat() {
const prompt = userInput.value.trim();
if (!prompt || !generator || isGenerating) return;
isGenerating = true;
userInput.value = '';
userInput.disabled = true;
sendBtn.disabled = true;
addMessage("Você", prompt);
const aiMsgDiv = addMessage("LFM", "Pensando...", "dot-pulse italic");
try {
history.push({ role: 'user', content: prompt });
const recent = history.slice(-6);
const context = recent.map(m => `${m.role === 'user' ? 'Usuário' : 'Assistente'}: ${m.content}`).join('\n');
const fullPrompt = `Você é um assistente útil e direto. Responda em português.\n\n${context}\nAssistente:`;
const output = await generator(fullPrompt, {
max_new_tokens: 180,
temperature: 0.7,
do_sample: true,
top_p: 0.9,
return_full_text: false,
});
let reply = (output?.[0]?.generated_text || '').trim();
if (!reply) reply = 'Não consegui gerar resposta agora. Tente novamente.';
history.push({ role: 'assistant', content: reply });
aiMsgDiv.innerHTML = `<p class="text-[10px] opacity-70 mb-1 font-bold uppercase tracking-tighter">LFM</p><p class="text-sm leading-relaxed">${reply.replace(/\n/g, '<br>')}</p>`;
aiMsgDiv.classList.remove('dot-pulse', 'italic');
} catch (err) {
aiMsgDiv.innerText = "Erro ao gerar resposta: " + err.message;
} finally {
isGenerating = false;
userInput.disabled = false;
sendBtn.disabled = false;
userInput.focus();
}
}
sendBtn.onclick = handleChat;
userInput.onkeypress = (e) => { if(e.key === 'Enter') handleChat(); };
window.onload = checkWebGPU;
</script>
</body>
</html>