Spaces:
Running on Zero
Running on Zero
Commit ·
1b5e2bb
1
Parent(s): b74a8c4
Merge PR2 updated Gradio server app
Browse filesThanks to @akhaliq for the contribution.
Co-authored-by: Cursor <cursoragent@cursor.com>
- README.md +1 -2
- app.py +381 -32
- index.html +940 -0
- requirements.txt +9 -12
README.md
CHANGED
|
@@ -4,12 +4,11 @@ emoji: 🪐
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
python_version: "3.12"
|
| 9 |
app_file: app.py
|
| 10 |
models:
|
| 11 |
- openbmb/MiniCPM-V-4.6
|
| 12 |
-
- openbmb/MiniCPM-V-4.6-Thinking
|
| 13 |
pinned: true
|
| 14 |
short_description: MiniCPM-V 4.6 Ultra-Efficient Multimodal AI
|
| 15 |
---
|
|
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.14.0
|
| 8 |
python_version: "3.12"
|
| 9 |
app_file: app.py
|
| 10 |
models:
|
| 11 |
- openbmb/MiniCPM-V-4.6
|
|
|
|
| 12 |
pinned: true
|
| 13 |
short_description: MiniCPM-V 4.6 Ultra-Efficient Multimodal AI
|
| 14 |
---
|
app.py
CHANGED
|
@@ -1,35 +1,384 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import torch
|
| 3 |
+
import re
|
| 4 |
+
import av
|
| 5 |
+
import uuid
|
| 6 |
+
import copy
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
import shutil
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from transformers import AutoProcessor, MiniCPMV4_6ForConditionalGeneration, TextIteratorStreamer
|
| 12 |
+
from gradio import Server
|
| 13 |
+
from gradio.data_classes import FileData
|
| 14 |
+
from fastapi.responses import HTMLResponse
|
| 15 |
+
import logging
|
| 16 |
+
|
| 17 |
+
# Silence asyncio noise from ZeroGPU cleanup
|
| 18 |
+
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
|
| 19 |
+
|
| 20 |
+
from starlette.middleware import Middleware
|
| 21 |
+
import hashlib
|
| 22 |
+
import base64
|
| 23 |
+
import json
|
| 24 |
+
|
| 25 |
+
# ---------- Logging Middleware ----------
|
| 26 |
+
|
| 27 |
+
def _headers_from_asgi(raw_headers) -> list[dict]:
|
| 28 |
+
headers = []
|
| 29 |
+
for raw_key, raw_value in raw_headers or []:
|
| 30 |
+
headers.append({
|
| 31 |
+
"name": raw_key.decode("latin-1", errors="replace"),
|
| 32 |
+
"value": raw_value.decode("latin-1", errors="replace"),
|
| 33 |
+
})
|
| 34 |
+
return headers
|
| 35 |
+
|
| 36 |
+
def _header_value(headers: list[dict], name: str) -> str:
|
| 37 |
+
name = name.lower()
|
| 38 |
+
for header in headers:
|
| 39 |
+
if header["name"].lower() == name:
|
| 40 |
+
return header["value"]
|
| 41 |
+
return ""
|
| 42 |
+
|
| 43 |
+
def _body_text(data: bytes, content_type: str) -> str | None:
|
| 44 |
+
if not data: return ""
|
| 45 |
+
lower_type = (content_type or "").lower()
|
| 46 |
+
if "text/" in lower_type or "json" in lower_type or "x-www-form-urlencoded" in lower_type:
|
| 47 |
+
return data.decode("utf-8", errors="replace")
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
def _body_record(data: bytes, content_type: str) -> dict:
|
| 51 |
+
return {
|
| 52 |
+
"size": len(data),
|
| 53 |
+
"sha256": hashlib.sha256(data).hexdigest() if data else "",
|
| 54 |
+
"base64": base64.b64encode(data).decode("ascii") if data else "",
|
| 55 |
+
"text": _body_text(data, content_type),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
def _append_http_log(record: dict) -> None:
|
| 59 |
+
os.makedirs(os.path.dirname(HTTP_LOG_FILE), exist_ok=True)
|
| 60 |
+
line = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
|
| 61 |
+
with HTTP_LOG_LOCK:
|
| 62 |
+
with open(HTTP_LOG_FILE, "a", encoding="utf-8") as f:
|
| 63 |
+
f.write(line + "\n")
|
| 64 |
+
|
| 65 |
+
class HTTPRequestLogMiddleware:
|
| 66 |
+
def __init__(self, app):
|
| 67 |
+
self.app = app
|
| 68 |
+
|
| 69 |
+
async def __call__(self, scope, receive, send):
|
| 70 |
+
if scope.get("type") != "http":
|
| 71 |
+
await self.app(scope, receive, send)
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
+
started = time.time()
|
| 75 |
+
request_id = uuid.uuid4().hex[:12]
|
| 76 |
+
request_body = bytearray()
|
| 77 |
+
response_headers = []
|
| 78 |
+
response_body = bytearray()
|
| 79 |
+
status_code = None
|
| 80 |
+
|
| 81 |
+
async def receive_wrapper():
|
| 82 |
+
message = await receive()
|
| 83 |
+
if message.get("type") == "http.request":
|
| 84 |
+
chunk = message.get("body", b"")
|
| 85 |
+
if chunk: request_body.extend(chunk)
|
| 86 |
+
return message
|
| 87 |
+
|
| 88 |
+
async def send_wrapper(message):
|
| 89 |
+
nonlocal status_code, response_headers
|
| 90 |
+
if message.get("type") == "http.response.start":
|
| 91 |
+
status_code = message.get("status")
|
| 92 |
+
response_headers = _headers_from_asgi(message.get("headers", []))
|
| 93 |
+
elif message.get("type") == "http.response.body":
|
| 94 |
+
chunk = message.get("body", b"")
|
| 95 |
+
if chunk: response_body.extend(chunk)
|
| 96 |
+
await send(message)
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
await self.app(scope, receive_wrapper, send_wrapper)
|
| 100 |
+
finally:
|
| 101 |
+
request_headers = _headers_from_asgi(scope.get("headers", []))
|
| 102 |
+
client = scope.get("client") or (None, None)
|
| 103 |
+
record = {
|
| 104 |
+
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(started)),
|
| 105 |
+
"request_id": request_id,
|
| 106 |
+
"client_id": _header_value(request_headers, "x-v46-client-id"),
|
| 107 |
+
"method": scope.get("method"),
|
| 108 |
+
"path": scope.get("path"),
|
| 109 |
+
"status_code": status_code,
|
| 110 |
+
"duration_ms": round((time.time() - started) * 1000, 2),
|
| 111 |
+
}
|
| 112 |
+
try:
|
| 113 |
+
_append_http_log(record)
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"Logging error: {e}")
|
| 116 |
|
| 117 |
import spaces
|
| 118 |
+
from typing import Generator
|
| 119 |
+
|
| 120 |
+
# ---------- Globals & Model Loading ----------
|
| 121 |
+
MODEL_ID = "openbmb/MiniCPM-V-4.6"
|
| 122 |
+
print(f"Loading processor: {MODEL_ID}")
|
| 123 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 124 |
+
print(f"Loading model: {MODEL_ID}")
|
| 125 |
+
model = MiniCPMV4_6ForConditionalGeneration.from_pretrained(
|
| 126 |
+
MODEL_ID,
|
| 127 |
+
torch_dtype=torch.bfloat16,
|
| 128 |
+
attn_implementation="sdpa",
|
| 129 |
+
trust_remote_code=True,
|
| 130 |
+
device_map="cuda"
|
| 131 |
+
).eval()
|
| 132 |
+
|
| 133 |
+
# ---------- Logging & Helper Functions ----------
|
| 134 |
+
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
|
| 135 |
+
LOG_DIR = os.path.join(PROJECT_ROOT, "logs")
|
| 136 |
+
UPLOAD_LOG_DIR = os.path.join(LOG_DIR, "uploads")
|
| 137 |
+
HTTP_LOG_FILE = os.path.join(LOG_DIR, "http_requests.jsonl")
|
| 138 |
+
RAW_OUTPUT_LOG_FILE = os.path.join(LOG_DIR, "raw_model_outputs.jsonl")
|
| 139 |
+
HTTP_LOG_LOCK = threading.Lock()
|
| 140 |
+
RAW_OUTPUT_LOG_LOCK = threading.Lock()
|
| 141 |
+
|
| 142 |
+
def _append_raw_output_log(record: dict) -> None:
|
| 143 |
+
os.makedirs(os.path.dirname(RAW_OUTPUT_LOG_FILE), exist_ok=True)
|
| 144 |
+
line = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
|
| 145 |
+
with RAW_OUTPUT_LOG_LOCK:
|
| 146 |
+
with open(RAW_OUTPUT_LOG_FILE, "a", encoding="utf-8") as f:
|
| 147 |
+
f.write(line + "\n")
|
| 148 |
+
|
| 149 |
+
def log_raw_model_output(session_id: str, **record) -> None:
|
| 150 |
+
payload = {
|
| 151 |
+
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
| 152 |
+
"session_id": session_id,
|
| 153 |
+
**record,
|
| 154 |
+
}
|
| 155 |
+
try:
|
| 156 |
+
_append_raw_output_log(payload)
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"Logging error: {e}")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def load_video(video_path, max_frames=64):
|
| 162 |
+
"""Fast video loading using PyAV timestamp seeking."""
|
| 163 |
+
try:
|
| 164 |
+
container = av.open(video_path)
|
| 165 |
+
stream = container.streams.video[0]
|
| 166 |
+
stream.thread_count = 8
|
| 167 |
+
duration = stream.duration
|
| 168 |
+
if duration is None or duration <= 0:
|
| 169 |
+
frames = [f.to_image() for f in container.decode(video=0)]
|
| 170 |
+
if len(frames) > max_frames:
|
| 171 |
+
indices = [int(i * len(frames) / max_frames) for i in range(max_frames)]
|
| 172 |
+
return [frames[i] for i in indices]
|
| 173 |
+
return frames
|
| 174 |
+
|
| 175 |
+
indices = [int(i * duration / max_frames) for i in range(max_frames)]
|
| 176 |
+
frames = []
|
| 177 |
+
for ts in indices:
|
| 178 |
+
container.seek(ts, stream=stream)
|
| 179 |
+
for frame in container.decode(video=0):
|
| 180 |
+
frames.append(frame.to_image())
|
| 181 |
+
break
|
| 182 |
+
container.close()
|
| 183 |
+
return frames
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"Error loading video: {e}")
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
def persist_uploaded_files(files: list, session_id: str) -> list:
|
| 189 |
+
"""Copy Gradio temp uploads into the project log directory."""
|
| 190 |
+
if not files: return []
|
| 191 |
+
dest_dir = os.path.join(UPLOAD_LOG_DIR, session_id or "session")
|
| 192 |
+
os.makedirs(dest_dir, exist_ok=True)
|
| 193 |
+
persisted = []
|
| 194 |
+
for f in files:
|
| 195 |
+
src = f["path"] if isinstance(f, dict) else f
|
| 196 |
+
if not os.path.isfile(src):
|
| 197 |
+
persisted.append(src)
|
| 198 |
+
continue
|
| 199 |
+
base = os.path.basename(src)
|
| 200 |
+
stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
|
| 201 |
+
dest = os.path.join(dest_dir, f"{stamp}-{uuid.uuid4().hex[:8]}-{base}")
|
| 202 |
+
shutil.copy2(src, dest)
|
| 203 |
+
persisted.append(dest)
|
| 204 |
+
return persisted
|
| 205 |
+
|
| 206 |
+
def normalize_response_text(text: str) -> str:
|
| 207 |
+
"""Robust conversion of literal \n to newlines while protecting code/LaTeX."""
|
| 208 |
+
if not isinstance(text, str) or "\\" not in text:
|
| 209 |
+
return text
|
| 210 |
+
protected = {}
|
| 211 |
+
counter = [0]
|
| 212 |
+
def _convert(v):
|
| 213 |
+
v = re.sub(r"(?<!\\)(?:\\r\\n|\\n|\\r){2,}", lambda m: "\n" * len(re.findall(r"\\n|\\r", m.group(0))), v)
|
| 214 |
+
v = re.sub(r"(?<!\\)\\r\\n", "\n", v)
|
| 215 |
+
v = re.sub(r"(?<!\\)\\n(?![a-zA-Z])", "\n", v)
|
| 216 |
+
return v
|
| 217 |
+
def _protect(m):
|
| 218 |
+
key = f"\x00P{counter[0]}\x00"
|
| 219 |
+
counter[0] += 1
|
| 220 |
+
protected[key] = m.group(0)
|
| 221 |
+
return key
|
| 222 |
+
res = text
|
| 223 |
+
res = re.sub(r"```[\s\S]*?```", lambda m: _protect(re.match(r"```[\s\S]*?```", _convert(m.group(0)))), res) # Simplified for parity
|
| 224 |
+
res = re.sub(r"`[^`]+`", _protect, res)
|
| 225 |
+
res = _convert(res)
|
| 226 |
+
for k, v in protected.items(): res = res.replace(k, v)
|
| 227 |
+
return res
|
| 228 |
+
|
| 229 |
+
# ---------- Inference Endpoint ----------
|
| 230 |
+
|
| 231 |
+
demo = Server()
|
| 232 |
+
|
| 233 |
+
@demo.api()
|
| 234 |
+
@spaces.GPU(duration=120)
|
| 235 |
+
def predict(
|
| 236 |
+
message: str,
|
| 237 |
+
history: list[list] = None,
|
| 238 |
+
files: list[FileData] = None,
|
| 239 |
+
thinking_mode: bool = True,
|
| 240 |
+
max_new_tokens: int = 1024,
|
| 241 |
+
temperature: float = 0.7,
|
| 242 |
+
top_p: float = 0.8,
|
| 243 |
+
top_k: int = 100,
|
| 244 |
+
max_frames: int = 64,
|
| 245 |
+
generation_mode: str = "Sampling"
|
| 246 |
+
) -> Generator[str, None, None]:
|
| 247 |
+
"""
|
| 248 |
+
Streaming inference endpoint with history support.
|
| 249 |
+
"""
|
| 250 |
+
session_id = str(uuid.uuid4())
|
| 251 |
+
# Persist files in background to avoid blocking user (parity audit)
|
| 252 |
+
if files:
|
| 253 |
+
threading.Thread(target=persist_uploaded_files, args=(files, session_id), daemon=True).start()
|
| 254 |
+
messages = []
|
| 255 |
+
|
| 256 |
+
# Process history
|
| 257 |
+
if history:
|
| 258 |
+
for turn in history:
|
| 259 |
+
# history turn is [user_text, assistant_text, [optional_file_paths]]
|
| 260 |
+
user_text = turn[0]
|
| 261 |
+
assistant_text = turn[1]
|
| 262 |
+
turn_files = turn[2] if len(turn) > 2 else []
|
| 263 |
+
|
| 264 |
+
h_content = []
|
| 265 |
+
if turn_files:
|
| 266 |
+
for f_path in turn_files:
|
| 267 |
+
# In history, we don't have mime_type, so we check extension
|
| 268 |
+
ext = os.path.splitext(f_path)[1].lower()
|
| 269 |
+
if ext in {".mp4", ".mkv", ".mov", ".avi", ".webm"}:
|
| 270 |
+
v_frames = load_video(f_path, max_frames=max_frames)
|
| 271 |
+
if v_frames:
|
| 272 |
+
h_content.append({"type": "video", "video": v_frames})
|
| 273 |
+
else:
|
| 274 |
+
h_content.append({"type": "video", "path": f_path})
|
| 275 |
+
else:
|
| 276 |
+
try:
|
| 277 |
+
img = Image.open(f_path).convert("RGB")
|
| 278 |
+
h_content.append({"type": "image", "image": img})
|
| 279 |
+
except Exception:
|
| 280 |
+
v_frames = load_video(f_path, max_frames=max_frames)
|
| 281 |
+
if v_frames:
|
| 282 |
+
h_content.append({"type": "video", "video": v_frames})
|
| 283 |
+
else:
|
| 284 |
+
h_content.append({"type": "video", "path": f_path})
|
| 285 |
+
|
| 286 |
+
if user_text:
|
| 287 |
+
h_content.append({"type": "text", "text": user_text})
|
| 288 |
+
|
| 289 |
+
if h_content:
|
| 290 |
+
messages.append({"role": "user", "content": h_content})
|
| 291 |
+
if assistant_text:
|
| 292 |
+
messages.append({"role": "assistant", "content": [{"type": "text", "text": assistant_text}]})
|
| 293 |
+
|
| 294 |
+
content = []
|
| 295 |
+
if files:
|
| 296 |
+
for f in files:
|
| 297 |
+
file_path = f["path"]
|
| 298 |
+
try:
|
| 299 |
+
# Try image first
|
| 300 |
+
img = Image.open(file_path).convert("RGB")
|
| 301 |
+
content.append({"type": "image", "image": img})
|
| 302 |
+
except Exception:
|
| 303 |
+
# Fallback to manual video frame extraction (bypasses broken torchvision)
|
| 304 |
+
v_frames = load_video(file_path, max_frames=max_frames)
|
| 305 |
+
if v_frames:
|
| 306 |
+
content.append({"type": "video", "video": v_frames})
|
| 307 |
+
else:
|
| 308 |
+
print(f"Failed to load video: {file_path}")
|
| 309 |
+
|
| 310 |
+
if message:
|
| 311 |
+
content.append({"type": "text", "text": message})
|
| 312 |
+
|
| 313 |
+
if content:
|
| 314 |
+
messages.append({"role": "user", "content": content})
|
| 315 |
+
|
| 316 |
+
# Prepare inputs with Advanced Parameters for MiniCPM-V 4.6
|
| 317 |
+
with torch.no_grad():
|
| 318 |
+
inputs = processor.apply_chat_template(
|
| 319 |
+
messages,
|
| 320 |
+
add_generation_prompt=True,
|
| 321 |
+
tokenize=True,
|
| 322 |
+
return_dict=True,
|
| 323 |
+
return_tensors="pt",
|
| 324 |
+
enable_thinking=thinking_mode,
|
| 325 |
+
processor_kwargs={
|
| 326 |
+
"downsample_mode": "16x",
|
| 327 |
+
"max_slice_nums": 1 if any(it.get("type") == "video" for msg in messages for it in msg["content"]) else 9,
|
| 328 |
+
"use_image_id": False if any(it.get("type") == "video" for msg in messages for it in msg["content"]) else True,
|
| 329 |
+
"videos_kwargs": {
|
| 330 |
+
"max_num_frames": max_frames,
|
| 331 |
+
"do_sample_frames": False, # Frames are already sampled by load_video
|
| 332 |
+
"stack_frames": 1,
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
).to(model.device)
|
| 336 |
+
|
| 337 |
+
for k, v in inputs.items():
|
| 338 |
+
if isinstance(v, torch.Tensor) and torch.is_floating_point(v):
|
| 339 |
+
inputs[k] = v.to(dtype=torch.bfloat16)
|
| 340 |
+
|
| 341 |
+
streamer = TextIteratorStreamer(
|
| 342 |
+
processor.tokenizer,
|
| 343 |
+
skip_prompt=True,
|
| 344 |
+
skip_special_tokens=True,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
sampling = (generation_mode == "Sampling")
|
| 348 |
+
generate_kwargs = {
|
| 349 |
+
**inputs,
|
| 350 |
+
"max_new_tokens": max_new_tokens,
|
| 351 |
+
"do_sample": sampling,
|
| 352 |
+
"streamer": streamer,
|
| 353 |
+
"downsample_mode": "16x"
|
| 354 |
+
}
|
| 355 |
+
if sampling:
|
| 356 |
+
generate_kwargs.update({
|
| 357 |
+
"temperature": temperature,
|
| 358 |
+
"top_p": top_p,
|
| 359 |
+
"top_k": top_k,
|
| 360 |
+
})
|
| 361 |
+
else:
|
| 362 |
+
generate_kwargs.update({"num_beams": 1})
|
| 363 |
+
|
| 364 |
+
thread = threading.Thread(target=model.generate, kwargs=generate_kwargs)
|
| 365 |
+
thread.start()
|
| 366 |
+
|
| 367 |
+
full_text = ""
|
| 368 |
+
for new_text in streamer:
|
| 369 |
+
full_text += new_text
|
| 370 |
+
yield normalize_response_text(full_text)
|
| 371 |
+
|
| 372 |
+
log_raw_model_output(session_id, message=message, response=full_text, variant="thinking" if thinking_mode else "instruct")
|
| 373 |
+
|
| 374 |
+
@demo.get("/", response_class=HTMLResponse)
|
| 375 |
+
async def homepage():
|
| 376 |
+
html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "index.html")
|
| 377 |
+
with open(html_path, "r", encoding="utf-8") as f:
|
| 378 |
+
return f.read()
|
| 379 |
+
|
| 380 |
+
if __name__ == "__main__":
|
| 381 |
+
demo.launch(
|
| 382 |
+
show_error=True,
|
| 383 |
+
app_kwargs={"middleware": [Middleware(HTTPRequestLogMiddleware)]}
|
| 384 |
+
)
|
index.html
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, maximum-scale=1.0, user-scalable=no">
|
| 6 |
+
<title>MiniCPM-V | OpenBMB Premium</title>
|
| 7 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
| 8 |
+
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
|
| 9 |
+
<script src="https://unpkg.com/lucide@latest"></script>
|
| 10 |
+
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
| 11 |
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.css">
|
| 12 |
+
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.js"></script>
|
| 13 |
+
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/contrib/auto-render.min.js"></script>
|
| 14 |
+
<style>
|
| 15 |
+
:root {
|
| 16 |
+
--bg: #05070A;
|
| 17 |
+
--blue: #3B5BFF;
|
| 18 |
+
--cyan: #27D4EA;
|
| 19 |
+
--text: #FFFFFF;
|
| 20 |
+
--text-muted: #8B949E;
|
| 21 |
+
--glass: rgba(255, 255, 255, 0.03);
|
| 22 |
+
--glass-border: rgba(255, 255, 255, 0.08);
|
| 23 |
+
--accent: #3B5BFF;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
body {
|
| 27 |
+
font-family: 'Inter', sans-serif;
|
| 28 |
+
background-color: var(--bg);
|
| 29 |
+
color: var(--text);
|
| 30 |
+
height: 100vh;
|
| 31 |
+
margin: 0;
|
| 32 |
+
display: flex;
|
| 33 |
+
flex-direction: column;
|
| 34 |
+
overflow: hidden;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
h1, h2, h3 { font-family: 'Outfit', sans-serif; }
|
| 38 |
+
|
| 39 |
+
.chat-scroll-area {
|
| 40 |
+
flex: 1;
|
| 41 |
+
overflow-y: auto;
|
| 42 |
+
padding-bottom: 140px;
|
| 43 |
+
-webkit-overflow-scrolling: touch;
|
| 44 |
+
scroll-behavior: smooth;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
.chat-scroll-area::-webkit-scrollbar { width: 4px; }
|
| 48 |
+
.chat-scroll-area::-webkit-scrollbar-track { background: transparent; }
|
| 49 |
+
.chat-scroll-area::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); border-radius: 10px; }
|
| 50 |
+
|
| 51 |
+
.message-bubble {
|
| 52 |
+
max-width: 85%;
|
| 53 |
+
animation: fadeIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
| 54 |
+
position: relative;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
@keyframes fadeIn {
|
| 58 |
+
from { opacity: 0; transform: translateY(15px); }
|
| 59 |
+
to { opacity: 1; transform: translateY(0); }
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
.user-message {
|
| 63 |
+
background: linear-gradient(135deg, var(--blue), var(--cyan));
|
| 64 |
+
color: #FFFFFF;
|
| 65 |
+
box-shadow: 0 8px 25px rgba(59, 91, 255, 0.15);
|
| 66 |
+
border-radius: 24px 24px 4px 24px;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
.bot-message {
|
| 70 |
+
background: rgba(255, 255, 255, 0.03);
|
| 71 |
+
border: 1px solid var(--glass-border);
|
| 72 |
+
border-radius: 24px 24px 24px 4px;
|
| 73 |
+
backdrop-filter: blur(10px);
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
.thinking-block {
|
| 77 |
+
background: rgba(59, 91, 255, 0.05);
|
| 78 |
+
border-left: 3px solid var(--blue);
|
| 79 |
+
padding: 12px 16px;
|
| 80 |
+
margin-bottom: 12px;
|
| 81 |
+
border-radius: 4px 12px 12px 4px;
|
| 82 |
+
font-size: 14px;
|
| 83 |
+
color: var(--text-muted);
|
| 84 |
+
font-style: italic;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
.typing-dot {
|
| 88 |
+
width: 4px; height: 4px;
|
| 89 |
+
background: var(--cyan);
|
| 90 |
+
border-radius: 50%;
|
| 91 |
+
animation: bounce 1.4s infinite ease-in-out;
|
| 92 |
+
}
|
| 93 |
+
/* Tab Styles */
|
| 94 |
+
.tab-btn {
|
| 95 |
+
@apply px-6 py-3 text-sm font-bold text-white/40 border-b-2 border-transparent transition-all;
|
| 96 |
+
}
|
| 97 |
+
.tab-btn.active {
|
| 98 |
+
@apply text-white border-white;
|
| 99 |
+
}
|
| 100 |
+
.tab-content {
|
| 101 |
+
display: none;
|
| 102 |
+
}
|
| 103 |
+
.tab-content.active {
|
| 104 |
+
display: flex;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
@keyframes bounce {
|
| 108 |
+
0%, 80%, 100% { transform: scale(0.3); opacity: 0.4; }
|
| 109 |
+
40% { transform: scale(1); opacity: 1; }
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
.input-pill {
|
| 113 |
+
background: rgba(255, 255, 255, 0.04);
|
| 114 |
+
backdrop-filter: blur(25px);
|
| 115 |
+
-webkit-backdrop-filter: blur(25px);
|
| 116 |
+
border: 1px solid var(--glass-border);
|
| 117 |
+
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
.input-pill:focus-within {
|
| 121 |
+
border-color: rgba(59, 91, 255, 0.4);
|
| 122 |
+
background: rgba(255, 255, 255, 0.06);
|
| 123 |
+
box-shadow: 0 0 40px rgba(59, 91, 255, 0.08);
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
.logo-glow {
|
| 127 |
+
filter: drop-shadow(0 0 15px rgba(39, 212, 234, 0.4));
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
.send-btn {
|
| 131 |
+
background: linear-gradient(135deg, var(--blue), var(--cyan));
|
| 132 |
+
transition: all 0.3s ease;
|
| 133 |
+
}
|
| 134 |
+
.send-btn:hover:not(:disabled) { transform: scale(1.05); filter: brightness(1.1); }
|
| 135 |
+
.send-btn:active:not(:disabled) { transform: scale(0.95); }
|
| 136 |
+
|
| 137 |
+
.settings-panel {
|
| 138 |
+
background: rgba(10, 12, 16, 0.95);
|
| 139 |
+
backdrop-filter: blur(30px);
|
| 140 |
+
border-left: 1px solid var(--glass-border);
|
| 141 |
+
transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
.control-slider {
|
| 145 |
+
-webkit-appearance: none;
|
| 146 |
+
width: 100%;
|
| 147 |
+
height: 4px;
|
| 148 |
+
background: rgba(255, 255, 255, 0.1);
|
| 149 |
+
border-radius: 2px;
|
| 150 |
+
outline: none;
|
| 151 |
+
}
|
| 152 |
+
.control-slider::-webkit-slider-thumb {
|
| 153 |
+
-webkit-appearance: none;
|
| 154 |
+
width: 12px; height: 12px;
|
| 155 |
+
background: var(--blue);
|
| 156 |
+
border-radius: 50%;
|
| 157 |
+
cursor: pointer;
|
| 158 |
+
transition: scale 0.2s;
|
| 159 |
+
}
|
| 160 |
+
.control-slider::-webkit-slider-thumb:hover { scale: 1.2; }
|
| 161 |
+
|
| 162 |
+
.toggle-switch {
|
| 163 |
+
width: 36px; height: 20px;
|
| 164 |
+
background: rgba(255, 255, 255, 0.1);
|
| 165 |
+
border-radius: 10px;
|
| 166 |
+
position: relative;
|
| 167 |
+
cursor: pointer;
|
| 168 |
+
transition: background 0.3s;
|
| 169 |
+
}
|
| 170 |
+
.toggle-switch.active { background: var(--blue); }
|
| 171 |
+
.toggle-switch::after {
|
| 172 |
+
content: '';
|
| 173 |
+
position: absolute;
|
| 174 |
+
top: 2px; left: 2px;
|
| 175 |
+
width: 16px; height: 16px;
|
| 176 |
+
background: white;
|
| 177 |
+
border-radius: 50%;
|
| 178 |
+
transition: transform 0.3s;
|
| 179 |
+
}
|
| 180 |
+
.toggle-switch.active::after { transform: translateX(16px); }
|
| 181 |
+
|
| 182 |
+
.media-preview-item {
|
| 183 |
+
position: relative;
|
| 184 |
+
animation: scaleIn 0.3s ease-out;
|
| 185 |
+
}
|
| 186 |
+
@keyframes scaleIn { from { scale: 0.8; opacity: 0; } to { scale: 1; opacity: 1; } }
|
| 187 |
+
|
| 188 |
+
.shimmer {
|
| 189 |
+
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.05), transparent);
|
| 190 |
+
background-size: 200% 100%;
|
| 191 |
+
animation: shimmer 2s infinite;
|
| 192 |
+
}
|
| 193 |
+
@keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
|
| 194 |
+
</style>
|
| 195 |
+
</head>
|
| 196 |
+
<body>
|
| 197 |
+
|
| 198 |
+
<!-- Header -->
|
| 199 |
+
<header class="h-20 flex items-center justify-between px-6 md:px-12 shrink-0 z-50 border-b border-white/5">
|
| 200 |
+
<div class="flex items-center gap-4">
|
| 201 |
+
<div class="relative">
|
| 202 |
+
<img src="https://cdn-avatars.huggingface.co/v1/production/uploads/1670387859384-633fe7784b362488336bbfad.png"
|
| 203 |
+
alt="OpenBMB" class="w-10 h-10 logo-glow">
|
| 204 |
+
<div class="absolute -bottom-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-[var(--bg)]"></div>
|
| 205 |
+
</div>
|
| 206 |
+
<div>
|
| 207 |
+
<h1 class="text-xl font-bold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white to-white/60">MiniCPM-V</h1>
|
| 208 |
+
<p class="text-[10px] text-muted uppercase tracking-[0.2em] font-bold opacity-50">By OpenBMB</p>
|
| 209 |
+
</div>
|
| 210 |
+
</div>
|
| 211 |
+
<div class="flex items-center gap-6">
|
| 212 |
+
<div class="hidden md:flex items-center gap-2 text-[10px] font-bold text-muted uppercase tracking-widest bg-white/5 px-3 py-1.5 rounded-full border border-white/5">
|
| 213 |
+
<span class="w-1.5 h-1.5 rounded-full bg-[#27D4EA] animate-pulse"></span>
|
| 214 |
+
v4.6 Intelligence Engine
|
| 215 |
+
</div>
|
| 216 |
+
<button id="toggle-settings" class="p-2.5 rounded-xl hover:bg-white/5 text-white/40 hover:text-white transition-all relative">
|
| 217 |
+
<i data-lucide="sliders-horizontal" class="w-5 h-5"></i>
|
| 218 |
+
</button>
|
| 219 |
+
</div>
|
| 220 |
+
</header>
|
| 221 |
+
|
| 222 |
+
<!-- Settings Panel (Side) -->
|
| 223 |
+
<div id="settings-panel" class="fixed top-0 right-0 h-full w-80 z-[100] translate-x-full settings-panel p-8 flex flex-col gap-8 shadow-[-20px_0_50px_rgba(0,0,0,0.5)]">
|
| 224 |
+
<div class="flex items-center justify-between">
|
| 225 |
+
<h2 class="text-lg font-bold">Engine Settings</h2>
|
| 226 |
+
<button id="close-settings" class="text-white/40 hover:text-white"><i data-lucide="x" class="w-5 h-5"></i></button>
|
| 227 |
+
</div>
|
| 228 |
+
|
| 229 |
+
<div class="space-y-6">
|
| 230 |
+
<div class="flex items-center justify-between">
|
| 231 |
+
<span class="text-sm font-medium text-white/70">Thinking Mode</span>
|
| 232 |
+
<div id="thinking-toggle" class="toggle-switch active"></div>
|
| 233 |
+
</div>
|
| 234 |
+
<div class="flex items-center justify-between">
|
| 235 |
+
<span class="text-sm font-medium text-white/70">Streaming</span>
|
| 236 |
+
<div id="streaming-toggle" class="toggle-switch active"></div>
|
| 237 |
+
</div>
|
| 238 |
+
|
| 239 |
+
<div class="space-y-3">
|
| 240 |
+
<span class="text-xs font-bold text-white/40 uppercase tracking-widest">Generation Mode</span>
|
| 241 |
+
<div class="flex gap-2 p-1 bg-white/5 rounded-xl border border-white/10">
|
| 242 |
+
<button id="mode-sampling" class="flex-1 py-2 text-xs font-bold rounded-lg bg-white/10 text-white transition-all">Sampling</button>
|
| 243 |
+
<button id="mode-beam" class="flex-1 py-2 text-xs font-bold rounded-lg text-white/40 hover:text-white transition-all">Beam Search</button>
|
| 244 |
+
</div>
|
| 245 |
+
</div>
|
| 246 |
+
|
| 247 |
+
<div class="space-y-3">
|
| 248 |
+
<div class="flex justify-between text-xs font-bold text-white/40 uppercase tracking-widest">
|
| 249 |
+
<span>Max Tokens</span>
|
| 250 |
+
<span id="tokens-val">2048</span>
|
| 251 |
+
</div>
|
| 252 |
+
<input type="range" id="tokens-slider" min="64" max="16384" step="64" value="2048" class="control-slider">
|
| 253 |
+
</div>
|
| 254 |
+
<div class="space-y-3">
|
| 255 |
+
<div class="flex justify-between text-xs font-bold text-white/40 uppercase tracking-widest">
|
| 256 |
+
<span>Temperature</span>
|
| 257 |
+
<span id="temp-val">0.7</span>
|
| 258 |
+
</div>
|
| 259 |
+
<input type="range" id="temp-slider" min="0" max="2" step="0.01" value="0.7" class="control-slider">
|
| 260 |
+
</div>
|
| 261 |
+
<div class="space-y-3">
|
| 262 |
+
<div class="flex justify-between text-xs font-bold text-white/40 uppercase tracking-widest">
|
| 263 |
+
<span>Top-P</span>
|
| 264 |
+
<span id="p-val">0.8</span>
|
| 265 |
+
</div>
|
| 266 |
+
<input type="range" id="p-slider" min="0" max="1" step="0.05" value="0.8" class="control-slider">
|
| 267 |
+
</div>
|
| 268 |
+
<div class="space-y-3">
|
| 269 |
+
<div class="flex justify-between text-xs font-bold text-white/40 uppercase tracking-widest">
|
| 270 |
+
<span>Top-K</span>
|
| 271 |
+
<span id="k-val">100</span>
|
| 272 |
+
</div>
|
| 273 |
+
<input type="range" id="k-slider" min="0" max="200" step="1" value="100" class="control-slider">
|
| 274 |
+
</div>
|
| 275 |
+
<div class="space-y-3">
|
| 276 |
+
<div class="flex justify-between text-xs font-bold text-white/40 uppercase tracking-widest">
|
| 277 |
+
<span>Max Frames</span>
|
| 278 |
+
<span id="frames-val">64</span>
|
| 279 |
+
</div>
|
| 280 |
+
<input type="range" id="frames-slider" min="8" max="256" step="8" value="64" class="control-slider">
|
| 281 |
+
</div>
|
| 282 |
+
|
| 283 |
+
<button id="open-fewshot" class="w-full py-4 rounded-2xl bg-white/5 hover:bg-white/10 border border-white/5 transition-all flex items-center justify-center gap-2 group mb-2">
|
| 284 |
+
<i data-lucide="sparkles" class="w-4 h-4 text-[#27D4EA] group-hover:scale-110 transition-transform"></i>
|
| 285 |
+
<span class="text-sm font-bold">Few-Shot Builder</span>
|
| 286 |
+
</button>
|
| 287 |
+
|
| 288 |
+
<button onclick="clearHistory()" class="w-full py-4 rounded-2xl bg-red-500/10 border border-red-500/20 text-red-500 text-sm font-bold hover:bg-red-500/20 transition-all flex items-center justify-center gap-2">
|
| 289 |
+
<i data-lucide="trash-2" class="w-4 h-4"></i>
|
| 290 |
+
Clear Conversation
|
| 291 |
+
</button>
|
| 292 |
+
</div>
|
| 293 |
+
</div>
|
| 294 |
+
|
| 295 |
+
<!-- Help Modal -->
|
| 296 |
+
<div id="help-modal" class="fixed inset-0 z-[200] flex items-center justify-center bg-black/80 backdrop-blur-sm hidden p-6">
|
| 297 |
+
<div class="max-w-4xl w-full bg-[#0D1117] border border-white/10 rounded-[32px] overflow-hidden shadow-2xl flex flex-col max-h-[90vh]">
|
| 298 |
+
<div class="p-8 border-b border-white/10 flex items-center justify-between">
|
| 299 |
+
<h2 class="text-2xl font-bold">How to use MiniCPM-V 4.6</h2>
|
| 300 |
+
<button id="close-help" class="text-white/40 hover:text-white"><i data-lucide="x" class="w-6 h-6"></i></button>
|
| 301 |
+
</div>
|
| 302 |
+
<div class="p-8 overflow-y-auto space-y-12">
|
| 303 |
+
<div class="grid grid-cols-1 md:grid-cols-3 gap-8">
|
| 304 |
+
<div class="space-y-4">
|
| 305 |
+
<div class="aspect-video bg-white/5 rounded-2xl overflow-hidden border border-white/5">
|
| 306 |
+
<img src="http://thunlp.oss-cn-qingdao.aliyuncs.com/multi_modal/never_delete/m_bear2.gif" class="w-full h-full object-cover">
|
| 307 |
+
</div>
|
| 308 |
+
<h3 class="font-bold text-lg">1. Multi-Image Chat</h3>
|
| 309 |
+
<p class="text-sm text-white/50 leading-relaxed">Upload multiple images at once. Use the "+" button to select files or drag them into the input area.</p>
|
| 310 |
+
</div>
|
| 311 |
+
<div class="space-y-4">
|
| 312 |
+
<div class="aspect-video bg-white/5 rounded-2xl overflow-hidden border border-white/5">
|
| 313 |
+
<img src="http://thunlp.oss-cn-qingdao.aliyuncs.com/multi_modal/never_delete/video2.gif" class="w-full h-full object-cover">
|
| 314 |
+
</div>
|
| 315 |
+
<h3 class="font-bold text-lg">2. Video Intelligence</h3>
|
| 316 |
+
<p class="text-sm text-white/50 leading-relaxed">Upload videos for temporal reasoning. MiniCPM-V will sample frames and describe events over time.</p>
|
| 317 |
+
</div>
|
| 318 |
+
<div class="space-y-4">
|
| 319 |
+
<div class="aspect-video bg-white/5 rounded-2xl overflow-hidden border border-white/5">
|
| 320 |
+
<img src="http://thunlp.oss-cn-qingdao.aliyuncs.com/multi_modal/never_delete/fshot.gif" class="w-full h-full object-cover">
|
| 321 |
+
</div>
|
| 322 |
+
<h3 class="font-bold text-lg">3. Few-Shot Learning</h3>
|
| 323 |
+
<p class="text-sm text-white/50 leading-relaxed">Provide examples to guide the model. Add turns with correct answers to teach the model a specific style.</p>
|
| 324 |
+
</div>
|
| 325 |
+
</div>
|
| 326 |
+
</div>
|
| 327 |
+
</div>
|
| 328 |
+
</div>
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
<!-- Chat Area (Tab 1) -->
|
| 332 |
+
<div id="tab-chat" class="tab-content active flex-col h-full">
|
| 333 |
+
<main id="chat-messages" class="chat-scroll-area px-4 flex-1">
|
| 334 |
+
<div class="max-w-3xl mx-auto space-y-8 pt-24 pb-40" id="chat-container">
|
| 335 |
+
</div>
|
| 336 |
+
</main>
|
| 337 |
+
|
| 338 |
+
<!-- Input Area -->
|
| 339 |
+
<div class="fixed bottom-0 left-0 right-0 p-6 md:p-10 pointer-events-none z-50">
|
| 340 |
+
<div class="max-w-3xl mx-auto pointer-events-auto">
|
| 341 |
+
<!-- Multi-file Preview -->
|
| 342 |
+
<div id="preview-container" class="hidden mb-6 flex flex-wrap gap-3 max-h-40 overflow-y-auto p-2 scrollbar-none">
|
| 343 |
+
<!-- Preview items will be injected here -->
|
| 344 |
+
</div>
|
| 345 |
+
|
| 346 |
+
<!-- Input Bar -->
|
| 347 |
+
<div class="input-pill rounded-[2rem] p-2 flex items-end shadow-2xl overflow-hidden bg-white/5 backdrop-blur-xl border border-white/10">
|
| 348 |
+
<input type="file" id="file-input" class="hidden" accept="image/*,video/*" multiple>
|
| 349 |
+
<button id="upload-trigger" class="w-12 h-12 flex items-center justify-center text-white/50 hover:text-[#27D4EA] transition-colors relative shrink-0 mb-1">
|
| 350 |
+
<i data-lucide="plus" class="w-6 h-6"></i>
|
| 351 |
+
<span id="file-count-badge" class="absolute top-2 right-2 w-4 h-4 bg-indigo-500 text-[10px] text-white rounded-full flex items-center justify-center hidden shadow-lg">0</span>
|
| 352 |
+
</button>
|
| 353 |
+
|
| 354 |
+
<textarea id="user-input" placeholder="Ask MiniCPM-V..." class="flex-1 bg-transparent border-none focus:ring-0 text-white placeholder-white/30 py-4 px-2 resize-none max-h-48 leading-relaxed font-medium" rows="1"></textarea>
|
| 355 |
+
|
| 356 |
+
<div class="flex items-center gap-1 mb-1 pr-2">
|
| 357 |
+
<button onclick="regenerate()" class="w-10 h-10 flex items-center justify-center text-white/30 hover:text-white transition-colors shrink-0" title="Regenerate last response">
|
| 358 |
+
<i data-lucide="refresh-cw" class="w-4 h-4"></i>
|
| 359 |
+
</button>
|
| 360 |
+
<button id="send-btn" class="send-btn w-12 h-12 text-white rounded-full flex items-center justify-center disabled:opacity-20 disabled:grayscale shrink-0">
|
| 361 |
+
<i data-lucide="arrow-up" class="w-5 h-5" id="send-icon"></i>
|
| 362 |
+
<div id="loading-icon" class="hidden"><div class="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div></div>
|
| 363 |
+
</button>
|
| 364 |
+
</div>
|
| 365 |
+
</div>
|
| 366 |
+
</div>
|
| 367 |
+
</div>
|
| 368 |
+
</div>
|
| 369 |
+
|
| 370 |
+
<!-- Few-Shot Area (Tab 2) -->
|
| 371 |
+
<div id="tab-fewshot" class="tab-content flex-col items-center pt-32 px-4 h-full overflow-y-auto">
|
| 372 |
+
<div class="max-w-3xl w-full space-y-8 pb-20">
|
| 373 |
+
<div class="flex items-center justify-between">
|
| 374 |
+
<div class="space-y-2">
|
| 375 |
+
<h2 class="text-2xl font-bold tracking-tight">Few-Shot Builder</h2>
|
| 376 |
+
<p class="text-white/40 text-sm">Add custom examples to guide the model's behavior.</p>
|
| 377 |
+
</div>
|
| 378 |
+
<button id="return-chat" class="px-6 py-2 rounded-full bg-white/5 hover:bg-white/10 border border-white/10 transition-all flex items-center gap-2 text-xs font-bold uppercase tracking-widest">
|
| 379 |
+
<i data-lucide="arrow-left" class="w-4 h-4"></i>
|
| 380 |
+
Back to Chat
|
| 381 |
+
</button>
|
| 382 |
+
</div>
|
| 383 |
+
|
| 384 |
+
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
| 385 |
+
<div class="space-y-4">
|
| 386 |
+
<div class="aspect-video bg-white/5 rounded-3xl border border-white/10 flex items-center justify-center relative overflow-hidden group cursor-pointer" onclick="document.getElementById('fs-file').click()">
|
| 387 |
+
<input type="file" id="fs-file" class="hidden" accept="image/*">
|
| 388 |
+
<img id="fs-preview" class="hidden w-full h-full object-contain">
|
| 389 |
+
<div id="fs-placeholder" class="flex flex-col items-center gap-2 text-white/20">
|
| 390 |
+
<i data-lucide="image" class="w-10 h-10"></i>
|
| 391 |
+
<span class="text-[10px] font-bold uppercase tracking-[0.2em]">Upload Example Image</span>
|
| 392 |
+
</div>
|
| 393 |
+
<div class="absolute inset-0 bg-indigo-500/10 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center font-bold text-[10px] uppercase tracking-widest">Update Image</div>
|
| 394 |
+
</div>
|
| 395 |
+
</div>
|
| 396 |
+
<div class="space-y-4 flex flex-col">
|
| 397 |
+
<textarea id="fs-user" placeholder="User question for this example..." class="flex-1 bg-white/5 border border-white/10 rounded-2xl p-4 text-sm text-white placeholder-white/20 resize-none focus:border-indigo-500/50 focus:ring-0 transition-all"></textarea>
|
| 398 |
+
<textarea id="fs-bot" placeholder="Model's expected answer..." class="flex-1 bg-white/5 border border-white/10 rounded-2xl p-4 text-sm text-white placeholder-white/20 resize-none focus:border-indigo-500/50 focus:ring-0 transition-all"></textarea>
|
| 399 |
+
</div>
|
| 400 |
+
</div>
|
| 401 |
+
|
| 402 |
+
<div class="flex gap-4">
|
| 403 |
+
<button id="fs-add" class="flex-1 py-4 rounded-2xl bg-white/10 hover:bg-white/20 border border-white/10 font-bold text-xs uppercase tracking-widest transition-all">Add to Context</button>
|
| 404 |
+
<button id="fs-gen" class="flex-1 py-4 rounded-2xl bg-indigo-500 hover:bg-indigo-600 font-bold text-xs uppercase tracking-widest transition-all shadow-lg shadow-indigo-500/20">Ask with Context</button>
|
| 405 |
+
</div>
|
| 406 |
+
|
| 407 |
+
<div class="p-6 rounded-3xl bg-indigo-500/5 border border-indigo-500/10 space-y-4">
|
| 408 |
+
<div class="flex items-center gap-2 text-indigo-400">
|
| 409 |
+
<i data-lucide="info" class="w-4 h-4"></i>
|
| 410 |
+
<span class="text-[10px] font-bold uppercase tracking-widest">Few-Shot Pro Tip</span>
|
| 411 |
+
</div>
|
| 412 |
+
<p class="text-xs text-white/40 leading-relaxed italic">"Demonstrations help the model learn complex formatting or specific domain knowledge by example. Upload an image, type a question and the ideal answer, then click 'Add to Context' to teach the model before you start chatting."</p>
|
| 413 |
+
</div>
|
| 414 |
+
</div>
|
| 415 |
+
</div>
|
| 416 |
+
|
| 417 |
+
<script type="module">
|
| 418 |
+
import { Client, handle_file } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
|
| 419 |
+
|
| 420 |
+
lucide.createIcons();
|
| 421 |
+
|
| 422 |
+
// DOM Elements
|
| 423 |
+
const chatContainer = document.getElementById('chat-container');
|
| 424 |
+
const chatScrollArea = document.getElementById('chat-messages');
|
| 425 |
+
const userInput = document.getElementById('user-input');
|
| 426 |
+
const sendBtn = document.getElementById('send-btn');
|
| 427 |
+
const fileInput = document.getElementById('file-input');
|
| 428 |
+
const uploadTrigger = document.getElementById('upload-trigger');
|
| 429 |
+
const previewContainer = document.getElementById('preview-container');
|
| 430 |
+
const fileCountBadge = document.getElementById('file-count-badge');
|
| 431 |
+
const sendIcon = document.getElementById('send-icon');
|
| 432 |
+
const loadingIcon = document.getElementById('loading-icon');
|
| 433 |
+
|
| 434 |
+
const settingsPanel = document.getElementById('settings-panel');
|
| 435 |
+
const toggleSettings = document.getElementById('toggle-settings');
|
| 436 |
+
const closeSettings = document.getElementById('close-settings');
|
| 437 |
+
|
| 438 |
+
const thinkingToggle = document.getElementById('thinking-toggle');
|
| 439 |
+
const streamingToggle = document.getElementById('streaming-toggle');
|
| 440 |
+
const tempSlider = document.getElementById('temp-slider');
|
| 441 |
+
const tokensSlider = document.getElementById('tokens-slider');
|
| 442 |
+
const tokensVal = document.getElementById('tokens-val');
|
| 443 |
+
const pSlider = document.getElementById('p-slider');
|
| 444 |
+
const pVal = document.getElementById('p-val');
|
| 445 |
+
const kSlider = document.getElementById('k-slider');
|
| 446 |
+
const kVal = document.getElementById('k-val');
|
| 447 |
+
const framesSlider = document.getElementById('frames-slider');
|
| 448 |
+
const framesVal = document.getElementById('frames-val');
|
| 449 |
+
const modeSampling = document.getElementById('mode-sampling');
|
| 450 |
+
const modeBeam = document.getElementById('mode-beam');
|
| 451 |
+
const helpModal = document.getElementById('help-modal');
|
| 452 |
+
const closeHelp = document.getElementById('close-help');
|
| 453 |
+
|
| 454 |
+
let client = null;
|
| 455 |
+
let selectedFiles = [];
|
| 456 |
+
let isSettingsOpen = false;
|
| 457 |
+
let generationMode = 'Sampling';
|
| 458 |
+
|
| 459 |
+
modeSampling.onclick = () => {
|
| 460 |
+
generationMode = 'Sampling';
|
| 461 |
+
modeSampling.classList.add('bg-white/10');
|
| 462 |
+
modeSampling.classList.remove('text-white/40');
|
| 463 |
+
modeBeam.classList.remove('bg-white/10');
|
| 464 |
+
modeBeam.classList.add('text-white/40');
|
| 465 |
+
};
|
| 466 |
+
|
| 467 |
+
modeBeam.onclick = () => {
|
| 468 |
+
generationMode = 'Beam Search';
|
| 469 |
+
modeBeam.classList.add('bg-white/10');
|
| 470 |
+
modeBeam.classList.remove('text-white/40');
|
| 471 |
+
modeSampling.classList.remove('bg-white/10');
|
| 472 |
+
modeSampling.classList.add('text-white/40');
|
| 473 |
+
// Disable streaming toggle for beam search parity
|
| 474 |
+
if (streamingToggle.classList.contains('active')) {
|
| 475 |
+
streamingToggle.click();
|
| 476 |
+
}
|
| 477 |
+
};
|
| 478 |
+
|
| 479 |
+
// Help Modal Logic
|
| 480 |
+
window.openHelp = () => helpModal.classList.remove('hidden');
|
| 481 |
+
closeHelp.onclick = () => helpModal.classList.add('hidden');
|
| 482 |
+
|
| 483 |
+
tempSlider.oninput = () => tempVal.textContent = tempSlider.value;
|
| 484 |
+
tokensSlider.oninput = () => tokensVal.textContent = tokensSlider.value;
|
| 485 |
+
pSlider.oninput = () => pVal.textContent = pSlider.value;
|
| 486 |
+
kSlider.oninput = () => kVal.textContent = kSlider.value;
|
| 487 |
+
framesSlider.oninput = () => framesVal.textContent = framesSlider.value;
|
| 488 |
+
// Tab Switching Logic
|
| 489 |
+
const tabChat = document.getElementById('tab-chat');
|
| 490 |
+
const tabFewshot = document.getElementById('tab-fewshot');
|
| 491 |
+
|
| 492 |
+
function switchTab(target) {
|
| 493 |
+
if (target === 'chat') {
|
| 494 |
+
tabChat.classList.add('active');
|
| 495 |
+
tabFewshot.classList.remove('active');
|
| 496 |
+
} else {
|
| 497 |
+
tabFewshot.classList.add('active');
|
| 498 |
+
tabChat.classList.remove('active');
|
| 499 |
+
}
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
const openFewShot = document.getElementById('open-fewshot');
|
| 503 |
+
const returnChat = document.getElementById('return-chat');
|
| 504 |
+
|
| 505 |
+
openFewShot.onclick = () => {
|
| 506 |
+
toggleSettingsSidebar(false);
|
| 507 |
+
switchTab('fewshot');
|
| 508 |
+
};
|
| 509 |
+
returnChat.onclick = () => switchTab('chat');
|
| 510 |
+
|
| 511 |
+
// Few-Shot Builder
|
| 512 |
+
const fsFile = document.getElementById('fs-file');
|
| 513 |
+
const fsPreview = document.getElementById('fs-preview');
|
| 514 |
+
const fsPlaceholder = document.getElementById('fs-placeholder');
|
| 515 |
+
const fsUser = document.getElementById('fs-user');
|
| 516 |
+
const fsBot = document.getElementById('fs-bot');
|
| 517 |
+
const fsAddBtn = document.getElementById('fs-add');
|
| 518 |
+
const fsGenBtn = document.getElementById('fs-gen');
|
| 519 |
+
|
| 520 |
+
let fsSelectedFile = null;
|
| 521 |
+
|
| 522 |
+
fsFile.onchange = (e) => {
|
| 523 |
+
const file = e.target.files[0];
|
| 524 |
+
if (file) {
|
| 525 |
+
fsSelectedFile = file;
|
| 526 |
+
const reader = new FileReader();
|
| 527 |
+
reader.onload = (re) => {
|
| 528 |
+
fsPreview.src = re.target.result;
|
| 529 |
+
fsPreview.classList.remove('hidden');
|
| 530 |
+
fsPlaceholder.classList.add('hidden');
|
| 531 |
+
};
|
| 532 |
+
reader.readAsDataURL(file);
|
| 533 |
+
}
|
| 534 |
+
};
|
| 535 |
+
|
| 536 |
+
fsAddBtn.onclick = () => {
|
| 537 |
+
if (!fsUser.value.trim() && !fsSelectedFile) {
|
| 538 |
+
alert("Please provide at least a question or an image.");
|
| 539 |
+
return;
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
// Add to history as a "completed turn"
|
| 543 |
+
const userText = fsUser.value.trim();
|
| 544 |
+
const botText = fsBot.value.trim();
|
| 545 |
+
|
| 546 |
+
// Parity with reference: add to chatHistory and show in UI
|
| 547 |
+
chatHistory.push([userText || null, botText || null, fsSelectedFile ? [handle_file(fsSelectedFile)] : []]);
|
| 548 |
+
|
| 549 |
+
// Visual feedback
|
| 550 |
+
appendMessage('user', userText || "(Example Image)", fsSelectedFile ? [fsSelectedFile] : []);
|
| 551 |
+
if (botText) appendMessage('bot', botText);
|
| 552 |
+
|
| 553 |
+
// Clear inputs
|
| 554 |
+
fsUser.value = '';
|
| 555 |
+
fsBot.value = '';
|
| 556 |
+
fsSelectedFile = null;
|
| 557 |
+
fsPreview.classList.add('hidden');
|
| 558 |
+
fsPlaceholder.classList.remove('hidden');
|
| 559 |
+
|
| 560 |
+
switchTab('chat');
|
| 561 |
+
};
|
| 562 |
+
|
| 563 |
+
fsGenBtn.onclick = async () => {
|
| 564 |
+
if (!fsUser.value.trim() && !fsSelectedFile) return;
|
| 565 |
+
|
| 566 |
+
// Switch to chat tab and trigger generation with current FS inputs
|
| 567 |
+
const tempUser = fsUser.value;
|
| 568 |
+
const tempFile = fsSelectedFile;
|
| 569 |
+
|
| 570 |
+
switchTab('chat');
|
| 571 |
+
|
| 572 |
+
userInput.value = tempUser;
|
| 573 |
+
if (tempFile) {
|
| 574 |
+
selectedFiles = [tempFile];
|
| 575 |
+
renderPreviews();
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
sendMessage();
|
| 579 |
+
|
| 580 |
+
// Clear FS inputs
|
| 581 |
+
fsUser.value = '';
|
| 582 |
+
fsBot.value = '';
|
| 583 |
+
fsSelectedFile = null;
|
| 584 |
+
fsPreview.classList.add('hidden');
|
| 585 |
+
fsPlaceholder.classList.remove('hidden');
|
| 586 |
+
};
|
| 587 |
+
|
| 588 |
+
let chatHistory = [];
|
| 589 |
+
let currentJob = null;
|
| 590 |
+
|
| 591 |
+
async function init() {
|
| 592 |
+
try {
|
| 593 |
+
client = await Client.connect(window.location.origin);
|
| 594 |
+
} catch (err) { console.error("Gradio Connection Error", err); }
|
| 595 |
+
}
|
| 596 |
+
init();
|
| 597 |
+
|
| 598 |
+
// Settings Logic
|
| 599 |
+
const toggleSettingsSidebar = (open) => {
|
| 600 |
+
isSettingsOpen = open;
|
| 601 |
+
if (open) {
|
| 602 |
+
settingsPanel.classList.remove('translate-x-full');
|
| 603 |
+
settingsPanel.classList.add('translate-x-0');
|
| 604 |
+
} else {
|
| 605 |
+
settingsPanel.classList.add('translate-x-full');
|
| 606 |
+
settingsPanel.classList.remove('translate-x-0');
|
| 607 |
+
}
|
| 608 |
+
};
|
| 609 |
+
|
| 610 |
+
toggleSettings.onclick = (e) => {
|
| 611 |
+
e.stopPropagation();
|
| 612 |
+
toggleSettingsSidebar(true);
|
| 613 |
+
};
|
| 614 |
+
|
| 615 |
+
closeSettings.onclick = (e) => {
|
| 616 |
+
e.stopPropagation();
|
| 617 |
+
toggleSettingsSidebar(false);
|
| 618 |
+
};
|
| 619 |
+
|
| 620 |
+
// Close sidebar when clicking outside
|
| 621 |
+
document.addEventListener('click', (e) => {
|
| 622 |
+
if (isSettingsOpen && !settingsPanel.contains(e.target) && !toggleSettings.contains(e.target)) {
|
| 623 |
+
toggleSettingsSidebar(false);
|
| 624 |
+
}
|
| 625 |
+
});
|
| 626 |
+
|
| 627 |
+
const setupToggle = (el) => {
|
| 628 |
+
el.onclick = () => el.classList.toggle('active');
|
| 629 |
+
};
|
| 630 |
+
setupToggle(thinkingToggle);
|
| 631 |
+
setupToggle(streamingToggle);
|
| 632 |
+
|
| 633 |
+
const setupSlider = (slider, valEl) => {
|
| 634 |
+
slider.oninput = () => valEl.textContent = slider.value;
|
| 635 |
+
};
|
| 636 |
+
setupSlider(tempSlider, document.getElementById('temp-val'));
|
| 637 |
+
setupSlider(tokensSlider, document.getElementById('tokens-val'));
|
| 638 |
+
setupSlider(pSlider, document.getElementById('p-val'));
|
| 639 |
+
|
| 640 |
+
// File Handling
|
| 641 |
+
uploadTrigger.onclick = () => fileInput.click();
|
| 642 |
+
fileInput.onchange = (e) => {
|
| 643 |
+
const files = Array.from(e.target.files);
|
| 644 |
+
selectedFiles = [...selectedFiles, ...files];
|
| 645 |
+
renderPreviews();
|
| 646 |
+
};
|
| 647 |
+
|
| 648 |
+
function renderPreviews() {
|
| 649 |
+
previewContainer.innerHTML = '';
|
| 650 |
+
if (selectedFiles.length > 0) {
|
| 651 |
+
previewContainer.classList.remove('hidden');
|
| 652 |
+
fileCountBadge.classList.remove('hidden');
|
| 653 |
+
fileCountBadge.textContent = selectedFiles.length;
|
| 654 |
+
|
| 655 |
+
selectedFiles.forEach((file, index) => {
|
| 656 |
+
const url = URL.createObjectURL(file);
|
| 657 |
+
const item = document.createElement('div');
|
| 658 |
+
item.className = 'media-preview-item h-24 w-24 rounded-2xl overflow-hidden border border-white/20 shadow-lg';
|
| 659 |
+
|
| 660 |
+
if (file.type.startsWith('image/')) {
|
| 661 |
+
item.innerHTML = `<img src="${url}" class="w-full h-full object-cover">`;
|
| 662 |
+
} else {
|
| 663 |
+
item.innerHTML = `<video src="${url}" class="w-full h-full object-cover" muted></video><div class="absolute inset-0 flex items-center justify-center bg-black/20"><i data-lucide="play" class="w-6 h-6 text-white"></i></div>`;
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
const removeBtn = document.createElement('button');
|
| 667 |
+
removeBtn.className = 'absolute -top-1 -right-1 bg-red-500 text-white rounded-full p-1 shadow-lg scale-75';
|
| 668 |
+
removeBtn.innerHTML = '<i data-lucide="x" class="w-3 h-3"></i>';
|
| 669 |
+
removeBtn.onclick = (e) => {
|
| 670 |
+
e.stopPropagation();
|
| 671 |
+
selectedFiles.splice(index, 1);
|
| 672 |
+
renderPreviews();
|
| 673 |
+
};
|
| 674 |
+
item.appendChild(removeBtn);
|
| 675 |
+
previewContainer.appendChild(item);
|
| 676 |
+
});
|
| 677 |
+
lucide.createIcons();
|
| 678 |
+
} else {
|
| 679 |
+
previewContainer.classList.add('hidden');
|
| 680 |
+
fileCountBadge.classList.add('hidden');
|
| 681 |
+
}
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
// Message Handling
|
| 685 |
+
function appendMessage(role, text = '', files = []) {
|
| 686 |
+
const div = document.createElement('div');
|
| 687 |
+
div.className = `flex gap-4 items-start ${role === 'user' ? 'flex-row-reverse' : ''}`;
|
| 688 |
+
|
| 689 |
+
let mediaHtml = '';
|
| 690 |
+
if (files.length > 0) {
|
| 691 |
+
mediaHtml = '<div class="flex flex-wrap gap-2 mb-4">';
|
| 692 |
+
files.forEach(file => {
|
| 693 |
+
const url = typeof file === 'string' ? file : URL.createObjectURL(file);
|
| 694 |
+
const type = typeof file === 'string' ? (file.match(/\.(mp4|webm|mkv)/i) ? 'video' : 'image') : (file.type.startsWith('video') ? 'video' : 'image');
|
| 695 |
+
|
| 696 |
+
if (type === 'image') {
|
| 697 |
+
mediaHtml += `<img src="${url}" class="h-48 rounded-2xl border border-white/10 shadow-lg object-contain bg-black/20" />`;
|
| 698 |
+
} else {
|
| 699 |
+
mediaHtml += `<video src="${url}" controls class="h-48 rounded-2xl border border-white/10 shadow-lg" />`;
|
| 700 |
+
}
|
| 701 |
+
});
|
| 702 |
+
mediaHtml += '</div>';
|
| 703 |
+
}
|
| 704 |
+
|
| 705 |
+
const bubbleClass = role === 'user' ? 'user-message' : 'bot-message';
|
| 706 |
+
div.innerHTML = `
|
| 707 |
+
<div class="${bubbleClass} p-6 message-bubble shadow-xl">
|
| 708 |
+
${mediaHtml}
|
| 709 |
+
<div class="thinking-container hidden"></div>
|
| 710 |
+
<div class="content-container leading-relaxed text-[15px] whitespace-pre-wrap font-medium">${marked.parse(text)}</div>
|
| 711 |
+
</div>
|
| 712 |
+
`;
|
| 713 |
+
|
| 714 |
+
chatContainer.appendChild(div);
|
| 715 |
+
|
| 716 |
+
const contentContainer = div.querySelector('.content-container');
|
| 717 |
+
if (window.renderMathInElement) {
|
| 718 |
+
renderMathInElement(contentContainer, {
|
| 719 |
+
delimiters: [
|
| 720 |
+
{left: '$$', right: '$$', display: true},
|
| 721 |
+
{left: '$', right: '$', display: false},
|
| 722 |
+
{left: '\\(', right: '\\)', display: false},
|
| 723 |
+
{left: '\\[', right: '\\]', display: true}
|
| 724 |
+
],
|
| 725 |
+
throwOnError: false
|
| 726 |
+
});
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
chatScrollArea.scrollTo({ top: chatScrollArea.scrollHeight, behavior: 'smooth' });
|
| 730 |
+
return div;
|
| 731 |
+
}
|
| 732 |
+
|
| 733 |
+
function updateBotMessage(div, fullText) {
|
| 734 |
+
const thinkingContainer = div.querySelector('.thinking-container');
|
| 735 |
+
const contentContainer = div.querySelector('.content-container');
|
| 736 |
+
|
| 737 |
+
const thinkMatch = fullText.match(/<think>([\s\S]*?)<\/think>/);
|
| 738 |
+
const thinkingText = thinkMatch ? thinkMatch[1].trim() : (fullText.includes('<think>') && !fullText.includes('</think>') ? fullText.split('<think>')[1].trim() : '');
|
| 739 |
+
const actualText = fullText.replace(/<think>[\s\S]*?<\/think>/, '').trim();
|
| 740 |
+
|
| 741 |
+
if (thinkingText) {
|
| 742 |
+
thinkingContainer.classList.remove('hidden');
|
| 743 |
+
thinkingContainer.innerHTML = `<div class="thinking-block">${marked.parse(thinkingText)}</div>`;
|
| 744 |
+
} else {
|
| 745 |
+
thinkingContainer.classList.add('hidden');
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
contentContainer.innerHTML = marked.parse(actualText);
|
| 749 |
+
|
| 750 |
+
// Render Math
|
| 751 |
+
[thinkingContainer, contentContainer].forEach(el => {
|
| 752 |
+
if (window.renderMathInElement) {
|
| 753 |
+
renderMathInElement(el, {
|
| 754 |
+
delimiters: [
|
| 755 |
+
{left: '$$', right: '$$', display: true},
|
| 756 |
+
{left: '$', right: '$', display: false},
|
| 757 |
+
{left: '\\(', right: '\\)', display: false},
|
| 758 |
+
{left: '\\[', right: '\\]', display: true}
|
| 759 |
+
],
|
| 760 |
+
throwOnError: false
|
| 761 |
+
});
|
| 762 |
+
}
|
| 763 |
+
});
|
| 764 |
+
|
| 765 |
+
chatScrollArea.scrollTo({ top: chatScrollArea.scrollHeight, behavior: 'smooth' });
|
| 766 |
+
return actualText;
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
async function sendMessage() {
|
| 770 |
+
const text = userInput.value.trim();
|
| 771 |
+
if (!text && selectedFiles.length === 0) return;
|
| 772 |
+
|
| 773 |
+
const filesToUpload = [...selectedFiles];
|
| 774 |
+
const content = text;
|
| 775 |
+
|
| 776 |
+
userInput.value = '';
|
| 777 |
+
userInput.style.height = 'auto';
|
| 778 |
+
|
| 779 |
+
appendMessage('user', content, filesToUpload);
|
| 780 |
+
selectedFiles = [];
|
| 781 |
+
renderPreviews();
|
| 782 |
+
|
| 783 |
+
sendIcon.classList.add('hidden');
|
| 784 |
+
loadingIcon.classList.remove('hidden');
|
| 785 |
+
sendBtn.innerHTML = '<i data-lucide="square" class="w-5 h-5 fill-white"></i>';
|
| 786 |
+
sendBtn.classList.remove('send-btn');
|
| 787 |
+
sendBtn.classList.add('bg-red-500/20', 'hover:bg-red-500/40', 'border', 'border-red-500/50');
|
| 788 |
+
lucide.createIcons();
|
| 789 |
+
|
| 790 |
+
let isStopped = false;
|
| 791 |
+
sendBtn.onclick = () => {
|
| 792 |
+
if (currentJob) {
|
| 793 |
+
currentJob.cancel();
|
| 794 |
+
isStopped = true;
|
| 795 |
+
resetSendBtn();
|
| 796 |
+
}
|
| 797 |
+
};
|
| 798 |
+
|
| 799 |
+
// Bot response placeholder
|
| 800 |
+
const botDiv = appendMessage('bot', '');
|
| 801 |
+
const contentContainer = botDiv.querySelector('.content-container');
|
| 802 |
+
contentContainer.innerHTML = '<div class="flex gap-1.5 py-2"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div>';
|
| 803 |
+
|
| 804 |
+
try {
|
| 805 |
+
const gradioFiles = filesToUpload.length > 0 ? filesToUpload.map(f => handle_file(f)) : null;
|
| 806 |
+
|
| 807 |
+
currentJob = client.submit("/predict", {
|
| 808 |
+
message: content,
|
| 809 |
+
history: chatHistory,
|
| 810 |
+
files: gradioFiles,
|
| 811 |
+
thinking_mode: thinkingToggle.classList.contains('active'),
|
| 812 |
+
max_new_tokens: parseInt(tokensSlider.value),
|
| 813 |
+
temperature: parseFloat(tempSlider.value),
|
| 814 |
+
top_p: parseFloat(pSlider.value),
|
| 815 |
+
top_k: parseInt(kSlider.value),
|
| 816 |
+
max_frames: parseInt(framesSlider.value),
|
| 817 |
+
generation_mode: generationMode
|
| 818 |
+
});
|
| 819 |
+
|
| 820 |
+
let finalAnswer = "";
|
| 821 |
+
for await (const msg of currentJob) {
|
| 822 |
+
if (isStopped) break;
|
| 823 |
+
if (msg.type === "data" && msg.data) {
|
| 824 |
+
const chunk = msg.data[0];
|
| 825 |
+
finalAnswer = updateBotMessage(botDiv, chunk);
|
| 826 |
+
}
|
| 827 |
+
}
|
| 828 |
+
|
| 829 |
+
if (!isStopped) {
|
| 830 |
+
chatHistory.push([content, finalAnswer]);
|
| 831 |
+
}
|
| 832 |
+
} catch (err) {
|
| 833 |
+
console.error(err);
|
| 834 |
+
if (!isStopped) {
|
| 835 |
+
contentContainer.textContent = "I encountered an error while processing your request. Please try again.";
|
| 836 |
+
}
|
| 837 |
+
} finally {
|
| 838 |
+
resetSendBtn();
|
| 839 |
+
currentJob = null;
|
| 840 |
+
}
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
function resetSendBtn() {
|
| 844 |
+
sendBtn.innerHTML = '<i data-lucide="arrow-up" class="w-5 h-5" id="send-icon"></i>';
|
| 845 |
+
sendBtn.className = 'send-btn w-12 h-12 text-white rounded-full flex items-center justify-center disabled:opacity-20 disabled:grayscale shrink-0 mb-1';
|
| 846 |
+
sendBtn.onclick = sendMessage;
|
| 847 |
+
lucide.createIcons();
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
window.clearHistory = function() {
|
| 851 |
+
chatHistory = [];
|
| 852 |
+
chatContainer.innerHTML = `
|
| 853 |
+
<div class="flex gap-4 items-start">
|
| 854 |
+
<div class="bot-message p-6 message-bubble shadow-2xl">
|
| 855 |
+
<p class="text-white/90 leading-relaxed text-[15px]">
|
| 856 |
+
History cleared. How can I help you today?
|
| 857 |
+
</p>
|
| 858 |
+
</div>
|
| 859 |
+
</div>
|
| 860 |
+
`;
|
| 861 |
+
closeSettings.click();
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
async function regenerate() {
|
| 865 |
+
if (chatHistory.length === 0) return;
|
| 866 |
+
|
| 867 |
+
const lastTurn = chatHistory.pop();
|
| 868 |
+
// Remove last assistant message from UI
|
| 869 |
+
chatContainer.removeChild(chatContainer.lastChild);
|
| 870 |
+
|
| 871 |
+
// Re-send last user message
|
| 872 |
+
userInput.value = lastTurn[0];
|
| 873 |
+
// We need to re-handle files if we want perfect parity, but for now we re-send text
|
| 874 |
+
sendMessage();
|
| 875 |
+
}
|
| 876 |
+
|
| 877 |
+
thinkingToggle.onclick = () => {
|
| 878 |
+
thinkingToggle.classList.toggle('active');
|
| 879 |
+
if (chatHistory.length > 0) {
|
| 880 |
+
if (confirm("Changing Thinking Mode will clear your current conversation history. Proceed?")) {
|
| 881 |
+
window.clearHistory();
|
| 882 |
+
} else {
|
| 883 |
+
thinkingToggle.classList.toggle('active');
|
| 884 |
+
}
|
| 885 |
+
}
|
| 886 |
+
};
|
| 887 |
+
|
| 888 |
+
// Client ID injection (Parity with reference)
|
| 889 |
+
const header = "x-v46-client-id";
|
| 890 |
+
const key = "minicpm_v46_demo_client_id";
|
| 891 |
+
let clientId = localStorage.getItem(key);
|
| 892 |
+
if (!clientId) {
|
| 893 |
+
clientId = "local-" + Math.random().toString(36).slice(2) + Date.now().toString(36);
|
| 894 |
+
localStorage.setItem(key, clientId);
|
| 895 |
+
}
|
| 896 |
+
window.__minicpmV46ClientId = clientId;
|
| 897 |
+
|
| 898 |
+
// Patch fetch to include client ID
|
| 899 |
+
const originalFetch = window.fetch;
|
| 900 |
+
window.fetch = function(input, init) {
|
| 901 |
+
const nextInit = init ? Object.assign({}, init) : {};
|
| 902 |
+
const headers = new Headers(nextInit.headers || (input instanceof Request ? input.headers : undefined));
|
| 903 |
+
headers.set(header, clientId);
|
| 904 |
+
nextInit.headers = headers;
|
| 905 |
+
return originalFetch.call(this, input, nextInit);
|
| 906 |
+
};
|
| 907 |
+
|
| 908 |
+
// Few-Shot Logic (Enhanced for Parity)
|
| 909 |
+
window.addFewShot = function() {
|
| 910 |
+
// In the reference, this is a form. Here we can use a modal or simple prompts.
|
| 911 |
+
// For true parity, let's add a more structured prompt sequence.
|
| 912 |
+
const hasImage = confirm("Include an image in this example?");
|
| 913 |
+
if (hasImage) {
|
| 914 |
+
// In a real web app we'd open a file picker, but here we can just ask the user to upload it normally
|
| 915 |
+
// and then "Mark as Few-Shot".
|
| 916 |
+
// For now, let's keep it simple as a guided prompt.
|
| 917 |
+
alert("Please upload your image normally, then click 'Add Example' in the settings to mark the current turn as few-shot.");
|
| 918 |
+
}
|
| 919 |
+
};
|
| 920 |
+
// Initial Button Wiring
|
| 921 |
+
sendBtn.onclick = sendMessage;
|
| 922 |
+
|
| 923 |
+
userInput.onkeydown = (e) => {
|
| 924 |
+
if (e.key === 'Enter' && !e.shiftKey) {
|
| 925 |
+
e.preventDefault();
|
| 926 |
+
sendMessage();
|
| 927 |
+
}
|
| 928 |
+
};
|
| 929 |
+
|
| 930 |
+
// Auto-resize textarea
|
| 931 |
+
userInput.oninput = () => {
|
| 932 |
+
userInput.style.height = 'auto';
|
| 933 |
+
userInput.style.height = userInput.scrollHeight + 'px';
|
| 934 |
+
};
|
| 935 |
+
|
| 936 |
+
// Make regenerate global for the HTML onclick
|
| 937 |
+
window.regenerate = regenerate;
|
| 938 |
+
</script>
|
| 939 |
+
</body>
|
| 940 |
+
</html>
|
requirements.txt
CHANGED
|
@@ -1,15 +1,12 @@
|
|
|
|
|
| 1 |
torch
|
| 2 |
torchvision
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
gradio==5.50.0
|
| 6 |
-
modelscope_studio==1.6.1
|
| 7 |
-
Pillow>=10.0
|
| 8 |
-
decord>=0.6.0
|
| 9 |
-
huggingface_hub>=1.0
|
| 10 |
-
tokenizers>=0.22.0,<=0.23.0
|
| 11 |
-
regex>=2025.10.22
|
| 12 |
-
mistral_common>=1.11.0
|
| 13 |
-
accelerate>=1.1.0
|
| 14 |
-
av==17.0.1
|
| 15 |
spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers>=4.44.0
|
| 2 |
torch
|
| 3 |
torchvision
|
| 4 |
+
gradio==6.14.0
|
| 5 |
+
fastapi
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
spaces
|
| 7 |
+
pillow
|
| 8 |
+
av
|
| 9 |
+
accelerate
|
| 10 |
+
sentencepiece
|
| 11 |
+
uvicorn>=0.14.0
|
| 12 |
+
websockets>=10.4
|