File size: 13,116 Bytes
2c082ce
 
 
 
 
c88be65
2c082ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c88be65
2c082ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df4d0b5
2c082ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tema_Q-R4.2-Chat</title>
    <style>
        :root { --background-color: #fff; --header-bg: #fff; --chat-bg: #fff; --input-bg: #f5f5f5; --input-shadow: rgba(0, 0, 0, 0.1); --user-message-bg: #0084ff; --user-message-color: #fff; --bot-message-bg: #f5f5f5; --bot-message-color: #000; --text-color: #000; --send-button-bg: #000; --send-button-color: #fff; --send-button-disabled-bg: #ccc; --send-button-stop-bg: #d32f2f; --new-chat-button-bg: #999; --new-chat-button-color: #fff; --code-bg: #2d2d2d; --code-color: #f8f8f2; }
        [data-theme="dark"] { --background-color: #1e1e1e; --header-bg: #2a2a2a; --chat-bg: #1e1e1e; --input-bg: #333; --input-shadow: rgba(0, 0, 0, 0.3); --user-message-bg: #005bb5; --user-message-color: #fff; --bot-message-bg: #444; --bot-message-color: #ddd; --text-color: #ddd; --send-button-bg: #555; --send-button-color: #fff; --send-button-disabled-bg: #666; --send-button-stop-bg: #e57373; --new-chat-button-bg: #666; --new-chat-button-color: #fff; --code-bg: #1a1a1a; --code-color: #f8f8f2; }
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: var(--background-color); color: var(--text-color); display: flex; flex-direction: column; height: 100vh; overflow: hidden; -webkit-overflow-scrolling: touch; touch-action: manipulation; }
        .header { background-color: var(--header-bg); padding: 10px; display: flex; justify-content: flex-end; align-items: center; flex-shrink: 0; position: fixed; top: 0; right: 0; width: 100%; z-index: 20; }
        #new-chat-button, #theme-toggle-button { background-color: var(--new-chat-button-bg); color: var(--new-chat-button-color); border: none; border-radius: 50%; width: 32px; height: 32px; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-left: 10px; font-size: 20px; }
        #theme-toggle-button img { width: 20px; height: 20px; object-fit: contain; }
        .chat-container { flex: 1; width: 100%; max-width: 100%; display: flex; flex-direction: column; background-color: var(--chat-bg); position: relative; overflow: hidden; padding-top: 52px; }
        .chat-messages { flex: 1; padding: 10px; padding-bottom: 100px; overflow-y: auto; -webkit-overflow-scrolling: touch; touch-action: pan-y; }
        .message { margin-bottom: 10px; display: flex; flex-direction: column; }
        .message.user { align-items: flex-end; }
        .message.bot { align-items: flex-start; }
        .message-content { max-width: 80%; padding: 8px 12px; border-radius: 6px; font-size: 16px; line-height: 1.6; }
        .message.user .message-content { background-color: var(--user-message-bg); color: var(--user-message-color); white-space: pre-wrap; word-wrap: break-word; }
        .message.bot .message-content { background-color: var(--bot-message-bg); color: var(--bot-message-color); white-space: pre-wrap; word-wrap: break-word; text-align: left; }
        .status-info { font-size: 11px; color: #888; margin-top: 4px; padding-left: 12px; font-family: monospace; }
        [data-theme="dark"] .status-info { color: #aaa; }
        .message.bot pre { background-color: var(--code-bg); padding: 12px; border-radius: 6px; overflow-x: auto; margin: 10px 0; white-space: pre; }
        .message.bot code { font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; color: var(--code-color); font-size: 14px; }
        .message.bot :not(pre) > code { background-color: var(--code-bg); padding: 2px 5px; border-radius: 3px; font-size: 90%; white-space: pre-wrap; }
        .input-container { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); width: 90%; max-width: 600px; z-index: 10; }
        .input-wrapper { display: flex; align-items: center; background-color: var(--input-bg); border-radius: 20px; padding: 8px 12px; box-shadow: 0 2px 5px var(--input-shadow); min-height: 40px; }
        #user-input { flex: 1; padding: 8px; border: none; background: transparent; font-size: 16px; outline: none; resize: none; min-height: 24px; max-height: 120px; overflow-y: auto; line-height: 1.4; white-space: pre-wrap; word-wrap: break-word; align-self: center; color: var(--text-color); }
        #send-button { width: 30px; height: 30px; background-color: var(--send-button-bg); color: var(--send-button-color); border: none; border-radius: 50%; font-size: 16px; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; align-self: center; transition: background-color 0.2s; }
        #send-button:disabled { background-color: var(--send-button-disabled-bg); cursor: not-allowed; }
        #send-button.stop-mode { background-color: var(--send-button-stop-bg); font-size: 12px; }
        #welcome-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 40px; color: var(--text-color); z-index: 5; pointer-events: none; }
    </style>
</head>
<body data-theme="light">
    <div class="header">
        <button id="theme-toggle-button" title="γƒ€γƒΌγ‚―γƒ’γƒΌγƒ‰εˆ‡γ‚Šζ›Ώγˆ"><img src="1.png" alt="γƒ©γ‚€γƒˆγƒ’γƒΌγƒ‰" id="theme-icon"></button>
        <button id="new-chat-button" title="ζ–°γ—γ„γƒγƒ£γƒƒγƒˆγ‚’ι–‹ε§‹">↻</button>
    </div>
    <div class="chat-container">
        <div class="chat-messages" id="chat-messages"></div>
        <div id="welcome-text">Tema_Q-R4.2</div>
        <div class="input-container">
            <div class="input-wrapper">
                <textarea id="user-input" placeholder="ヒデルをロード中..." disabled></textarea>
                <button id="send-button" disabled>↑</button>
            </div>
        </div>
    </div>

    <script type="module">
        import { CreateMLCEngine } from "https://esm.run/@mlc-ai/web-llm";

        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const welcomeText = document.getElementById('welcome-text');
        const themeToggleButton = document.getElementById('theme-toggle-button');
        const newChatButton = document.getElementById('new-chat-button');
        const body = document.body;
        const themeIcon = document.getElementById('theme-icon');

        let engine;
        let isGenerating = false;
        let messages = [];

        async function initWebLLM() {
            const modelId = "Tema-Q-X-MLC";

            const appConfig = {
                model_list: [{
                    model_id: modelId,
                    model: "https://huggingface.co/kawasumi/Tema_Q-R4.2-MLC/resolve/main/",
                    model_lib: "https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/web-llm-models/v0_2_80/gemma-2-9b-it-q4f16_1-ctx4k_cs1k-webgpu.wasm",
                }]
            };

            const statusDiv = addMessage("Tema Q-X ヒデルロード中...", "bot");

            try {
                engine = await CreateMLCEngine(modelId, {
                    appConfig,
                    initProgressCallback: (report) => {
                        statusDiv.textContent = `ロード中: ${report.text} (${(report.progress * 100).toFixed(1)}%)`;
                    }
                });
                statusDiv.parentElement.remove();
                userInput.placeholder = "パッセージをε…₯εŠ›...";
                userInput.disabled = false;
                checkInput();
            } catch (err) {
                statusDiv.textContent = "エラー: ヒデルロード倱敗。ブラウアコンソールを璺θͺγ—てください。";
                console.error(err);
            }
        }

        function parseMarkdown(text) {
            if (!text) return '';
            let html = text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
            html = html.replace(/^### (.*$)/gm, '<h3>$1</h3>');
            html = html.replace(/^## (.*$)/gm, '<h2>$1</h2>');
            html = html.replace(/^# (.*$)/gm, '<h1>$1</h1>');
            html = html.replace(/^\s*[-*+]\s/gm, 'β€’ ');
            html = html.replace(/```(\w*)?\n?([\s\S]*?)```/g, (m, lang, code) => `<pre><code>${code.trim()}</code></pre>`);
            html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
            html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
            return html;
        }

        function setGeneratingState(generating) {
            isGenerating = generating;
            sendButton.textContent = generating ? 'β– ' : '↑';
            sendButton.classList.toggle('stop-mode', generating);
            sendButton.disabled = false;
            if (!generating) checkInput();
        }

        async function sendMessage() {
            if (isGenerating) {
                await engine.interruptGenerate?.();
                setGeneratingState(false);
                return;
            }

            const message = userInput.value.trim();
            if (!message || !engine) return;

            userInput.value = '';
            userInput.style.height = 'auto';
            welcomeText.style.display = 'none';
            checkInput();

            addMessage(message, 'user');
            messages.push({ role: "user", content: message });

            const botContentDiv = addMessage('', 'bot');
            const statusDiv = document.createElement('div');
            statusDiv.className = 'status-info';
            botContentDiv.parentNode.appendChild(statusDiv);

            let fullBotText = '';
            setGeneratingState(true);

            try {
                const completion = await engine.chat.completions.create({
                    messages,
                    stream: true,
                    temperature: 0.7,
                });

                for await (const chunk of completion) {
                    const curText = chunk.choices[0]?.delta.content || "";
                    fullBotText += curText;
                    botContentDiv.innerHTML = parseMarkdown(fullBotText);

                    if (chunk.usage?.extra?.decode_tokens_per_s) {
                        const tps = chunk.usage.extra.decode_tokens_per_s.toFixed(1);
                        statusDiv.textContent = `${tps} tokens/s | ${chunk.usage.total_tokens ?? 0} tokens`;
                    }
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
                messages.push({ role: "assistant", content: fullBotText });
            } catch (error) {
                botContentDiv.innerHTML += '<br><span style="color:red;">γ‚¨γƒ©γƒΌγŒη™Ίη”Ÿγ—γΎγ—γŸγ€‚</span>';
                console.error(error);
            } finally {
                setGeneratingState(false);
            }
        }

        function addMessage(text, sender) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', sender);
            const contentDiv = document.createElement('div');
            contentDiv.classList.add('message-content');
            if (sender === 'user') contentDiv.textContent = text;
            else contentDiv.innerHTML = parseMarkdown(text);
            messageDiv.appendChild(contentDiv);
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            return contentDiv;
        }

        function checkInput() {
            if (!isGenerating) sendButton.disabled = userInput.value.trim().length === 0;
        }

        userInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = this.scrollHeight + 'px';
            checkInput();
        });

        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!isGenerating && !sendButton.disabled) sendMessage();
            }
        });

        sendButton.addEventListener('click', sendMessage);

        newChatButton.addEventListener('click', async () => {
            if (isGenerating) await engine.interruptGenerate?.();
            chatMessages.innerHTML = '';
            messages = [];
            welcomeText.style.display = 'block';
            userInput.value = '';
            setGeneratingState(false);
            if (engine) await engine.resetChat();
        });

        themeToggleButton.addEventListener('click', () => {
            const isLight = body.getAttribute('data-theme') === 'light';
            body.setAttribute('data-theme', isLight ? 'dark' : 'light');
            themeIcon.src = isLight ? '2.png' : '1.png';
            themeIcon.alt = isLight ? 'ダークヒード' : 'γƒ©γ‚€γƒˆγƒ’γƒΌγƒ‰';
        });

        initWebLLM();
    </script>
</body>
</html>