akhaliq HF Staff commited on
Commit
f28c8d2
·
1 Parent(s): fe4bc04

feat: implement Kimi-K2.6 chat interface with Gradio backend and image support

Browse files
Files changed (2) hide show
  1. app.py +76 -0
  2. index.html +252 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ import typing
4
+ from openai import OpenAI
5
+ from gradio import Server
6
+ from gradio.data_classes import FileData
7
+ from fastapi.responses import HTMLResponse
8
+
9
+ app = Server()
10
+
11
+ client = OpenAI(
12
+ base_url="https://router.huggingface.co/v1",
13
+ api_key=os.environ.get("HF_TOKEN", ""),
14
+ default_headers={
15
+ "X-HF-Bill-To": "huggingface"
16
+ }
17
+ )
18
+
19
+ def encode_image(image_path):
20
+ with open(image_path, "rb") as image_file:
21
+ return base64.b64encode(image_file.read()).decode('utf-8')
22
+
23
+ @app.api()
24
+ def chat(message: str, history: typing.List[typing.List[str]], image: typing.Optional[FileData] = None):
25
+ messages = []
26
+
27
+ # Reconstruct history
28
+ for user_msg, assistant_msg in history:
29
+ if user_msg:
30
+ messages.append({"role": "user", "content": [{"type": "text", "text": user_msg}]})
31
+ if assistant_msg:
32
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": assistant_msg}]})
33
+
34
+ # Add new message
35
+ content = []
36
+ if message:
37
+ content.append({"type": "text", "text": message})
38
+ else:
39
+ if image:
40
+ content.append({"type": "text", "text": "Describe this image."})
41
+
42
+ if image:
43
+ base64_image = encode_image(image.path)
44
+ img_type = "image/png"
45
+ if image.path.lower().endswith("jpg") or image.path.lower().endswith("jpeg"):
46
+ img_type = "image/jpeg"
47
+ content.append({
48
+ "type": "image_url",
49
+ "image_url": {
50
+ "url": f"data:{img_type};base64,{base64_image}"
51
+ }
52
+ })
53
+
54
+ messages.append({
55
+ "role": "user",
56
+ "content": content
57
+ })
58
+
59
+ try:
60
+ completion = client.chat.completions.create(
61
+ model="moonshotai/Kimi-K2.6:fireworks-ai",
62
+ messages=messages,
63
+ stream=False
64
+ )
65
+ return completion.choices[0].message.content
66
+ except Exception as e:
67
+ return f"Error: {str(e)}"
68
+
69
+ @app.get("/")
70
+ async def homepage():
71
+ html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "index.html")
72
+ with open(html_path, "r", encoding="utf-8") as f:
73
+ return HTMLResponse(f.read())
74
+
75
+ if __name__ == "__main__":
76
+ app.launch()
index.html ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Kimi-K2.6 Chat</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
9
+ <style>
10
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f7f7f8; margin: 0; }
11
+ .header { display: flex; align-items: center; justify-content: center; padding: 12px; background: white; border-bottom: 1px solid #e5e7eb; font-weight: 600; color: #111827; }
12
+ .chat-container { max-width: 800px; margin: 0 auto; height: calc(100vh - 49px); display: flex; flex-direction: column; }
13
+ .messages { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 20px; }
14
+ .message { display: flex; gap: 16px; padding: 0 20px; }
15
+ .message.assistant { }
16
+ .avatar { width: 30px; height: 30px; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-weight: bold; color: white; flex-shrink: 0; font-size: 14px; }
17
+ .avatar.user { background-color: #5436DA; }
18
+ .avatar.assistant { background-color: #10a37f; }
19
+ .content { flex: 1; line-height: 1.6; color: #374151; max-width: calc(100% - 46px); }
20
+ .input-area { padding: 20px; background: #f7f7f8; position: relative; }
21
+ .input-container { position: relative; display: flex; align-items: flex-end; background: white; border: 1px solid #d1d5db; border-radius: 16px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); padding: 8px 12px; max-width: 800px; margin: 0 auto; }
22
+ .input-container:focus-within { border-color: #10a37f; box-shadow: 0 0 0 1px #10a37f; }
23
+ textarea { flex: 1; border: none; outline: none; resize: none; max-height: 200px; min-height: 24px; padding: 8px; font-family: inherit; font-size: 16px; background: transparent; }
24
+ .btn-container { display: flex; align-items: center; height: 40px; }
25
+ .btn { display: flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 8px; border: none; background: transparent; color: #6b7280; cursor: pointer; transition: all 0.2s; }
26
+ .btn:hover { background: #f3f4f6; color: #374151; }
27
+ .btn.send { background: #10a37f; color: white; margin-left: 8px; transition: opacity 0.2s; }
28
+ .btn.send:hover { background: #0e906f; color: white; }
29
+ .btn.send:disabled { opacity: 0.5; cursor: not-allowed; }
30
+ .spinner { animation: spin 1s linear infinite; }
31
+ @keyframes spin { 100% { transform: rotate(360deg); } }
32
+ .image-preview-container { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; max-width: 800px; margin-left: auto; margin-right: auto; }
33
+ .image-preview { position: relative; display: inline-block; }
34
+ .image-preview img { width: 64px; height: 64px; object-fit: cover; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
35
+ .remove-image { position: absolute; top: -8px; right: -8px; background: white; color: #374151; border: 1px solid #e5e7eb; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; font-size: 12px; cursor: pointer; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
36
+ .remove-image:hover { background: #f3f4f6; }
37
+ .markdown { font-size: 16px; }
38
+ .markdown p { margin-bottom: 12px; }
39
+ .markdown p:last-child { margin-bottom: 0; }
40
+ .markdown pre { background: #1e1e1e; color: #d4d4d4; padding: 16px; border-radius: 8px; overflow-x: auto; margin-bottom: 12px; margin-top: 12px; }
41
+ .markdown code { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 14px; background: #e5e7eb; padding: 2px 4px; border-radius: 4px; color: #111827; }
42
+ .markdown pre code { background: transparent; padding: 0; color: inherit; }
43
+ .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #6b7280; gap: 16px; }
44
+ .empty-logo { width: 48px; height: 48px; border-radius: 50%; background: #10a37f; color: white; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: bold; }
45
+ </style>
46
+ </head>
47
+ <body>
48
+ <div class="header">
49
+ Kimi-K2.6 Chat
50
+ </div>
51
+ <div class="chat-container">
52
+ <div class="messages" id="messages">
53
+ <div class="empty-state" id="empty-state">
54
+ <div class="empty-logo">K</div>
55
+ <h2>How can I help you today?</h2>
56
+ </div>
57
+ </div>
58
+ <div class="input-area">
59
+ <div id="image-preview-area" class="image-preview-container" style="display: none;">
60
+ <div class="image-preview">
61
+ <img id="preview-img" src="" alt="Preview">
62
+ <button class="remove-image" onclick="removeImage()">
63
+ <i class="fas fa-times"></i>
64
+ </button>
65
+ </div>
66
+ </div>
67
+ <div class="input-container">
68
+ <input type="file" id="file-upload" accept="image/*" style="display: none" onchange="previewImage(event)">
69
+ <div class="btn-container">
70
+ <button class="btn" onclick="document.getElementById('file-upload').click()" title="Upload Image">
71
+ <i class="fas fa-image"></i>
72
+ </button>
73
+ </div>
74
+ <textarea id="user-input" rows="1" placeholder="Message Kimi-K2.6..." onkeydown="handleKeydown(event)" oninput="autoResize(this)"></textarea>
75
+ <div class="btn-container">
76
+ <button class="btn send" id="send-btn" onclick="sendMessage()" disabled>
77
+ <i class="fas fa-arrow-up"></i>
78
+ </button>
79
+ </div>
80
+ </div>
81
+ <div style="text-align: center; font-size: 12px; color: #9ca3af; margin-top: 12px;">
82
+ Kimi-K2.6 can make mistakes. Consider verifying important information.
83
+ </div>
84
+ </div>
85
+ </div>
86
+
87
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
88
+ <script type="module">
89
+ import { Client, handle_file } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
90
+
91
+ let client = null;
92
+ let history = [];
93
+ let selectedFile = null;
94
+
95
+ async function initClient() {
96
+ try {
97
+ client = await Client.connect(window.location.origin);
98
+ console.log("Connected to Gradio Server");
99
+ } catch (e) {
100
+ console.error("Failed to connect:", e);
101
+ // Optionally show error to user
102
+ }
103
+ }
104
+
105
+ initClient();
106
+
107
+ window.autoResize = function(textarea) {
108
+ textarea.style.height = 'auto';
109
+ textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
110
+
111
+ const text = textarea.value.trim();
112
+ const btn = document.getElementById('send-btn');
113
+ if (text || selectedFile) {
114
+ btn.disabled = false;
115
+ } else {
116
+ btn.disabled = true;
117
+ }
118
+ };
119
+
120
+ window.handleKeydown = function(e) {
121
+ if (e.key === 'Enter' && !e.shiftKey) {
122
+ e.preventDefault();
123
+ if (!document.getElementById('send-btn').disabled) {
124
+ sendMessage();
125
+ }
126
+ }
127
+ };
128
+
129
+ window.previewImage = function(e) {
130
+ const file = e.target.files[0];
131
+ if (file) {
132
+ selectedFile = file;
133
+ const reader = new FileReader();
134
+ reader.onload = function(e) {
135
+ document.getElementById('preview-img').src = e.target.result;
136
+ document.getElementById('image-preview-area').style.display = 'flex';
137
+ document.getElementById('send-btn').disabled = false;
138
+ }
139
+ reader.readAsDataURL(file);
140
+ }
141
+ // Reset input so same file can be selected again
142
+ e.target.value = '';
143
+ };
144
+
145
+ window.removeImage = function() {
146
+ selectedFile = null;
147
+ document.getElementById('image-preview-area').style.display = 'none';
148
+ autoResize(document.getElementById('user-input')); // re-evaluate btn state
149
+ };
150
+
151
+ function addMessage(role, text, imageSrc = null) {
152
+ const emptyState = document.getElementById('empty-state');
153
+ if (emptyState) emptyState.style.display = 'none';
154
+
155
+ const messagesDiv = document.getElementById('messages');
156
+ const msgDiv = document.createElement('div');
157
+ msgDiv.className = `message ${role}`;
158
+
159
+ let avatar = role === 'user' ? '<div class="avatar user">U</div>' : '<div class="avatar assistant">K</div>';
160
+
161
+ let contentStr = '';
162
+ if (imageSrc) {
163
+ contentStr += `<img src="${imageSrc}" style="max-width: 250px; border-radius: 8px; margin-bottom: 12px; border: 1px solid #e5e7eb; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"><br>`;
164
+ }
165
+ if (text) {
166
+ contentStr += `<div class="markdown">${role === 'user' ? text : marked.parse(text)}</div>`;
167
+ }
168
+
169
+ msgDiv.innerHTML = `
170
+ ${avatar}
171
+ <div class="content">${contentStr}</div>
172
+ `;
173
+
174
+ messagesDiv.appendChild(msgDiv);
175
+ messagesDiv.scrollTop = messagesDiv.scrollHeight;
176
+ return msgDiv;
177
+ }
178
+
179
+ window.sendMessage = async function() {
180
+ if (!client) {
181
+ // If not connected yet, show visually but don't proceed
182
+ console.warn("Client not connected yet.");
183
+ }
184
+
185
+ const input = document.getElementById('user-input');
186
+ const text = input.value.trim();
187
+
188
+ if (!text && !selectedFile) return;
189
+
190
+ const sendBtn = document.getElementById('send-btn');
191
+ sendBtn.disabled = true;
192
+ sendBtn.innerHTML = '<i class="fas fa-spinner spinner"></i>';
193
+ input.disabled = true;
194
+
195
+ // Display user message
196
+ let imgSrc = null;
197
+ if (selectedFile) {
198
+ imgSrc = document.getElementById('preview-img').src;
199
+ }
200
+ addMessage('user', text, imgSrc);
201
+
202
+ const fileToSend = selectedFile;
203
+ const textToSend = text;
204
+
205
+ // Clear inputs
206
+ input.value = '';
207
+ input.style.height = 'auto';
208
+ removeImage();
209
+
210
+ // Add loading placeholder for assistant
211
+ const typingDiv = addMessage('assistant', '<i class="fas fa-circle-notch fa-spin type-indicator"></i>');
212
+
213
+ try {
214
+ let fileData = null;
215
+ if (fileToSend) {
216
+ fileData = handle_file(fileToSend);
217
+ }
218
+
219
+ // If client disconnect failed earlier, try mapping
220
+ if (!client) {
221
+ await initClient();
222
+ }
223
+
224
+ const result = await client.predict("/chat", {
225
+ message: textToSend,
226
+ history: history,
227
+ image: fileData
228
+ });
229
+
230
+ const responseText = result.data[0];
231
+
232
+ // Update history
233
+ history.push([textToSend, responseText]);
234
+
235
+ // Replace typing element with actual response
236
+ typingDiv.querySelector('.content').innerHTML = `<div class="markdown">${marked.parse(responseText)}</div>`;
237
+ } catch (err) {
238
+ console.error(err);
239
+ typingDiv.querySelector('.content').innerHTML = `<div class="markdown" style="color: #ef4444;">Sorry, I encountered an error. Please try again.</div>`;
240
+ } finally {
241
+ sendBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
242
+ input.disabled = false;
243
+ input.focus();
244
+ autoResize(input); // will disable button if text is empty
245
+
246
+ const messagesDiv = document.getElementById('messages');
247
+ messagesDiv.scrollTop = messagesDiv.scrollHeight;
248
+ }
249
+ };
250
+ </script>
251
+ </body>
252
+ </html>