Text Generation
Transformers
Safetensors
English
Chinese
spark2_5
sparkx2_5
html-generation
web-design
visual-ui
reasoning
sft
conversational
custom_code
Run this model with HF Jobs
Run wesjos/Spark-x2.6-4B-HTML on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/wesjos/Spark-x2.6-4B-HTML. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/wesjos/Spark-x2.6-4B-HTML on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/wesjos/Spark-x2.6-4B-HTML. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/wesjos/Spark-x2.6-4B-HTML. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use wesjos/Spark-x2.6-4B-HTML with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use wesjos/Spark-x2.6-4B-HTML with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="wesjos/Spark-x2.6-4B-HTML", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("wesjos/Spark-x2.6-4B-HTML", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use wesjos/Spark-x2.6-4B-HTML with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "wesjos/Spark-x2.6-4B-HTML" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "wesjos/Spark-x2.6-4B-HTML", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/wesjos/Spark-x2.6-4B-HTML
- SGLang
How to use wesjos/Spark-x2.6-4B-HTML with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "wesjos/Spark-x2.6-4B-HTML" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "wesjos/Spark-x2.6-4B-HTML", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "wesjos/Spark-x2.6-4B-HTML" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "wesjos/Spark-x2.6-4B-HTML", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use wesjos/Spark-x2.6-4B-HTML with Docker Model Runner:
docker model run hf.co/wesjos/Spark-x2.6-4B-HTML
update: wesjos/Spark-x2.6-4B-HTML
Browse filesFiles changed (19)
- .gitattributes+24-9
- chat_template.jinjaAdded+123
- config.jsonAdded+83
- configuration.jsonAdded+1
- configuration_spark.pyAdded+118
- generation_config.jsonAdded+15
- merges.txtAdded
- model.safetensorsAdded+3
- modeling_spark.pyAdded+483
- special_tokens_map.jsonAdded+6
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+14
- vocab.jsonAdded
- webui/config.jsonAdded+22
- webui/requirements.txtAdded+4
- webui/run_webui.shAdded+58
- webui/server.pyAdded+442
- webui/static/index.htmlAdded+1613
- webui/static/theme.cssAdded+593
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bin.* filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zstandard filter=lfs diff=lfs merge=lfs -text*.tfevents* filter=lfs diff=lfs merge=lfs -text*.db* filter=lfs diff=lfs merge=lfs -text*.ark* filter=lfs diff=lfs merge=lfs -text**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.gguf* filter=lfs diff=lfs merge=lfs -text*.ggml filter=lfs diff=lfs merge=lfs -text*.llamafile* filter=lfs diff=lfs merge=lfs -text*.pt2 filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text"/tokenizer.json" filter=lfs diff=lfs merge=lfs -text"/merges.txt" filter=lfs diff=lfs merge=lfs -text"/vocab.json" filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- set enable_thinking = enable_thinking | default(true) %}{%- set reasoning_instructions = '' %}{%- if enable_thinking is true %} {%- set raw_effort = reasoning_effort|default('high') %} {%- if raw_effort in ('low', 'none', 'off') %} {%- set resolved_reasoning_effort = 'low' %} {%- else %} {%- set resolved_reasoning_effort = 'high' %} {%- endif %} {%- if resolved_reasoning_effort == 'high' %} {%- set reasoning_instructions = '\n`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low` and `high`.\nNow the system is invoked with `thinking_effort=high`.' %} {%- elif resolved_reasoning_effort == 'low' %} {%- set reasoning_instructions = '\n`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low` and `high`.\nNow the system is invoked with `thinking_effort=low`.' %} {%- endif %}{%- endif %}
{#- Render a string or a list of text blocks. -#}{%- macro render_content(content, context_name) %} {%- if content is string %} {{- content }} {%- elif content is none or content is undefined %} {{- '' }} {%- elif content is iterable and content is not mapping %} {%- for block in content %} {%- if block.type == 'text' %} {{- block.text }} {%- else %} {{- raise_exception('Unsupported ' ~ context_name ~ ' content block type: ' ~ (block.type | string)) }} {%- endif %} {%- endfor %} {%- else %} {{- raise_exception(context_name ~ ' content must be a string or a list of text blocks') }} {%- endif %}{%- endmacro %}
{#- Default system prompt -#}{%- set default_system = "You are Mario-html. You are a helpful assistant who generates nice visual content." + reasoning_instructions %}
{#- The first message-level system is placed in the initial system block. -#}{%- set ns = namespace(initial_system='') %}{%- if messages[0].role == "system" %} {%- set ns.initial_system = render_content(messages[0].content, 'system') %}{%- endif %}
{#- System block -#}{{- '<|start▁of▁sentence|><|System|>' + '\n' + default_system }}{%- if tools %} {{- '\n\n' + '## Tools' + '\n' + 'You have access to the following functions:' + '\n' + '<tools>' }} {%- for tool in tools %} {{- '\n' + (tool.function | tojson(separators=(',', ':'))) }} {%- endfor %} {{- '\n' + '</tools>' }}{%- endif %}{%- if ns.initial_system %} {{- '\n\n' + ns.initial_system }}{%- endif %}{{- '<|end▁of▁sentence|>'}}
{#- Conversation turns -#}{%- for message in messages %} {%- if message.role == "system" %} {#- The first system message was consumed by the initial block. -#} {%- if not loop.first %} {{- '<|start▁of▁sentence|><|System|>\n' + render_content(message.content, 'system') + '<|end▁of▁sentence|>' }} {%- endif %} {%- elif message.role == "user" %} {{- '<|start▁of▁sentence|><|User|>' + render_content(message.content, 'user') + '<|end▁of▁sentence|>' }} {%- elif message.role == "assistant" %} {%- set assistant_content = render_content(message.content, 'assistant') %} {%- if message.reasoning_content is defined and message.reasoning_content %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- set reasoning_content = '' %} {%- endif %} {{- '<|start▁of▁sentence|><|Bot|>'}} {%- if reasoning_content %} {{- '<think>' + reasoning_content + '</think>'}} {%- else %} {{- '</think>' }} {%- endif %} {%- if assistant_content %} {{- assistant_content }} {%- endif %} {%- if message.tool_calls is defined and message.tool_calls is not none %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function.arguments is not mapping %} {{- raise_exception('tool_call.function.arguments must be a dictionary; normalize JSON strings before apply_chat_template') }} {%- endif %} {%- set args = tool_call.function.arguments %} {{- '<tool_call>' + tool_call.function.name }} {%- for k, v in args.items() %} {{- '<arg_key>' ~ k ~ '</arg_key><arg_value>' ~ (v if v is string else v | tojson(separators=(', ', ': '))) ~ '</arg_value>' }} {%- endfor %} {{- '</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|end▁of▁sentence|>' }} {%- elif message.role == "tool" %} {%- if loop.previtem is undefined or loop.previtem.role != "tool" %} {{- '<���start▁of▁sentence|><|Tool|>' }} {%- endif %} {{- '<tool_response>' ~ message.content ~ '</tool_response>' }} {%- if loop.nextitem is undefined or loop.nextitem.role != "tool" %} {{- '<|end▁of▁sentence|>' }} {%- endif %} {%- else %} {{- raise_exception('Unsupported message role: ' ~ message.role) }} {%- endif %}{%- endfor %}
{#- Generation prompt -#}{%- if add_generation_prompt %} {{- '<|start▁of▁sentence|><|Bot|>' }} {%- if enable_thinking is defined and enable_thinking %} {{- '<think>' }} {%- endif %} {%- if enable_thinking is defined and not enable_thinking %} {{- '</think>' }} {%- endif %}{%- endif %}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283{ "architectures": [ "Spark2_5ForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_spark.Spark2_5Config", "AutoModel": "modeling_spark.Spark2_5Model", "AutoModelForCausalLM": "modeling_spark.Spark2_5ForCausalLM" }, "bos_token_id": 0, "dtype": "bfloat16", "eos_token_id": 1, "gate_attn_act_mode": "sigmoid", "head_dim": 256, "headwise_attn_output_gate": true, "hidden_act": "gelu", "hidden_size": 2560, "initializer_range": 0.01976, "intermediate_size": 10240, "layer_types": [ "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention" ], "max_position_embeddings": 1048576, "mlp_bias": false, "model_type": "spark2_5", "num_attention_heads": 16, "num_hidden_layers": 36, "num_key_value_heads": 4, "pad_token_id": 2, "rms_norm_eps": 1e-06, "rope_parameters": { "full_attention": { "partial_rotary_factor": 0.25, "rope_theta": 5000000 }, "sliding_attention": { "partial_rotary_factor": 1.0, "rope_theta": 10000 } }, "sliding_window": 512, "tie_word_embeddings": true, "transformers_version": "4.57.1", "use_cache": true, "vocab_size": 131072}1{"task":"text-generation"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118# coding=utf-8# Copyright 2026 The XHToken team and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from transformers import PretrainedConfig
class Spark2_5Config(PretrainedConfig): model_type = "spark2_5" keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = { "layers.*.self_attn.q_k_v_proj": "colwise", "layers.*.self_attn.g_proj": "colwise", "layers.*.self_attn.out_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embedding": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, vocab_size=32000, hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=None, hidden_act="gelu", max_position_embeddings=2048, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=None, bos_token_id=1, eos_token_id=2, tie_word_embeddings=False, rope_parameters=None, attention_bias=False, attention_dropout=0.0, mlp_bias=False, head_dim=None, headwise_attn_output_gate=False, gate_attn_act_mode="sigmoid", sliding_window=None, layer_types=None, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads
if num_key_value_heads is None: num_key_value_heads = num_attention_heads if num_attention_heads % num_key_value_heads != 0: raise ValueError( f"num_attention_heads ({num_attention_heads}) must be divisible by num_key_value_heads ({num_key_value_heads})" ) self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.mlp_bias = mlp_bias self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads self.headwise_attn_output_gate = headwise_attn_output_gate self.gate_attn_act_mode = gate_attn_act_mode self.sliding_window = sliding_window self.rope_parameters = rope_parameters
if layer_types is None: layer_types = ["full_attention"] * num_hidden_layers if len(layer_types) != num_hidden_layers: raise ValueError( f"layer_types length ({len(layer_types)}) must match num_hidden_layers ({num_hidden_layers})" ) self.layer_types = layer_types
super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
def get_rope_theta(self, layer_type): params = self.rope_parameters.get(layer_type, {}) return params.get("rope_theta", 10000)
def get_partial_rotary_factor(self, layer_type): params = self.rope_parameters.get(layer_type, {}) return params.get("partial_rotary_factor", 1.0)
__all__ = ["Spark2_5Config"]123456789101112131415{ "bos_token_id": 0, "eos_token_id": 1, "pad_token_id": 2, "max_tokens": 1048576, "temperature": 0.7, "top_p": 0.8, "top_k": 40, "repetition_penalty": 1.05, "presence_penalty": 0.0, "frequency_penalty": 0.0, "do_sample": true, "transformers_version": "4.57.1", "max_new_tokens": 8192}123version https://git-lfs.github.com/spec/v1oid sha256:4eb6e934f1fb51eb6ce6daf1589b4c1bed81d58365abd7fe55f95ce633c7950bsize 8224192576123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483import math
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.generation import GenerationMixinfrom transformers.masking_utils import create_causal_mask, create_sliding_window_causal_maskfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.pytorch_utils import ALL_LAYERNORM_LAYERSfrom transformers.utils import TransformersKwargs, can_return_tuple, logging
from .configuration_spark import Spark2_5Config
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "Spark2_5Config"
def rotate_half(x): x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
def compute_rope_cos_sin(positions, head_dim, rope_theta, partial_rotary_factor=1.0, device="cpu"): rope_head_dim = int(head_dim * partial_rotary_factor) inv_freq = 1.0 / (rope_theta ** (torch.arange(0, rope_head_dim, 2, dtype=torch.int64).to(device="cpu", dtype=torch.float) / rope_head_dim)) inv_freq = inv_freq.to(device) t = positions.to(device=device, dtype=torch.float32) freqs = torch.outer(t, inv_freq) freqs = torch.cat([freqs, freqs], dim=-1) cos = freqs.cos() sin = freqs.sin() return cos, sin
def apply_rotary_pos_emb(x, cos, sin): rope_head_dim = cos.shape[-1] x_f32 = x.float() if x_f32.shape[-1] > rope_head_dim: x_rot = x_f32[..., :rope_head_dim] x_pass = x_f32[..., rope_head_dim:] c = cos.unsqueeze(0).unsqueeze(0) s = sin.unsqueeze(0).unsqueeze(0) x_rot = x_rot * c + rotate_half(x_rot) * s result = torch.cat([x_rot, x_pass], dim=-1) else: c = cos.unsqueeze(0).unsqueeze(0) s = sin.unsqueeze(0).unsqueeze(0) result = x_f32 * c + rotate_half(x_f32) * s return result.to(x.dtype)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None = None, scaling: float | None = None, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs],): key = repeat_kv(key, module.num_key_value_groups) value = repeat_kv(value, module.num_key_value_groups)
if scaling is None: scaling = 1.0 / math.sqrt(query.shape[-1])
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + causal_mask
attn_weights = attn_weights - attn_weights.max(dim=-1, keepdim=True).values attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) return attn_output, attn_weights
class Spark2_5RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return (self.weight.float() * hidden_states).to(input_dtype)
def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
ALL_LAYERNORM_LAYERS.append(Spark2_5RMSNorm)
class Spark2_5MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
if config.hidden_act != "gelu": raise ValueError(f"只支持hidden_act='gelu',当前传入:{config.hidden_act}") self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class Spark2_5Attention(nn.Module): def __init__(self, config: Spark2_5Config, layer_idx: int | None = None): super().__init__() self.config = config self.layer_idx = layer_idx self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = config.head_dim self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.scaling = 1.0 / math.sqrt(self.head_dim) self.headwise_attn_output_gate = config.headwise_attn_output_gate self.gate_attn_act_mode = config.gate_attn_act_mode self.q_dim = self.num_heads * self.head_dim self.kv_dim = self.num_key_value_heads * self.head_dim
qkv_out_dim = self.q_dim + 2 * self.kv_dim self.q_k_v_proj = nn.Linear(self.hidden_size, qkv_out_dim, bias=config.attention_bias) self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=config.attention_bias) if self.headwise_attn_output_gate else None self.out_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias) self.sliding_window = None
def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, past_key_values: Cache | None = None, cache_position: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] bsz, seq_len = input_shape
qkv = self.q_k_v_proj(hidden_states) q = qkv[..., :self.q_dim] k = qkv[..., self.q_dim:self.q_dim + self.kv_dim] v = qkv[..., self.q_dim + self.kv_dim:] gate_score = self.g_proj(hidden_states) if self.g_proj is not None else None
q = q.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2) k = k.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) v = v.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) if gate_score is not None: gate_score = gate_score.view(bsz, seq_len, self.num_heads, 1).transpose(1, 2)
cos, sin = position_embeddings q = apply_rotary_pos_emb(q, cos, sin) k = apply_rotary_pos_emb(k, cos, sin)
if past_key_values is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs)
attn_output, attn_weights = eager_attention_forward( self, q, k, v, attention_mask=attention_mask, scaling=self.scaling, dropout=self.attention_dropout if self.training else 0.0, )
if gate_score is not None: if self.gate_attn_act_mode == "sigmoid": gate = torch.sigmoid(gate_score.float()) elif self.gate_attn_act_mode == "silu": gate = F.silu(gate_score.float()) else: raise ValueError(f"Unsupported gate_attn_act_mode: {self.gate_attn_act_mode}") gate = gate.to(attn_output.dtype) attn_output = attn_output * gate
attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, seq_len, -1) attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
class Spark2_5DecoderLayer(nn.Module): def __init__(self, config: Spark2_5Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size
self.self_attn = Spark2_5Attention(config=config, layer_idx=layer_idx) self.mlp = Spark2_5MLP(config) self.input_layernorm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.layer_type = config.layer_types[layer_idx] if layer_idx < len(config.layer_types) else "full_attention" if self.layer_type == "sliding_attention" and config.sliding_window is not None: self.self_attn.sliding_window = config.sliding_window else: self.self_attn.sliding_window = None self.self_attn.partial_rotary_factor = config.get_partial_rotary_factor(self.layer_type) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None = None, past_key_values: Cache | None = None, cache_position: torch.LongTensor | None = None, position_ids: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs] ) -> torch.Tensor:
residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states = hidden_states.to(self.mlp.gate_proj.weight.dtype)
hidden_states, _ = self.self_attn( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, past_key_values=past_key_values, cache_position=cache_position, position_ids=position_ids, ) hidden_states = residual + hidden_states
residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = hidden_states.to(self.mlp.gate_proj.weight.dtype)
hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
return hidden_states
class Spark2_5PreTrainedModel(PreTrainedModel): config_class = Spark2_5Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Spark2_5DecoderLayer"] # noqa: RUF012 _skip_keys_device_placement = ["past_key_values"] # noqa: RUF012
def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
class Spark2_5Model(Spark2_5PreTrainedModel): def __init__(self, config: Spark2_5Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size
self.embedding = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Spark2_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Spark2_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False self.has_sliding_layers = "sliding_attention" in config.layer_types
self.post_init()
def get_input_embeddings(self): return self.embedding
def set_input_embeddings(self, value): self.embedding = value def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, cache_position: torch.LongTensor | None = None, token_type_ids: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one" )
if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False
if inputs_embeds is None: inputs_embeds = self.embedding(input_ids)
if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config)
if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device )
if position_ids is None: position_ids = cache_position.unsqueeze(0)
if not isinstance(attention_mask, dict): mask_kwargs = { "config": self.config, "input_embeds": inputs_embeds, "attention_mask": attention_mask, "cache_position": cache_position, "past_key_values": past_key_values, "position_ids": position_ids, } causal_mask_mapping = { "full_attention": create_causal_mask(**mask_kwargs), } if self.has_sliding_layers: causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs) else: causal_mask_mapping = attention_mask
hidden_states = inputs_embeds.float()
device = hidden_states.device dtype = self.embedding.weight.dtype
head_dim = self.config.head_dim rope_cache = {} for lt in set(self.config.layer_types): rope_theta = self.config.get_rope_theta(lt) prf = self.config.get_partial_rotary_factor(lt) cos, sin = compute_rope_cos_sin(cache_position, head_dim, rope_theta, partial_rotary_factor=prf, device=device) rope_cache[lt] = (cos, sin)
for decoder_layer in self.layers: layer_type = decoder_layer.layer_type position_embeddings = rope_cache.get(layer_type, rope_cache.get("full_attention")) layer_attention_mask = causal_mask_mapping.get(layer_type, causal_mask_mapping.get("full_attention"))
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, position_embeddings, layer_attention_mask, ) hidden_states = layer_outputs[0] if isinstance(layer_outputs, tuple) else layer_outputs else: hidden_states = decoder_layer( hidden_states, position_embeddings=position_embeddings, attention_mask=layer_attention_mask, past_key_values=past_key_values, cache_position=cache_position, position_ids=position_ids, )
hidden_states = self.norm(hidden_states) hidden_states = hidden_states.to(dtype)
return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, )
class Spark2_5ForCausalLM(Spark2_5PreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] # noqa: RUF012
def __init__(self, config): super().__init__(config) self.model = Spark2_5Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self): return self.model.embedding
def set_input_embeddings(self, value): self.model.embedding = value
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def set_decoder(self, decoder): self.model = decoder
def get_decoder(self): return self.model
@can_return_tuple def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, cache_position: torch.LongTensor | None = None, logits_to_keep: int = 0, token_type_ids: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, )
hidden_states = outputs.last_hidden_state slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep hidden_states = hidden_states[:, slice_indices, :]
if self.config.tie_word_embeddings: embed_weight = self.model.embedding.weight logits = F.linear(hidden_states, embed_weight) else: logits = self.lm_head(hidden_states)
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
__all__ = ["Spark2_5Config", "Spark2_5ForCausalLM", "Spark2_5Model"]123456{ "bos_token": "<|start▁of▁sentence|>", "eos_token": "<|end▁of▁sentence|>", "unk_token": "<unk>", "pad_token": "<|▁pad▁|>"}1234567891011121314{ "backend": "tokenizers", "bos_token": "<|start▁of▁sentence|>", "clean_up_tokenization_spaces": false, "eos_token": "<|end▁of▁sentence|>", "is_local": true, "legacy": true, "local_files_only": false, "model_max_length": 131072, "pad_token": "<|▁pad▁|>", "sp_model_kwargs": {}, "tokenizer_class": "TokenizersBackend", "unk_token": "<unk>"}12345678910111213141516171819202122{ "backend_mode": "api", "api_url": "http://127.0.0.1:18080", "model_path": "/mnt/sdb/models/Spark-x2.6-4B-HTML/Spark-x2.6-4B-HTML-Q8_0.gguf", "model_alias": "Spark-x2.6-4B-HTML", "context_size": 131072, "gpu_layers": 99, "do_sample": true, "temperature": 0.7, "top_p": 0.8, "top_k": 40, "min_p": 0.05, "presence_penalty": 0.0, "repetition_penalty": 1.05, "max_tokens": 8192, "enable_thinking": true, "theme_preset": "notion", "custom_css": "/* Notion Minimal */\n.html-canvas {\n border-radius: 4px !important;\n border: 1px solid #37352f !important;\n box-shadow: none !important;\n background: #ffffff !important;\n}\n.card {\n border-radius: 4px !important;\n border: 1px solid #e3e2e0 !important;\n box-shadow: none !important;\n}\n.summary-card {\n border-radius: 4px !important;\n border-left-color: #37352f !important;\n}\n.callout {\n border-radius: 4px !important;\n border-left-width: 4px !important;\n}\n.badge {\n border-radius: 3px !important;\n font-weight: 500 !important;\n}", "system_prompt": "You are Mario-html. You are a helpful assistant who generates nice visual content.", "reasoning_effort": "low", "frequency_penalty": 0.0}1234fastapi>=0.100.0uvicorn>=0.22.0httpx>=0.24.0pydantic>=2.0.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#!/usr/bin/env bash# ---------------------------------------------------------------------------# run_webui.sh — WebUI frontend/API for this folder (self-contained)## ./run_webui.sh # config.json decides; env vars override# WEBUI_PORT=8795 ./run_webui.sh## Precedence: explicitly-set env > config.json > built-in defaults.# API_URL / MODEL_ALIAS are NOT defaulted here on purpose — config.json is# the single source of truth so editing it is enough.# ---------------------------------------------------------------------------set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"cd "$SCRIPT_DIR"
LOG="${LOG_FILE:-$SCRIPT_DIR/webui.log}"
export PYTHONUNBUFFERED=1export TMPDIR="${TMPDIR:-/mnt/sdb/tmp}"export HF_HUB_OFFLINE="${HF_HUB_OFFLINE:-1}"export TRANSFORMERS_OFFLINE="${TRANSFORMERS_OFFLINE:-1}"
# ---- interpreter: pick one that actually has fastapi+uvicorn ---------------PY="${WEBUI_PY:-}"if [ -z "$PY" ]; then for cand in "$SCRIPT_DIR/../venv/bin/python" \ /mnt/sdb/data/conda-env/envs/unsloth-vlm/bin/python \ /mnt/sdb/data/conda-env/envs/StructBERT/bin/python \ "$(command -v python3)"; do [ -x "$cand" ] || continue if "$cand" -c 'import fastapi, uvicorn, httpx' 2>/dev/null; then PY="$cand"; break; fi donefiif [ -z "$PY" ]; then echo "ERROR: no interpreter with fastapi/uvicorn found. Set WEBUI_PY=/path/to/python" >&2 echo " or: pip install -r $SCRIPT_DIR/requirements.txt" >&2 exit 1fi
PORT="${WEBUI_PORT:-8798}"
# ---- backend health hint (advisory only, never blocks startup) -------------api_from_config="$(/mnt/sdb/data/conda-env/envs/unsloth-vlm/bin/python - "$SCRIPT_DIR/config.json" <<'EOF' 2>/dev/null || trueimport json, systry: print(json.load(open(sys.argv[1])).get("api_url", ""))except Exception: passEOF)"api_check="${API_URL:-${api_from_config:-http://127.0.0.1:18085}}"if ! curl -sSf -m 2 "$api_check/health" >/dev/null 2>&1; then echo "WARN: backend $api_check not responding — start the backend first (./start.sh)" >&2fi
echo "[$(date '+%F %T')] WebUI http://0.0.0.0:$PORT -> backend $api_check"exec "$PY" server.py --port "$PORT" > "$LOG" 2>&1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Minimalist Qwen-HTML WebUI Server (:8791)- English-only minimal interface- Backend options: Llama.cpp API Server or Direct Model Path- Real-time streaming for Reasoning Trace (<think>) & Rendered HTML (<div class="ai-view">)"""
import os, reimport jsonimport timeimport argparseimport subprocessimport threadingfrom pathlib import Pathfrom typing import List, Dict, Optional, Union, Anyimport httpximport uvicornfrom fastapi import FastAPI, Requestfrom fastapi.responses import FileResponse, JSONResponse, StreamingResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel
# --- Self-contained layout: everything resolved relative to this file, env-overridable ---BASE_DIR = Path(__file__).resolve().parentSTATIC_DIR = str(BASE_DIR / "static")CONFIG_FILE = str(BASE_DIR / "config.json")HISTORY_FILE = str(BASE_DIR / "chat_history.jsonl")
PORT = int(os.environ.get("WEBUI_PORT", "8791"))DEFAULT_API_URL = os.environ.get("API_URL", "http://127.0.0.1:18085")DEFAULT_MODEL_PATH = os.environ.get("MODEL_PATH", str(BASE_DIR.parent))DEFAULT_MODEL_ALIAS = os.environ.get("MODEL_ALIAS", "qwen-3.8-27b")
# Direct (llama.cpp GGUF) backend — only used by POST /api/model/loadLLAMA_SERVER_BIN = os.environ.get( "LLAMA_SERVER_BIN", "/mnt/sdb/ubuntu/llama.cpp-clef/build/bin/llama-server")LLAMA_SCOPE = os.environ.get("LLAMA_SCOPE", "llama-server-q8")LLAMA_BACKEND_PORT = int(os.environ.get("LLAMA_BACKEND_PORT", "18085"))
DEFAULT_CONFIG = { "backend_mode": "api", # 'api' = talk to vLLM/OpenAI backend; 'direct' = managed llama.cpp server "api_url": DEFAULT_API_URL, "model_path": DEFAULT_MODEL_PATH, "model_alias": DEFAULT_MODEL_ALIAS, "context_size": 81920, "gpu_layers": 99, "do_sample": True, "temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0, "presence_penalty": 1.5, "repetition_penalty": 1.0, "max_tokens": 8192, "enable_thinking": True, "theme_preset": "default", "custom_css": "", "system_prompt": "",}
config_lock = threading.Lock()
def load_config() -> dict: cfg = dict(DEFAULT_CONFIG) if os.path.exists(CONFIG_FILE): try: with open(CONFIG_FILE, "r", encoding="utf-8") as f: cfg.update(json.load(f)) except Exception: pass # Env (set by run_webui.sh, resolved relative to this folder) wins over a # stale config.json so a copied folder never points at the old model. for key, env in (("api_url", "API_URL"), ("model_path", "MODEL_PATH"), ("model_alias", "MODEL_ALIAS")): if os.environ.get(env): cfg[key] = os.environ[env] return cfg
def save_config(cfg: dict): with config_lock: with open(CONFIG_FILE, "w", encoding="utf-8") as f: json.dump(cfg, f, indent=2, ensure_ascii=False)
current_config = load_config()
history_lock = threading.Lock()
def log_chat(record: dict): with history_lock: with open(HISTORY_FILE, "a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n")
app = FastAPI(title="Qwen-HTML WebUI")app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
@app.get("/")async def root(): return FileResponse(os.path.join(STATIC_DIR, "index.html"))
@app.get("/api/config")async def get_config_endpoint(): return current_config
class UpdateConfigRequest(BaseModel): backend_mode: Optional[str] = None api_url: Optional[str] = None model_path: Optional[str] = None context_size: Optional[int] = None gpu_layers: Optional[int] = None do_sample: Optional[bool] = None temperature: Optional[float] = None top_p: Optional[float] = None top_k: Optional[int] = None min_p: Optional[float] = None presence_penalty: Optional[float] = None repetition_penalty: Optional[float] = None max_tokens: Optional[int] = None enable_thinking: Optional[bool] = None theme_preset: Optional[str] = None custom_css: Optional[str] = None system_prompt: Optional[str] = None
@app.post("/api/config")async def update_config_endpoint(req: UpdateConfigRequest): updates = req.dict(exclude_unset=True) current_config.update(updates) save_config(current_config) return {"status": "ok", "config": current_config}
@app.get("/api/status")async def status_endpoint(): api_url = current_config.get("api_url", DEFAULT_API_URL) is_alive = False model_info = "Unknown" latency_ms = None t0 = time.time() try: async with httpx.AsyncClient(timeout=2.0) as client: resp = await client.get(f"{api_url}/health") if resp.status_code == 200: is_alive = True latency_ms = round((time.time() - t0) * 1000, 1) m_resp = await client.get(f"{api_url}/v1/models") if m_resp.status_code == 200: models = m_resp.json().get("data", []) if models: model_info = models[0].get("id", DEFAULT_MODEL_ALIAS) except Exception: pass
return { "status": "ready" if is_alive else "disconnected", "backend_mode": current_config.get("backend_mode", "api"), "api_url": api_url, "model_path": current_config.get("model_path"), "model_info": model_info, "latency_ms": latency_ms, "enable_thinking": current_config.get("enable_thinking", True) }
class LoadModelRequest(BaseModel): model_path: str context_size: Optional[int] = 65536 gpu_layers: Optional[int] = 99
@app.post("/api/model/load")async def load_model_endpoint(req: LoadModelRequest): model_path = req.model_path.strip()
# 支持三种写法: # 1) 本地路径 /path/to/model.gguf -> -m # 2) HuggingFace 仓库 user/repo[:quant] -> -hf(国内可 export HF_ENDPOINT=https://hf-mirror.com) # 3) 直链 https://.../model.gguf -> -mu if model_path.startswith(("http://", "https://")): source, model_arg = "url", ["-mu", model_path] elif re.fullmatch(r"[\w.-]+/[\w.-]+(:\w+)?", model_path) and not os.path.exists(model_path): source, model_arg = "hf", ["-hf", model_path] elif os.path.exists(model_path): source, model_arg = "local", ["-m", model_path] else: return JSONResponse(status_code=400, content={ "error": f"Not found: {model_path}(既不是本地文件,也不是 user/repo 形式的 HF 仓库名)"}) ctx = req.context_size or DEFAULT_CONFIG["context_size"] ngl = req.gpu_layers if req.gpu_layers is not None else 99
# Restart managed llama-server scope subprocess.run(["systemctl", "--user", "stop", f"{LLAMA_SCOPE}.scope"], check=False) time.sleep(1.5)
start_cmd = [ "systemd-run", "--user", "--scope", f"--unit={LLAMA_SCOPE}", LLAMA_SERVER_BIN, "--host", "0.0.0.0", "--port", str(LLAMA_BACKEND_PORT), *model_arg, "-c", str(ctx), "-ngl", str(ngl), "-fa", "on", "--alias", DEFAULT_MODEL_ALIAS, "-t", "8" ] # Vision projector: sibling of the chosen model, else any well-known sibling dir mmproj_dirs = [os.path.dirname(model_path)] if source == "local" else [] for extra in (current_config.get("mmproj_path"), DEFAULT_MODEL_PATH): if extra and extra not in mmproj_dirs: mmproj_dirs.append(extra if os.path.isdir(extra) else os.path.dirname(extra) or ".") for d in mmproj_dirs: candidate = os.path.join(d, "mmproj-Qwen3.5-4B-BF16.gguf") if os.path.exists(candidate): start_cmd.extend(["--mmproj", candidate]) break
proc = subprocess.Popen(start_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Poll for health check ready = False for _ in range(25): time.sleep(0.5) try: with httpx.Client(timeout=1.0) as client: res = client.get(f"http://127.0.0.1:{LLAMA_BACKEND_PORT}/health") if res.status_code == 200: ready = True break except Exception: pass
if ready: current_config["model_path"] = model_path current_config["context_size"] = ctx current_config["gpu_layers"] = ngl current_config["backend_mode"] = "direct" save_config(current_config) return {"status": "ok", "message": f"Successfully loaded [{source}] {model_path}"} else: return JSONResponse(status_code=500, content={"error": "Failed to start llama-server with the specified model."})
class ChatMessage(BaseModel): role: str content: Union[str, List[Any], Dict[str, Any]]
class ChatStreamRequest(BaseModel): messages: List[ChatMessage] enable_thinking: Optional[bool] = None reasoning_effort: Optional[str] = None do_sample: Optional[bool] = None temperature: Optional[float] = None top_p: Optional[float] = None top_k: Optional[int] = None min_p: Optional[float] = None presence_penalty: Optional[float] = None repetition_penalty: Optional[float] = None max_tokens: Optional[int] = None system_prompt: Optional[str] = None
@app.post("/api/chat/stream")async def chat_stream_endpoint(req: ChatStreamRequest, request: Request): client_ip = request.client.host if request.client else "unknown" t0 = time.time() enable_thinking = req.enable_thinking if req.enable_thinking is not None else current_config.get("enable_thinking", True) do_sample = req.do_sample if req.do_sample is not None else current_config.get("do_sample", True) temp = req.temperature if req.temperature is not None else current_config.get("temperature", 1.0) if not do_sample: temp = 0.0 top_p = req.top_p if req.top_p is not None else current_config.get("top_p", 0.95) top_k = req.top_k if req.top_k is not None else current_config.get("top_k", 20) min_p = req.min_p if req.min_p is not None else current_config.get("min_p", 0.0) pres_penalty = req.presence_penalty if req.presence_penalty is not None else current_config.get("presence_penalty", 1.5) rep_penalty = req.repetition_penalty if req.repetition_penalty is not None else current_config.get("repetition_penalty", 1.0) max_tokens = req.max_tokens if req.max_tokens is not None else current_config.get("max_tokens", 8192) sys_prompt = req.system_prompt if req.system_prompt is not None else current_config.get("system_prompt", "") effort = req.reasoning_effort if req.reasoning_effort is not None else current_config.get("reasoning_effort") if effort in ("low", "medium"): effort = "low" elif effort in ("high", "xhigh"): effort = "high" else: effort = "low" messages_payload = [] if sys_prompt and sys_prompt.strip(): messages_payload.append({"role": "system", "content": sys_prompt.strip()}) for msg in req.messages: messages_payload.append({"role": msg.role, "content": msg.content})
api_url = current_config.get("api_url", DEFAULT_API_URL)
# Resolve the model id: use configured alias, but fall back to whatever # the backend actually serves (aliases drift when the user edits # config.json; a stale name would 404 every chat). model_alias = current_config.get("model_alias") or "" async with httpx.AsyncClient(timeout=3.0) as probe: try: r = await probe.get(f"{api_url}/v1/models") if r.status_code == 200: served = [m.get("id", "") for m in r.json().get("data", [])] if served and model_alias not in served: model_alias = served[0] except Exception: pass if not model_alias: model_alias = "qwen-3.8-27b"
payload = { "model": model_alias, "messages": messages_payload, "temperature": temp, "top_p": top_p, "max_tokens": max_tokens, "stream": True, "stop": ["<|end▁of▁sentence|>", "<|im_end|>", "</div>\n</div>\n</div>\n</div>"], "chat_template_kwargs": {"enable_thinking": enable_thinking, **({"reasoning_effort": effort} if effort else {})}, } if top_k is not None and top_k > 0: payload["top_k"] = top_k if min_p is not None and min_p > 0: payload["min_p"] = min_p if pres_penalty is not None: payload["presence_penalty"] = pres_penalty if rep_penalty is not None and rep_penalty > 0: payload["repetition_penalty"] = rep_penalty
async def event_generator(): thought_chunks = [] content_chunks = [] token_count = 0 in_thinking_mode = False try: async with httpx.AsyncClient(timeout=180.0) as client: async with client.stream( "POST", f"{api_url}/v1/chat/completions", json=payload, headers={"Content-Type": "application/json"} ) as response: if response.status_code != 200: err_text = await response.aread() yield f"data: {json.dumps({'type': 'error', 'error': err_text.decode('utf-8')}, ensure_ascii=False)}\n\n" return
async for line in response.aiter_lines(): if not line or not line.startswith("data: "): continue data_str = line[6:].strip() if data_str == "[DONE]": break try: chunk_json = json.loads(data_str) choice = chunk_json.get("choices", [{}])[0] delta = choice.get("delta", {}) # Reasoning trace reasoning = delta.get("reasoning_content") or delta.get("reasoning") if reasoning: thought_chunks.append(reasoning) token_count += 1 out_data = json.dumps({"type": "thought", "content": reasoning}, ensure_ascii=False) yield f"data: {out_data}\n\n" # Main content (HTML) if "content" in delta and delta["content"]: text = delta["content"] token_count += 1 # Intercept and route raw <think> tags if present in content cur = text while cur: if not in_thinking_mode: if "<think>" in cur: before, cur = cur.split("<think>", 1) if before: content_chunks.append(before) yield f"data: {json.dumps({'type': 'content', 'content': before}, ensure_ascii=False)}\n\n" in_thinking_mode = True else: content_chunks.append(cur) yield f"data: {json.dumps({'type': 'content', 'content': cur}, ensure_ascii=False)}\n\n" break else: if "</think>" in cur: thought_part, cur = cur.split("</think>", 1) if thought_part: thought_chunks.append(thought_part) yield f"data: {json.dumps({'type': 'thought', 'content': thought_part}, ensure_ascii=False)}\n\n" in_thinking_mode = False else: thought_chunks.append(cur) yield f"data: {json.dumps({'type': 'thought', 'content': cur}, ensure_ascii=False)}\n\n" break except Exception: continue
elapsed = round(time.time() - t0, 2) tok_per_sec = round(token_count / elapsed, 1) if elapsed > 0 else 0 full_thought = "".join(thought_chunks).strip() full_content = "".join(content_chunks).strip() done_payload = json.dumps({ "type": "done", "tokens": token_count, "elapsed": elapsed, "tok_per_sec": tok_per_sec, }, ensure_ascii=False) yield f"data: {done_payload}\n\n" # Log chat log_chat({ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "client_ip": client_ip, "messages": [m.dict() for m in req.messages], "tokens": token_count, "elapsed": elapsed, "tok_per_sec": tok_per_sec, "enable_thinking": enable_thinking, "thought_len": len(full_thought), "content_len": len(full_content) })
except Exception as ex: err_data = json.dumps({"type": "error", "error": str(ex)}, ensure_ascii=False) yield f"data: {err_data}\n\n"
return StreamingResponse(event_generator(), media_type="text/event-stream")
if __name__ == "__main__": ap = argparse.ArgumentParser(description="Qwen-HTML WebUI") ap.add_argument("--port", type=int, default=PORT, help=f"listen port (default {PORT}, env WEBUI_PORT)") args = ap.parse_args() print(f"Starting Qwen-HTML WebUI on http://0.0.0.0:{args.port} (api={DEFAULT_API_URL})") uvicorn.run(app, host="0.0.0.0", port=args.port, log_level="info")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mario-HTML Explorer</title> <link rel="stylesheet" href="/static/theme.css"> <style id="custom-theme-style"></style> <style> :root { --bg-page: #f8fafc; --bg-surface: #ffffff; --bg-surface-elevated: #f1f5f9; --border-color: #e2e8f0; --border-focus: #2563eb; --text-main: #0f172a; --text-sub: #64748b; --accent: #2563eb; --accent-hover: #1d4ed8; --accent-subtle: #eff6ff; }
* { box-sizing: border-box; margin: 0; padding: 0; } body { background-color: var(--bg-page); color: var(--text-main); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; height: 100vh; display: flex; flex-direction: column; overflow: hidden; padding: 0; }
/* Header */ header { background-color: rgba(255, 255, 255, 0.95); border-bottom: 1px solid var(--border-color); padding: 12px 24px; display: flex; align-items: center; justify-content: space-between; backdrop-filter: blur(8px); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); z-index: 20; } .brand { display: flex; align-items: center; gap: 10px; font-size: 1.1rem; font-weight: 700; color: var(--text-main); letter-spacing: -0.02em; } .brand-badge { background: var(--accent-subtle); color: var(--accent); font-size: 0.75rem; padding: 2px 8px; border-radius: 999px; font-weight: 600; border: 1px solid #bfdbfe; } .header-actions { display: flex; align-items: center; gap: 12px; } .status-pill { display: flex; align-items: center; gap: 6px; font-size: 0.8rem; padding: 4px 12px; border-radius: 999px; background: var(--bg-surface); border: 1px solid var(--border-color); color: var(--text-sub); cursor: pointer; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04); transition: all 0.2s; } .status-pill:hover { border-color: var(--accent); color: var(--text-main); } .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #10b981; } .status-dot.error { background: #ef4444; }
.btn-icon { background: var(--bg-surface); border: 1px solid var(--border-color); color: #334155; padding: 6px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 500; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04); transition: all 0.2s; } .btn-icon:hover { background: var(--bg-surface-elevated); border-color: #cbd5e1; color: var(--text-main); }
/* Main Chat Container */ #chat-container { flex: 1; overflow-y: auto; padding: 24px 16px 220px 16px; scroll-behavior: smooth; } .chat-inner { max-width: 920px; margin: 0 auto; display: flex; flex-direction: column; gap: 28px; padding-bottom: 40px; }
/* Welcome Banner */ .welcome-card { background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); border: 1px solid var(--border-color); border-radius: 14px; padding: 32px 24px; text-align: center; margin-top: 16px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05); } .welcome-title { font-size: 1.45rem; font-weight: 700; margin-bottom: 8px; color: var(--text-main); } .welcome-desc { color: var(--text-sub); font-size: 0.95rem; max-width: 620px; margin: 0 auto 24px auto; line-height: 1.6; } .chips-grid { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; } .prompt-chip { background: var(--bg-surface); border: 1px solid var(--border-color); padding: 7px 16px; border-radius: 20px; font-size: 0.85rem; color: var(--text-main); cursor: pointer; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); transition: all 0.2s; } .prompt-chip:hover { background: var(--accent-subtle); border-color: #93c5fd; color: var(--accent); transform: translateY(-1px); }
/* Message Bubbles */ .message-row { display: flex; flex-direction: column; gap: 8px; animation: fadeIn 0.25s ease-out; } @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } .message-user { align-self: flex-end; max-width: 80%; } .user-bubble { background: var(--accent); color: #ffffff; padding: 12px 18px; border-radius: 14px 14px 2px 14px; font-size: 0.95rem; line-height: 1.5; word-break: break-word; box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2); } .message-assistant { align-self: stretch; max-width: 100%; }
/* Thinking Trace Block */ .thinking-box { background: #f8fafc; border: 1px solid var(--border-color); border-left: 3px solid #6366f1; border-radius: 8px; margin-bottom: 12px; overflow: hidden; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02); } .thinking-summary { padding: 9px 14px; display: flex; align-items: center; gap: 8px; font-size: 0.82rem; font-weight: 600; color: #475569; font-family: var(--font-mono, monospace); cursor: pointer; user-select: none; background: #f1f5f9; } .thinking-summary:hover { color: var(--text-main); } .thinking-summary::marker { display: none; } .thinking-content { padding: 14px 18px; font-family: var(--font-mono, monospace); font-size: 0.82rem; color: #475569; line-height: 1.6; white-space: pre-wrap; word-break: break-word; border-top: 1px solid var(--border-color); max-height: 380px; overflow-y: auto; background: #f8fafc; }
/* HTML Content Canvas */ .html-canvas { background: #ffffff; color: #1e293b; border-radius: 14px; padding: 24px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06); border: 1px solid var(--border-color); overflow-x: auto; } .raw-source-view { background: #0f172a; color: #38bdf8; font-family: var(--font-mono, monospace); font-size: 0.82rem; padding: 16px; border-radius: 8px; white-space: pre-wrap; word-break: break-all; max-height: 400px; overflow-y: auto; border: 1px solid #1e293b; display: none; margin-top: 10px; }
/* Action bar below message */ .msg-footer { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; padding: 8px 14px; background: var(--bg-surface); border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.78rem; color: var(--text-sub); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); } .msg-stats { display: flex; align-items: center; gap: 12px; font-family: var(--font-mono, monospace); font-weight: 500; } .msg-actions { display: flex; align-items: center; gap: 8px; } .action-btn { background: var(--bg-surface-elevated); border: 1px solid var(--border-color); color: #334155; font-size: 0.75rem; font-weight: 500; padding: 4px 10px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; transition: all 0.15s; } .action-btn:hover { background: #e2e8f0; color: var(--accent); border-color: #cbd5e1; }
/* Input Floating Bar */ .input-wrapper { position: fixed; bottom: 0; left: 0; right: 0; background: linear-gradient(180deg, rgba(248, 250, 252, 0) 0%, rgba(248, 250, 252, 0.95) 25%, #f8fafc 100%); padding: 16px 16px 22px 16px; z-index: 10; } .input-box { max-width: 920px; margin: 0 auto; background: var(--bg-surface); border: 1px solid #cbd5e1; border-radius: 14px; padding: 12px 16px; display: flex; flex-direction: column; gap: 8px; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.08), 0 8px 10px -6px rgba(0, 0, 0, 0.04); transition: border-color 0.2s, box-shadow 0.2s; } .input-box:focus-within { border-color: var(--accent); box-shadow: 0 10px 25px -5px rgba(37, 99, 235, 0.12), 0 8px 10px -6px rgba(37, 99, 235, 0.08); } textarea { width: 100%; background: transparent; border: none; outline: none; color: var(--text-main); font-size: 0.95rem; font-family: inherit; resize: none; min-height: 44px; max-height: 180px; line-height: 1.5; } textarea::placeholder { color: #94a3b8; } .input-bottom-row { display: flex; align-items: center; justify-content: space-between; border-top: 1px solid #f1f5f9; padding-top: 8px; } .toggle-label { display: inline-flex; align-items: center; gap: 8px; font-size: 0.8rem; color: var(--text-sub); cursor: pointer; user-select: none; font-weight: 500; } .toggle-switch { position: relative; width: 34px; height: 18px; background: #cbd5e1; border-radius: 999px; transition: background 0.2s; } .toggle-switch.active { background: #6366f1; } .toggle-knob { position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; background: #fff; border-radius: 50%; transition: transform 0.2s; } .toggle-switch.active .toggle-knob { transform: translateX(16px); }
.btn-send { background: var(--accent); color: #ffffff; border: none; padding: 7px 18px; border-radius: 8px; font-weight: 600; font-size: 0.85rem; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s; } .btn-send:hover { background: var(--accent-hover); } .btn-send:disabled { background: #e2e8f0; color: #94a3b8; cursor: not-allowed; }
/* Settings Modal */ .modal-overlay { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.4); backdrop-filter: blur(4px); display: none; align-items: center; justify-content: center; z-index: 100; } .modal-overlay.open { display: flex; } .modal-card { background: #ffffff; border: 1px solid var(--border-color); border-radius: 14px; width: 90%; max-width: 620px; max-height: 85vh; display: flex; flex-direction: column; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); animation: modalIn 0.2s ease-out; } @keyframes modalIn { from { transform: scale(0.96); opacity: 0; } to { transform: scale(1); opacity: 1; } } .modal-header { padding: 16px 20px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between; } .modal-header h3 { font-size: 1.1rem; color: var(--text-main); } .modal-close { background: none; border: none; color: var(--text-sub); font-size: 1.2rem; cursor: pointer; } .modal-close:hover { color: var(--text-main); } .modal-body { padding: 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; } .modal-footer { padding: 14px 20px; border-top: 1px solid var(--border-color); display: flex; justify-content: flex-end; gap: 10px; }
.form-group { display: flex; flex-direction: column; gap: 6px; } .form-group label { font-size: 0.85rem; font-weight: 600; color: var(--text-main); } .form-desc { font-size: 0.75rem; color: var(--text-sub); } .input-text, select { background: #ffffff; border: 1px solid #cbd5e1; color: var(--text-main); padding: 8px 12px; border-radius: 6px; font-size: 0.85rem; font-family: inherit; outline: none; } .input-text:focus, select:focus { border-color: var(--accent); } .tab-pills { display: flex; gap: 6px; background: #f1f5f9; padding: 4px; border-radius: 8px; } .tab-pill { flex: 1; text-align: center; padding: 6px 12px; font-size: 0.8rem; font-weight: 600; border-radius: 6px; cursor: pointer; color: var(--text-sub); transition: all 0.2s; } .tab-pill.active { background: #ffffff; color: var(--text-main); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); } .modal-nav-tabs { display: flex; border-bottom: 1px solid var(--border-color); background: #f8fafc; border-top-left-radius: 14px; border-top-right-radius: 14px; } .modal-nav-tab { flex: 1; text-align: center; padding: 11px 14px; font-size: 0.82rem; font-weight: 600; color: var(--text-sub); cursor: pointer; border-bottom: 2px solid transparent; transition: all 0.2s; } .modal-nav-tab:hover { color: var(--text-main); background: #f1f5f9; } .modal-nav-tab.active { color: var(--accent); border-bottom-color: var(--accent); background: #ffffff; } .preset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 8px; } .preset-btn { background: #f8fafc; border: 1px solid var(--border-color); border-radius: 8px; padding: 9px 12px; font-size: 0.8rem; font-weight: 600; color: #334155; cursor: pointer; text-align: center; transition: all 0.15s; } .preset-btn:hover { background: var(--accent-subtle); border-color: #93c5fd; color: var(--accent); } .preset-btn.active { background: var(--accent-subtle); border-color: var(--accent); color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } .snippet-pills { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } .snippet-pill { background: #f1f5f9; border: 1px solid var(--border-color); color: #475569; font-size: 0.72rem; padding: 3px 8px; border-radius: 4px; cursor: pointer; font-family: var(--font-mono, monospace); } .snippet-pill:hover { background: #e2e8f0; color: var(--accent); } .slider-row { display: flex; align-items: center; gap: 12px; } .slider-row input[type="range"] { flex: 1; } .slider-val { font-family: var(--font-mono, monospace); font-size: 0.85rem; width: 50px; text-align: right; color: var(--text-main); } </style></head><body>
<!-- Top Navigation --> <header> <div class="brand"> <span>🍄 Mario-HTML Explorer</span> <span class="brand-badge">RL Math & HTML Native</span> </div> <div class="header-actions"> <div class="status-pill" id="status-pill" onclick="openSettings()"> <span class="status-dot" id="status-dot"></span> <span id="status-text">Connecting...</span> </div> <button class="btn-icon" onclick="clearChat()">🧹 Clear</button> <button class="btn-icon" onclick="openSettings()">⚙️ Settings</button> </div> </header>
<!-- Chat View --> <main id="chat-container"> <div class="chat-inner" id="messages-list"> <!-- Welcome Card --> <div class="welcome-card" id="welcome-card"> <div class="welcome-title">Spark-x2.6-4B · Mario-HTML</div> <p class="welcome-desc"> Spark-x2.6-4B + LoRA 在 830 条马里奥 HTML 数据上 SFT(1.4 Epoch)。思维链保留、正文输出规范卡片,思考强度可在输入框左侧切换。 </p> <div class="chips-grid"> <div class="prompt-chip" onclick="sendPreset('Solve the linear equation: 2x + 5 = 17 step by step')">📐 2x + 5 = 17 Equation</div> <div class="prompt-chip" onclick="sendPreset('Explain Binary Search algorithm with complexity and steps')">⚡ Binary Search</div> <div class="prompt-chip" onclick="sendPreset('Compare 9.11 and 9.9 — which one is larger and why?')">⚖️ 9.11 vs 9.9</div> <div class="prompt-chip" onclick="sendPreset('Compare Microservices vs Monolith architecture in a modern comparison grid')">🏛️ Microservices vs Monolith</div> </div> </div>
</div> </main>
<!-- Floating Input Bar --> <div class="input-wrapper"> <div class="input-box"> <!-- Attached image preview bar --> <div id="image-preview-bar" style="display:none; padding:8px 12px; align-items:center; gap:10px; background:#f1f5f9; border-radius:8px; margin-bottom:8px; border:1px solid #e2e8f0;"> <img id="attached-img-thumb" style="max-height:48px; max-width:64px; border-radius:6px; object-fit:cover; border:1px solid #cbd5e1;"> <span id="attached-img-name" style="font-size:0.8rem; color:#475569; flex-grow:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">image.png</span> <button onclick="removeAttachedImage()" type="button" style="background:none; border:none; color:#ef4444; font-size:1.1rem; cursor:pointer; padding:0 4px; font-weight:bold;" title="Remove image">✕</button> </div>
<textarea id="prompt-input" placeholder="Ask a question or request a structured HTML card presentation..." rows="1" onkeydown="handleKeyDown(event)"></textarea> <div class="input-bottom-row"> <div style="display:flex; align-items:center; gap:10px;"> <label class="toggle-label" onclick="toggleThinking()"> <span class="toggle-switch active" id="thinking-switch"> <span class="toggle-knob"></span> </span> <span id="thinking-label">🧠 CoT: ON</span> </label> <select id="effort-select" onchange="setEffort(this.value)" title="思考强度:低 = 快速出卡,高 = 深度推演" style="background:#ffffff;border:1px solid #cbd5e1;border-radius:8px;padding:5px 8px;font-size:0.82rem;color:#334155;cursor:pointer;"> <option value="low" selected>思考: 低(快速出卡,推荐)</option> <option value="medium">思考: 中(标准推演)</option> <option value="xhigh">思考: 高(深度推演)</option> </select> </div> <button class="btn-send" id="send-btn" onclick="handleSendOrStop()">Send ↵</button> </div> </div> </div>
<!-- Settings Modal --> <div class="modal-overlay" id="settings-modal"> <div class="modal-card"> <div class="modal-header"> <h3>Model & Inference Settings</h3> <button class="modal-close" onclick="closeSettings()">✕</button> </div> <div class="modal-nav-tabs"> <div class="modal-nav-tab active" id="nav-tab-conn" onclick="switchModalNav('conn')">🔌 Model & Engine</div> <div class="modal-nav-tab" id="nav-tab-theme" onclick="switchModalNav('theme')">🎨 Styling & Theme</div> <div class="modal-nav-tab" id="nav-tab-params" onclick="switchModalNav('params')">⚙️ Parameters</div> </div> <div class="modal-body"> <!-- SECTION 1: Model & Engine --> <div id="modal-sec-conn" style="display: flex; flex-direction: column; gap: 16px;"> <div class="form-group"> <label>Backend Provider Mode</label> <div class="tab-pills"> <div class="tab-pill active" id="tab-api" onclick="switchBackendTab('api')">Llama.cpp API Server</div> <div class="tab-pill" id="tab-direct" onclick="switchBackendTab('direct')">Direct Model Path</div> </div> </div>
<!-- API Mode Section --> <div id="section-api" style="display: flex; flex-direction: column; gap: 12px;"> <div class="form-group"> <label>Llama.cpp Server URL</label> <input type="text" class="input-text" id="cfg-api-url" placeholder="http://127.0.0.1:18085"> <span class="form-desc">Compatible with standard OpenAI-style <code>/v1/chat/completions</code> endpoint.</span> </div> </div>
<!-- Direct Mode Section --> <div id="section-direct" style="display: none; flex-direction: column; gap: 12px;"> <div class="form-group"> <label>Model Preset</label> <select id="cfg-model-preset" onchange="onPresetChange()"> <option value="/mnt/sdb/models/qwen3.5-4b-html-v4-grpo-math-gguf/Qwen3.5-4B-HTML-v4-GRPO-Math-Q8_0.gguf">Qwen3.5-4B-HTML-Q8_0 (Recommended, 4.3GB)</option> <option value="/mnt/sdb/models/qwen3.5-4b-html-v4-grpo-math-gguf/Qwen3.5-4B-HTML-v4-GRPO-Math-Q4_K_M.gguf">Qwen3.5-4B-HTML-Q4_K_M (Fast, 2.6GB)</option> <option value="custom">Custom Path...</option> </select> </div> <div class="form-group"> <label>GGUF Model Path</label> <input type="text" class="input-text" id="cfg-model-path" placeholder="/mnt/sdb/models/..."> </div> <div style="display: flex; gap: 12px;"> <div class="form-group" style="flex:1;"> <label>Context Window</label> <input type="number" class="input-text" id="cfg-ctx" value="65536"> </div> <div class="form-group" style="flex:1;"> <label>GPU Offload Layers</label> <input type="number" class="input-text" id="cfg-ngl" value="99"> </div> </div> <button class="btn-icon" style="background:#2563eb; color:#fff; justify-content:center; padding:8px;" onclick="loadDirectModel()"> 🚀 Load Model & Restart Llama Server </button> </div> </div>
<!-- SECTION 2: Styling & Theme --> <div id="modal-sec-theme" style="display: none; flex-direction: column; gap: 16px;"> <div class="form-group"> <label>Theme Presets (One-Click Style Switch)</label> <div class="preset-grid"> <button type="button" class="preset-btn active" id="btn-theme-default" onclick="selectThemePreset('default')">Default Modern</button> <button type="button" class="preset-btn" id="btn-theme-apple" onclick="selectThemePreset('apple')">Apple Clean</button> <button type="button" class="preset-btn" id="btn-theme-notion" onclick="selectThemePreset('notion')">Notion Minimal</button> <button type="button" class="preset-btn" id="btn-theme-cyber" onclick="selectThemePreset('cyber')">Cyber Neon</button> <button type="button" class="preset-btn" id="btn-theme-editorial" onclick="selectThemePreset('editorial')">Editorial Serif</button> </div> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between; align-items:center;"> <label>Custom CSS Overrides</label> <button type="button" class="action-link" style="font-size:0.75rem;" onclick="resetCustomCss()">Reset CSS</button> </div> <textarea class="input-text" id="cfg-custom-css" rows="8" placeholder="/* Enter custom CSS rules to customize .ai-view and cards */" oninput="applyLiveCustomCss(this.value)" style="font-size:0.78rem; font-family:var(--font-mono, monospace); line-height:1.5;"></textarea> <span class="form-desc">Injected live in real-time. Overrides apply instantly to all cards & responses.</span> <div class="snippet-pills"> <span style="font-size:0.72rem; color:var(--text-sub); align-self:center;">Quick Snippets:</span> <button type="button" class="snippet-pill" onclick="insertCssSnippet('cards_rounded')">+ 24px Round Cards</button> <button type="button" class="snippet-pill" onclick="insertCssSnippet('glassmorphism')">+ Frosted Glass</button> <button type="button" class="snippet-pill" onclick="insertCssSnippet('soft_shadows')">+ Subtle Glow</button> <button type="button" class="snippet-pill" onclick="insertCssSnippet('compact')">+ Compact Density</button> </div> </div> </div>
<!-- SECTION 3: Parameters --> <div id="modal-sec-params" style="display: none; flex-direction: column; gap: 16px;"> <div style="display:flex; justify-content:space-between; align-items:center; background:var(--bg-secondary); padding:10px 14px; border-radius:var(--radius-sm); border:1px solid var(--border);"> <div> <div style="font-weight:600; font-size:0.85rem;">Sampling Decoding (Do Sample)</div> <div style="font-size:0.72rem; color:var(--text-sub);">Enable probabilistic sampling. If disabled, uses greedy decoding (temp=0).</div> </div> <input type="checkbox" id="cfg-do-sample" style="width:18px; height:18px; accent-color:var(--accent); cursor:pointer;"> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Temperature</label> <span class="slider-val" id="temp-val">1.00</span> </div> <div class="slider-row"> <input type="range" id="cfg-temp" min="0" max="2.0" step="0.05" oninput="document.getElementById('temp-val').innerText = parseFloat(this.value).toFixed(2)"> </div> <span class="form-desc">Higher = more creative; lower = more focused and deterministic. Default: 1.0.</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Top-P (Nucleus Sampling)</label> <span class="slider-val" id="topp-val">0.95</span> </div> <div class="slider-row"> <input type="range" id="cfg-top-p" min="0" max="1.0" step="0.05" oninput="document.getElementById('topp-val').innerText = parseFloat(this.value).toFixed(2)"> </div> <span class="form-desc">Limits cumulative probability mass of top candidates. Default: 0.95.</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Top-K Sampling</label> <span class="slider-val" id="topk-val">20</span> </div> <div class="slider-row"> <input type="range" id="cfg-top-k" min="0" max="100" step="1" oninput="document.getElementById('topk-val').innerText = this.value === '0' ? 'Off' : this.value"> </div> <span class="form-desc">Sample only from top K tokens. Set to 0 to disable. Default: 20.</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Min-P Sampling</label> <span class="slider-val" id="minp-val">0.00</span> </div> <div class="slider-row"> <input type="range" id="cfg-min-p" min="0.0" max="1.0" step="0.01" oninput="document.getElementById('minp-val').innerText = parseFloat(this.value).toFixed(2)"> </div> <span class="form-desc">Minimum probability threshold relative to most likely token. Default: 0.00.</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Presence Penalty (存在惩罚)</label> <span class="slider-val" id="pres-val">1.50</span> </div> <div class="slider-row"> <input type="range" id="cfg-pres-penalty" min="-2.0" max="2.0" step="0.1" oninput="document.getElementById('pres-val').innerText = parseFloat(this.value).toFixed(2)"> </div> <span class="form-desc">Penalize tokens based on presence in text to encourage new topics. Default: 1.50.</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Repetition Penalty (重复性惩罚)</label> <span class="slider-val" id="rep-val">1.00</span> </div> <div class="slider-row"> <input type="range" id="cfg-rep-penalty" min="1.0" max="2.0" step="0.02" oninput="document.getElementById('rep-val').innerText = parseFloat(this.value).toFixed(2)"> </div> <span class="form-desc">Penalize recurring tokens to prevent repetitive n-gram loops. Default: 1.00.</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between;"> <label>Max Output Tokens (提高至最大 Context 80K)</label> <span class="slider-val" id="max-val">8192</span> </div> <div class="slider-row"> <input type="range" id="cfg-max-tokens" min="512" max="81920" step="512" oninput="document.getElementById('max-val').innerText = this.value"> </div> <div class="snippet-pills" style="margin-top:6px;"> <span style="font-size:0.72rem; color:var(--text-sub); align-self:center;">Presets:</span> <button type="button" class="snippet-pill" onclick="setMaxTokensPreset(4096)">4K</button> <button type="button" class="snippet-pill" onclick="setMaxTokensPreset(8192)">8K</button> <button type="button" class="snippet-pill" onclick="setMaxTokensPreset(16384)">16K</button> <button type="button" class="snippet-pill" onclick="setMaxTokensPreset(32768)">32K</button> <button type="button" class="snippet-pill" onclick="setMaxTokensPreset(65536)">64K</button> <button type="button" class="snippet-pill" onclick="setMaxTokensPreset(81920)">80K Max</button> </div> <span class="form-desc">Maximum generation token limit per response (up to full 80K context window).</span> </div>
<div class="form-group"> <div style="display:flex; justify-content:space-between; align-items:center;"> <label>System Prompt (留空默认 Mario Zero-Prompt)</label> <button type="button" class="action-link" style="font-size:0.72rem;" onclick="document.getElementById('cfg-system-prompt').value=''">Clear Prompt</button> </div> <textarea class="input-text" id="cfg-system-prompt" rows="4" placeholder="Leave empty to use native Mario card-generating persona" style="font-size:0.75rem; font-family:var(--font-mono, monospace);"></textarea> <span class="form-desc">Default is empty. Mario natively formats visual HTML cards without manual prompts.</span> </div> </div>
</div> <div class="modal-footer"> <button class="btn-icon" onclick="closeSettings()">Cancel</button> <button class="btn-icon" style="background:var(--accent); color:#ffffff;" onclick="saveSettings()">Save Settings</button> </div> </div> </div>
<script> let appConfig = {}; let isGenerating = false; let conversationHistory = [];
const THEME_PRESETS = { default: `/* Default Modern Theme */`, apple: `/* Apple Clean */.html-canvas { border-radius: 20px !important; background: #fbfbfd !important; border: 1px solid rgba(0,0,0,0.06) !important; box-shadow: 0 10px 30px rgba(0,0,0,0.05) !important; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif !important;}.card { border-radius: 16px !important; border: 1px solid rgba(0,0,0,0.06) !important; background: #ffffff !important; box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important;}.summary-card { border-radius: 16px !important; border-left-width: 6px !important;}.callout { border-radius: 14px !important;}.badge { border-radius: 8px !important; font-weight: 600 !important;}`, notion: `/* Notion Minimal */.html-canvas { border-radius: 4px !important; border: 1px solid #37352f !important; box-shadow: none !important; background: #ffffff !important;}.card { border-radius: 4px !important; border: 1px solid #e3e2e0 !important; box-shadow: none !important;}.summary-card { border-radius: 4px !important; border-left-color: #37352f !important;}.callout { border-radius: 4px !important; border-left-width: 4px !important;}.badge { border-radius: 3px !important; font-weight: 500 !important;}`, cyber: `/* Cyber Neon */.html-canvas { background: #090d16 !important; color: #e2e8f0 !important; border: 1px solid #00f2ff !important; box-shadow: 0 0 25px rgba(0, 242, 255, 0.25) !important;}.card { background: #111827 !important; border: 1px solid #1f2937 !important; color: #f8fafc !important;}.summary-card { background: #111827 !important; border-left-color: #00f2ff !important;}.modern-table th { background: #1e293b !important; color: #00f2ff !important;}.badge-accent { background: rgba(0, 242, 255, 0.2) !important; color: #00f2ff !important; border: 1px solid #00f2ff !important;}`, editorial: `/* Editorial Serif */.html-canvas { background: #fdfbf7 !important; color: #2c2523 !important; font-family: "Georgia", "Times New Roman", serif !important; border: 1px solid #e7dfd5 !important;}.card { background: #ffffff !important; border: 1px solid #e7dfd5 !important; box-shadow: 0 2px 4px rgba(44, 37, 35, 0.04) !important;}h2, h3, h4 { font-family: "Georgia", serif !important; font-weight: 600 !important;}.modern-table { border-top: 2px solid #2c2523 !important; border-bottom: 2px solid #2c2523 !important;}` };
const CSS_SNIPPETS = { cards_rounded: `\n/* Rounded Cards */\n.card, .html-canvas { border-radius: 24px !important; }\n`, glassmorphism: `\n/* Frosted Glass */\n.card {\n background: rgba(255, 255, 255, 0.8) !important;\n backdrop-filter: blur(12px) !important;\n border: 1px solid rgba(255, 255, 255, 0.6) !important;\n}\n`, soft_shadows: `\n/* Subtle Glow */\n.card:hover {\n box-shadow: 0 10px 25px -5px rgba(37, 99, 235, 0.15) !important;\n border-color: #93c5fd !important;\n}\n`, compact: `\n/* Compact Density */\n.ai-view { gap: 12px !important; }\n.card { padding: 14px 18px !important; }\n` };
function switchModalNav(tab) { document.getElementById("nav-tab-conn").className = tab === 'conn' ? "modal-nav-tab active" : "modal-nav-tab"; document.getElementById("nav-tab-theme").className = tab === 'theme' ? "modal-nav-tab active" : "modal-nav-tab"; document.getElementById("nav-tab-params").className = tab === 'params' ? "modal-nav-tab active" : "modal-nav-tab";
document.getElementById("modal-sec-conn").style.display = tab === 'conn' ? 'flex' : 'none'; document.getElementById("modal-sec-theme").style.display = tab === 'theme' ? 'flex' : 'none'; document.getElementById("modal-sec-params").style.display = tab === 'params' ? 'flex' : 'none'; }
function applyLiveCustomCss(cssText) { let tag = document.getElementById("custom-theme-style"); if (!tag) { tag = document.createElement("style"); tag.id = "custom-theme-style"; document.head.appendChild(tag); } tag.textContent = cssText || ""; }
function selectThemePreset(name) { appConfig.theme_preset = name; document.querySelectorAll(".preset-btn").forEach(b => b.classList.remove("active")); const activeBtn = document.getElementById("btn-theme-" + name); if (activeBtn) activeBtn.classList.add("active");
const css = THEME_PRESETS[name] || ""; document.getElementById("cfg-custom-css").value = css; applyLiveCustomCss(css); }
function insertCssSnippet(key) { const snip = CSS_SNIPPETS[key] || ""; const tx = document.getElementById("cfg-custom-css"); tx.value = (tx.value + "\n" + snip).trim(); applyLiveCustomCss(tx.value); }
function resetCustomCss() { selectThemePreset("default"); }
// Initialize window.addEventListener("DOMContentLoaded", async () => { await fetchConfig(); await checkStatus(); setInterval(checkStatus, 5000); autoResizeTextarea(); });
async function fetchConfig() { try { const res = await fetch("/api/config"); appConfig = await res.json(); // 思考强度:localStorage 记住上次选择,否则用 config 里的值(low) let eff = appConfig.reasoning_effort || "low"; try { eff = localStorage.getItem("reasoning_effort") || eff; } catch (e) {} appConfig.reasoning_effort = eff; const effSel = document.getElementById("effort-select"); if (effSel) effSel.value = eff; const preset = appConfig.theme_preset || "default"; const css = appConfig.custom_css || (preset !== 'default' ? THEME_PRESETS[preset] : ""); applyLiveCustomCss(css); updateSettingsModalForm(); } catch (e) { console.error("Failed to load config", e); } }
async function checkStatus() { try { const res = await fetch("/api/status"); const data = await res.json(); const dot = document.getElementById("status-dot"); const txt = document.getElementById("status-text");
if (data.status === "ready") { dot.className = "status-dot"; txt.innerText = `${data.model_info} (${data.latency_ms || 0}ms)`; } else { dot.className = "status-dot error"; txt.innerText = "Server Offline"; } } catch (e) { document.getElementById("status-dot").className = "status-dot error"; document.getElementById("status-text").innerText = "Connection Failed"; } }
function setEffort(v) { appConfig.reasoning_effort = v; try { localStorage.setItem("reasoning_effort", v); } catch (e) {} }
function toggleThinking() { appConfig.enable_thinking = !appConfig.enable_thinking; const sw = document.getElementById("thinking-switch"); const lbl = document.getElementById("thinking-label"); if (appConfig.enable_thinking) { sw.className = "toggle-switch active"; lbl.innerText = "🧠 CoT Reasoning: ON"; } else { sw.className = "toggle-switch"; lbl.innerText = "⚡ Direct HTML (No CoT)"; } }
function switchBackendTab(mode) { document.getElementById("tab-api").className = mode === 'api' ? "tab-pill active" : "tab-pill"; document.getElementById("tab-direct").className = mode === 'direct' ? "tab-pill active" : "tab-pill"; document.getElementById("section-api").style.display = mode === 'api' ? 'flex' : 'none'; document.getElementById("section-direct").style.display = mode === 'direct' ? 'flex' : 'none'; appConfig.backend_mode = mode; }
function onPresetChange() { const sel = document.getElementById("cfg-model-preset").value; if (sel !== "custom") { document.getElementById("cfg-model-path").value = sel; } }
function openSettings() { updateSettingsModalForm(); document.getElementById("settings-modal").classList.add("open"); }
function closeSettings() { document.getElementById("settings-modal").classList.remove("open"); }
function setMaxTokensPreset(val) { document.getElementById("cfg-max-tokens").value = val; document.getElementById("max-val").innerText = val; }
function updateSettingsModalForm() { document.getElementById("cfg-api-url").value = appConfig.api_url || "http://127.0.0.1:18085"; document.getElementById("cfg-model-path").value = appConfig.model_path || ""; document.getElementById("cfg-ctx").value = appConfig.context_size || 81920; document.getElementById("cfg-ngl").value = appConfig.gpu_layers || 99; const doSample = appConfig.do_sample !== false; document.getElementById("cfg-do-sample").checked = doSample;
const temp = appConfig.temperature ?? 1.0; document.getElementById("cfg-temp").value = temp; document.getElementById("temp-val").innerText = parseFloat(temp).toFixed(2);
const topP = appConfig.top_p ?? 0.95; document.getElementById("cfg-top-p").value = topP; document.getElementById("topp-val").innerText = parseFloat(topP).toFixed(2);
const topK = appConfig.top_k ?? 20; document.getElementById("cfg-top-k").value = topK; document.getElementById("topk-val").innerText = topK <= 0 ? "Off" : topK;
const minP = appConfig.min_p ?? 0.0; document.getElementById("cfg-min-p").value = minP; document.getElementById("minp-val").innerText = parseFloat(minP).toFixed(2);
const presPen = appConfig.presence_penalty ?? 1.5; document.getElementById("cfg-pres-penalty").value = presPen; document.getElementById("pres-val").innerText = parseFloat(presPen).toFixed(2);
const repPen = appConfig.repetition_penalty ?? 1.0; document.getElementById("cfg-rep-penalty").value = repPen; document.getElementById("rep-val").innerText = parseFloat(repPen).toFixed(2);
const maxTok = appConfig.max_tokens ?? 8192; document.getElementById("cfg-max-tokens").value = maxTok; document.getElementById("max-val").innerText = maxTok;
document.getElementById("cfg-system-prompt").value = appConfig.system_prompt || "";
const preset = appConfig.theme_preset || "default"; document.querySelectorAll(".preset-btn").forEach(b => b.classList.remove("active")); const btn = document.getElementById("btn-theme-" + preset); if (btn) btn.classList.add("active"); document.getElementById("cfg-custom-css").value = appConfig.custom_css || (preset !== 'default' ? THEME_PRESETS[preset] : "");
switchBackendTab(appConfig.backend_mode || 'api'); }
async function saveSettings() { const payload = { backend_mode: appConfig.backend_mode, api_url: document.getElementById("cfg-api-url").value, do_sample: document.getElementById("cfg-do-sample").checked, temperature: parseFloat(document.getElementById("cfg-temp").value), top_p: parseFloat(document.getElementById("cfg-top-p").value), top_k: parseInt(document.getElementById("cfg-top-k").value), min_p: parseFloat(document.getElementById("cfg-min-p").value), presence_penalty: parseFloat(document.getElementById("cfg-pres-penalty").value), repetition_penalty: parseFloat(document.getElementById("cfg-rep-penalty").value), max_tokens: parseInt(document.getElementById("cfg-max-tokens").value), system_prompt: document.getElementById("cfg-system-prompt").value, enable_thinking: appConfig.enable_thinking, theme_preset: appConfig.theme_preset || "default", custom_css: document.getElementById("cfg-custom-css").value }; await fetch("/api/config", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); closeSettings(); await fetchConfig(); await checkStatus(); }
async function loadDirectModel() { const path = document.getElementById("cfg-model-path").value.trim(); const ctx = parseInt(document.getElementById("cfg-ctx").value); const ngl = parseInt(document.getElementById("cfg-ngl").value); if (!path) { alert("Please enter a valid model path."); return; } const btn = event.target; const origText = btn.innerText; btn.innerText = "⏳ Loading Model..."; btn.disabled = true;
try { const res = await fetch("/api/model/load", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model_path: path, context_size: ctx, gpu_layers: ngl }) }); const data = await res.json(); if (res.ok) { alert(data.message || "Model loaded successfully!"); closeSettings(); await fetchConfig(); await checkStatus(); } else { alert("Error: " + (data.error || "Failed to load model.")); } } catch (err) { alert("Error connecting to server: " + err.message); } finally { btn.innerText = origText; btn.disabled = false; } }
function clearChat() { conversationHistory = []; const list = document.getElementById("messages-list"); list.innerHTML = ` <div class="welcome-card" id="welcome-card"> <div class="welcome-title">Qwen3.8-27B · Mario-HTML LoRA</div> <p class="welcome-desc"> Qwen3.8-27B + QLoRA(r16,仅 attention 层)在 830 条马里奥 HTML 数据上 SFT。思维链保留、只改造正文输出,思考强度可在输入框左侧切换。 </p> <div class="chips-grid"> <div class="prompt-chip" onclick="sendPreset('Solve the linear equation: 2x + 5 = 17 step by step')">📐 2x + 5 = 17 Equation</div> <div class="prompt-chip" onclick="sendPreset('Explain Binary Search algorithm with complexity and steps')">⚡ Binary Search</div> <div class="prompt-chip" onclick="sendPreset('Compare 9.11 and 9.9 — which one is larger and why?')">⚖️ 9.11 vs 9.9</div> <div class="prompt-chip" onclick="sendPreset('Compare Microservices vs Monolith architecture in a modern comparison grid')">🏛️ Microservices vs Monolith</div> </div> </div> `; }
function sendPreset(text) { document.getElementById("prompt-input").value = text; sendMessage(); }
function handleKeyDown(e) { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); } }
function autoResizeTextarea() { const tx = document.getElementById("prompt-input"); tx.addEventListener("input", () => { tx.style.height = "auto"; tx.style.height = Math.min(tx.scrollHeight, 180) + "px"; }); }
let attachedImageBase64 = null;
function handleImageFileSelect(e) { const file = e.target.files[0]; if (file) loadImageFile(file); e.target.value = ""; }
function loadImageFile(file) { if (!file || !file.type.startsWith("image/")) return; const reader = new FileReader(); reader.onload = function(evt) { attachedImageBase64 = evt.target.result; document.getElementById("attached-img-thumb").src = attachedImageBase64; document.getElementById("attached-img-name").innerText = `${file.name || 'Image'} (${(file.size / 1024).toFixed(1)} KB)`; document.getElementById("image-preview-bar").style.display = "flex"; }; reader.readAsDataURL(file); }
function removeAttachedImage() { attachedImageBase64 = null; document.getElementById("image-preview-bar").style.display = "none"; document.getElementById("attached-img-thumb").src = ""; }
// Direct clipboard paste support window.addEventListener("paste", function(e) { const items = (e.clipboardData || window.clipboardData).items; for (let item of items) { if (item.type.indexOf("image") !== -1) { const file = item.getAsFile(); loadImageFile(file); break; } } });
let activeAbortController = null;
function handleSendOrStop() { if (isGenerating) { stopGenerating(); } else { sendMessage(); } }
function stopGenerating() { if (activeAbortController) { try { activeAbortController.abort(); } catch (_) {} activeAbortController = null; } isGenerating = false; const sendBtn = document.getElementById("send-btn"); if (sendBtn) { sendBtn.innerText = "Send ↵"; sendBtn.style.background = "var(--accent)"; } }
async function sendMessage() { if (isGenerating) return; const input = document.getElementById("prompt-input"); const text = input.value.trim(); const currentImg = attachedImageBase64;
if (!text && !currentImg) return;
input.value = ""; input.style.height = "44px"; removeAttachedImage();
// Hide welcome card if present const welcome = document.getElementById("welcome-card"); if (welcome) welcome.remove();
// Append user bubble appendUserMessage(text, currentImg);
if (currentImg) { conversationHistory.push({ role: "user", content: [ { type: "text", text: text || "Please analyze and describe this image." }, { type: "image_url", image_url: { url: currentImg } } ] }); } else { conversationHistory.push({ role: "user", content: text }); }
// Create assistant container const { row, thinkingBody, htmlCanvas, rawSource, statsSpan } = createAssistantRow(); isGenerating = true; activeAbortController = new AbortController(); const sendBtn = document.getElementById("send-btn"); sendBtn.innerText = "Stop ⏹"; sendBtn.style.background = "#ef4444";
let accumulatedThought = ""; let accumulatedContent = "";
try { const response = await fetch("/api/chat/stream", { method: "POST", headers: { "Content-Type": "application/json" }, signal: activeAbortController.signal, body: JSON.stringify({ messages: conversationHistory, enable_thinking: appConfig.enable_thinking, reasoning_effort: appConfig.reasoning_effort || "low", do_sample: appConfig.do_sample, temperature: appConfig.temperature, top_p: appConfig.top_p, top_k: appConfig.top_k, min_p: appConfig.min_p, presence_penalty: appConfig.presence_penalty, repetition_penalty: appConfig.repetition_penalty, max_tokens: appConfig.max_tokens, system_prompt: appConfig.system_prompt }) });
const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); let streamBuffer = "";
while (true) { const { done, value } = await reader.read(); if (done) break;
streamBuffer += decoder.decode(value, { stream: true }); const lines = streamBuffer.split("\n"); // Keep the last segment in streamBuffer (it might be truncated or empty) streamBuffer = lines.pop();
for (const line of lines) { const trimmed = line.trim(); if (!trimmed.startsWith("data: ")) continue; const dataStr = trimmed.slice(6).trim(); if (!dataStr) continue;
let packet; try { packet = JSON.parse(dataStr); } catch (jsonErr) { console.warn("Skipping incomplete/malformed SSE chunk:", jsonErr, dataStr); continue; }
if (packet.type === "thought") { accumulatedThought += packet.content; thinkingBody.innerText = accumulatedThought; scrollToBottom(); } else if (packet.type === "content") { accumulatedContent += packet.content; if (accumulatedContent.includes("<think>")) { const tm = accumulatedContent.match(/<think>([\s\S]*?)(?:<\/think>|$)/i); if (tm && tm[1]) { thinkingBody.innerText = tm[1].trim(); } } renderHtmlView(htmlCanvas, rawSource, accumulatedContent); scrollToBottom(); } else if (packet.type === "done") { statsSpan.innerText = `⏱️ ${packet.elapsed}s | ⚡ ${packet.tok_per_sec} tok/s | 📊 ${packet.tokens} tokens`; conversationHistory.push({ role: "assistant", content: accumulatedContent }); } else if (packet.type === "error") { htmlCanvas.innerHTML = `<div style="color:#ef4444; padding:12px;"><strong>Error:</strong> ${packet.error}</div>`; } } }
// Process any residual trailing line in streamBuffer if (streamBuffer.trim().startsWith("data: ")) { try { const packet = JSON.parse(streamBuffer.trim().slice(6).trim()); if (packet.type === "done") { statsSpan.innerText = `⏱️ ${packet.elapsed}s | ⚡ ${packet.tok_per_sec} tok/s | 📊 ${packet.tokens} tokens`; conversationHistory.push({ role: "assistant", content: accumulatedContent }); } } catch (_) {} }
} catch (err) { if (err.name === "AbortError" || String(err).includes("aborted")) { statsSpan.innerText = (statsSpan.innerText ? statsSpan.innerText + " | " : "") + "⏹ Stopped by user"; conversationHistory.push({ role: "assistant", content: accumulatedContent }); } else { htmlCanvas.innerHTML = `<div style="color:#ef4444; padding:12px;"><strong>Network Error:</strong> ${err.message}</div>`; } } finally { isGenerating = false; activeAbortController = null; const sendBtn = document.getElementById("send-btn"); if (sendBtn) { sendBtn.innerText = "Send ↵"; sendBtn.style.background = "var(--accent)"; } } }
function appendUserMessage(text, imgSrc) { const list = document.getElementById("messages-list"); const row = document.createElement("div"); row.className = "message-row message-user"; let imgHtml = ""; if (imgSrc) { imgHtml = `<div style="margin-bottom:8px;"><img src="${imgSrc}" style="max-width:240px; max-height:180px; border-radius:8px; border:1px solid rgba(0,0,0,0.1); display:block; object-fit:cover;"></div>`; } row.innerHTML = `<div class="user-bubble">${imgHtml}${escapeHtml(text)}</div>`; list.appendChild(row); scrollToBottom(); }
function createAssistantRow() { const list = document.getElementById("messages-list"); const row = document.createElement("div"); row.className = "message-row message-assistant";
const showThinking = appConfig.enable_thinking;
row.innerHTML = ` <details class="thinking-box" ${showThinking ? 'open' : ''} style="${showThinking ? '' : 'display:none;'}"> <summary class="thinking-summary"> <span>🧠 Chain of Thought</span> <span style="margin-left:auto; font-size:0.75rem;">▼ Toggle</span> </summary> <div class="thinking-content">Thinking in progress...</div> </details> <div class="html-canvas">Generating visual presentation...</div> <div class="raw-source-view"></div> <div class="msg-footer"> <div class="msg-stats"><span>Generating...</span></div> <div class="msg-actions"> <button class="action-btn" onclick="toggleRawView(this)">👁️ View Source</button> <button class="action-btn" onclick="copyHtml(this)">📋 Copy HTML</button> </div> </div> `;
list.appendChild(row); scrollToBottom();
const thinkingBody = row.querySelector(".thinking-content"); const htmlCanvas = row.querySelector(".html-canvas"); const rawSource = row.querySelector(".raw-source-view"); const statsSpan = row.querySelector(".msg-stats span");
return { row, thinkingBody, htmlCanvas, rawSource, statsSpan }; }
function renderHtmlView(canvas, rawView, text) { // 1. Strip any thinking block from HTML canvas view let clean = text.replace(/<think>[\s\S]*?<\/think>/gi, "").trim(); clean = clean.replace(/<think>[\s\S]*$/gi, "").trim(); // 2. Strip code fences if model ever outputs them if (clean.startsWith("```html")) clean = clean.slice(7); if (clean.startsWith("```")) clean = clean.slice(3); if (clean.endsWith("```")) clean = clean.slice(0, -3); clean = clean.trim();
const startIdx = clean.indexOf('<div class="ai-view">'); if (startIdx !== -1) { clean = clean.slice(startIdx); } else if (!clean) { // If content is still in thinking phase canvas.innerHTML = '<div style="color:var(--text-sub); font-size:0.85rem; padding:16px 8px; display:flex; align-items:center; gap:8px;"><span>🧠</span><span>Thinking & formatting UI layout...</span></div>'; rawView.innerText = ""; return; }
rawView.innerText = clean; canvas.innerHTML = clean; }
function toggleRawView(btn) { const row = btn.closest(".message-assistant"); const canvas = row.querySelector(".html-canvas"); const raw = row.querySelector(".raw-source-view"); if (raw.style.display === "block") { raw.style.display = "none"; canvas.style.display = "block"; btn.innerText = "View Source"; } else { raw.style.display = "block"; canvas.style.display = "none"; btn.innerText = "View Preview"; } }
function copyHtml(btn) { const row = btn.closest(".message-assistant"); const raw = row.querySelector(".raw-source-view").innerText; navigator.clipboard.writeText(raw); const orig = btn.innerText; btn.innerText = "Copied! ✓"; setTimeout(() => btn.innerText = orig, 1500); }
function scrollToBottom() { const container = document.getElementById("chat-container"); container.scrollTop = container.scrollHeight; }
function escapeHtml(str) { return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); } </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593:root { --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; --font-mono: "JetBrains Mono", "Fira Code", Menlo, Monaco, Consolas, monospace; --bg-app: #f8fafc; --bg-card: #ffffff; --bg-subtle: #f1f5f9; --border-subtle: rgba(226, 232, 240, 0.8); --border-card: #e2e8f0; --text-main: #0f172a; --text-body: #334155; --text-muted: #64748b; --accent-color: #2563eb; --accent-bg: #eff6ff; --success-color: #059669; --success-bg: #ecfdf5; --success-border: #a7f3d0; --warning-color: #d97706; --warning-bg: #fffbeb; --warning-border: #fde68a; --danger-color: #dc2626; --danger-bg: #fef2f2; --danger-border: #fecaca; --info-color: #0284c7; --info-bg: #f0f9ff; --info-border: #bae6fd; --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.06), 0 2px 4px -2px rgba(0, 0, 0, 0.05); --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -4px rgba(0, 0, 0, 0.04); --radius-sm: 6px; --radius-md: 10px; --radius-lg: 14px;}
body { margin: 0; padding: 24px; background-color: var(--bg-app); font-family: var(--font-sans); color: var(--text-body); line-height: 1.6; -webkit-font-smoothing: antialiased;}
.ai-view { max-width: 880px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px;}
/* Card Foundation */.card { background: var(--bg-card); border: 1px solid var(--border-card); border-radius: var(--radius-lg); padding: 20px 24px; box-shadow: var(--shadow-sm); transition: box-shadow 0.2s ease, border-color 0.2s ease;}
/* Hero / TL;DR Summary Card */.summary-card { background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%); border: 1px solid var(--border-card); border-left: 5px solid var(--accent-color); border-radius: var(--radius-lg); padding: 20px 24px; box-shadow: var(--shadow-md);}
.summary-card .lead { font-size: 1.05rem; font-weight: 500; color: var(--text-main); margin: 10px 0 0 0; line-height: 1.6;}
/* Badges & Pills */.badge { display: inline-flex; align-items: center; gap: 5px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; padding: 3px 9px; border-radius: 9999px;}.badge-accent { background: var(--accent-bg); color: var(--accent-color); }.badge-success { background: var(--success-bg); color: var(--success-color); }.badge-warning { background: var(--warning-bg); color: var(--warning-color); }.badge-danger { background: var(--danger-bg); color: var(--danger-color); }.badge-info { background: var(--info-bg); color: var(--info-color); }
/* Typography */h1, h2, h3, h4 { color: var(--text-main); margin-top: 0; font-weight: 700; letter-spacing: -0.02em;}h2 { font-size: 1.3rem; margin-bottom: 12px; }h3 { font-size: 1.1rem; margin-bottom: 8px; }p { margin: 0 0 10px 0; }p:last-child { margin-bottom: 0; }
/* Grid Layouts (Bento) */.grid { display: grid; gap: 16px;}.grid-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }.grid-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }@media (max-width: 680px) { .grid-2, .grid-3 { grid-template-columns: 1fr; }}
/* Callout Blocks */.callout { border-radius: var(--radius-md); padding: 16px 20px; border-left: 4px solid; margin: 4px 0; font-size: 0.95rem;}.callout-header { font-weight: 700; display: flex; align-items: center; gap: 8px; margin-bottom: 6px;}.callout-info { background-color: var(--info-bg); border-color: var(--info-color); color: #0369a1;}.callout-warning { background-color: var(--warning-bg); border-color: var(--warning-color); color: #92400e;}.callout-danger { background-color: var(--danger-bg); border-color: var(--danger-color); color: #991b1b;}.callout-success { background-color: var(--success-bg); border-color: var(--success-color); color: #065f46;}
/* Stepper / Timeline */.stepper { display: flex; flex-direction: column; gap: 16px; position: relative; margin: 6px 0;}.step-item { display: flex; gap: 16px; align-items: flex-start;}.step-num { flex-shrink: 0; width: 32px; height: 32px; border-radius: 50%; background: var(--accent-bg); color: var(--accent-color); border: 2px solid var(--accent-color); display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.85rem;}.step-content { flex-grow: 1;}.step-content h4 { margin: 4px 0 6px 0; font-size: 1rem;}
/* Code Container (macOS style window) */.code-box { background: #0f172a; border-radius: var(--radius-md); overflow: hidden; box-shadow: var(--shadow-sm); margin: 8px 0;}.code-header { background: #1e293b; padding: 8px 14px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255, 255, 255, 0.05);}.code-dots { display: flex; gap: 6px;}.code-dots i { width: 10px; height: 10px; border-radius: 50%; display: inline-block;}.code-dots i:nth-child(1) { background: #ef4444; }.code-dots i:nth-child(2) { background: #f59e0b; }.code-dots i:nth-child(3) { background: #10b981; }.code-title { color: #94a3b8; font-family: var(--font-mono); font-size: 0.75rem; font-weight: 600; text-transform: uppercase;}.code-box pre { margin: 0; padding: 14px 16px; overflow-x: auto; font-family: var(--font-mono); font-size: 0.88rem; line-height: 1.5; color: #f1f5f9;}code { font-family: var(--font-mono); font-size: 0.88em; background: #e2e8f0; color: #0f172a; padding: 2px 6px; border-radius: 4px;}.code-box code { background: transparent; padding: 0; color: inherit;}
/* Metric / KPI Cards */.metric-group { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px;}.metric-card { background: var(--bg-card); border: 1px solid var(--border-card); border-radius: var(--radius-md); padding: 14px 18px; display: flex; flex-direction: column;}.metric-label { font-size: 0.8rem; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em;}.metric-value { font-size: 1.6rem; font-weight: 800; color: var(--text-main); letter-spacing: -0.03em; margin: 4px 0;}.metric-sub { font-size: 0.78rem; color: var(--text-muted);}
/* Modern Minimalist Table */.table-container { overflow-x: auto; border: 1px solid var(--border-card); border-radius: var(--radius-md); margin: 8px 0; background: var(--bg-card);}.modern-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 0.92rem;}.modern-table th { background: var(--bg-subtle); color: var(--text-muted); font-weight: 700; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.05em; padding: 10px 14px; border-bottom: 1px solid var(--border-card);}.modern-table td { padding: 12px 14px; border-bottom: 1px solid var(--border-subtle); color: var(--text-body);}.modern-table tr:last-child td { border-bottom: none;}.modern-table tr:hover td { background: #f8fafc;}/* Append Thinking Card component to theme.css */.thinking-card { background: var(--bg-subtle); border: 1px dashed var(--border-card); border-radius: var(--radius-lg); padding: 12px 18px; margin-bottom: 8px; transition: all 0.2s ease;}.thinking-card[open] { background: var(--bg-card); border-style: solid; border-color: #cbd5e1; box-shadow: var(--shadow-sm);}body.dark-mode .thinking-card { border-color: #374151; background: #11182788;}body.dark-mode .thinking-card[open] { background: #1f2937; border-color: #4b5563;}.thinking-header { display: flex; align-items: center; gap: 10px; cursor: pointer; user-select: none; font-size: 0.88rem; font-weight: 700; color: var(--text-muted); list-style: none; /* Hide default triangle */}.thinking-header::-webkit-details-marker { display: none;}.thinking-icon { font-size: 1.1rem;}.thinking-title { color: var(--text-main); flex-grow: 1;}.thinking-badge { font-size: 0.72rem; background: #ede9fe; color: #6d28d9; padding: 2px 8px; border-radius: 9999px; font-weight: 700;}body.dark-mode .thinking-badge { background: #4c1d9555; color: #c4b5fd;}.thinking-body { margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--border-subtle); font-size: 0.88rem; line-height: 1.6; color: var(--text-muted); font-family: var(--font-sans);}.thinking-step { margin-bottom: 8px;}.thinking-step strong { color: var(--text-main);}.thinking-math { font-family: var(--font-mono); background: var(--bg-subtle); padding: 2px 6px; border-radius: 4px; color: var(--text-main);}
/* Aliases for thinking and summary classes */.thinking { background: var(--bg-subtle); border: 1px dashed var(--border-card); border-radius: var(--radius-lg); padding: 12px 18px; margin-bottom: 12px; transition: all 0.2s ease;}.thinking[open] { background: var(--bg-card); border-style: solid; border-color: #cbd5e1; box-shadow: var(--shadow-sm);}body.dark-mode .thinking { border-color: #374151; background: #11182788;}body.dark-mode .thinking[open] { background: #1f2937; border-color: #4b5563;}
.summary { background: var(--bg-card); border: 1px solid var(--border-card); border-left: 5px solid var(--accent-color); border-radius: var(--radius-lg); padding: 20px 24px; box-shadow: var(--shadow-md); margin-top: 10px;}.summary .lead { font-size: 1.05rem; font-weight: 500; color: var(--text-main); margin: 10px 0 0 0; line-height: 1.6;}
/* Modern List System (Kills the Markdown / 90s bullet look) */.ai-view ul { list-style: none !important; padding-left: 0 !important; margin: 12px 0 !important; display: flex !important; flex-direction: column !important; gap: 8px !important;}
.ai-view ul li { position: relative !important; padding: 8px 14px 8px 30px !important; background: rgba(0, 0, 0, 0.02) !important; border-radius: var(--radius-sm, 8px) !important; border: 1px solid rgba(0, 0, 0, 0.05) !important; color: var(--text-body) !important; line-height: 1.5 !important; font-size: 0.92rem !important; transition: all 0.15s ease !important;}
.ai-view ul li:hover { background: rgba(37, 99, 235, 0.04) !important; border-color: rgba(37, 99, 235, 0.15) !important;}
.ai-view ul li::before { content: "" !important; position: absolute !important; left: 12px !important; top: 14px !important; width: 7px !important; height: 7px !important; border-radius: 50% !important; background: var(--accent-color, #2563eb) !important; box-shadow: 0 0 0 3px var(--accent-bg, rgba(37, 99, 235, 0.15)) !important;}
/* Grid Child Auto-Cardify: if model outputs bare <div> inside .grid, give it card polish */.grid > div:not(.card) { background: #f8fafc !important; border: 1px solid var(--border-card, #e2e8f0) !important; border-radius: var(--radius-md, 12px) !important; padding: 18px 20px !important; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02) !important;}
.grid > div:not(.card) h3 { margin-bottom: 12px !important; padding-bottom: 6px !important; border-bottom: 1px solid rgba(0, 0, 0, 0.06) !important;}
/* Auto-span single child in grid (Prevents blank ghost columns when model outputs only 1 child) */.grid > :only-child,.grid-2 > :only-child,.grid-3 > :only-child { grid-column: 1 / -1 !important;}
/* Grid Child Container Safety: Never allow child to burst out of grid track */.grid > div,.grid-2 > div,.grid-3 > div { min-width: 0 !important; box-sizing: border-box !important;}
/* Feature List & Item (Upgraded from old-school bullet points; clean vertical card flow) */.feature-list { display: flex !important; flex-direction: column !important; gap: 8px !important; margin: 10px 0 !important; width: 100% !important; box-sizing: border-box !important;}
.feature-item { display: flex !important; flex-direction: column !important; align-items: flex-start !important; gap: 6px !important; padding: 10px 14px !important; background: #ffffff !important; border-radius: var(--radius-sm, 8px) !important; border: 1px solid var(--border-card, #e2e8f0) !important; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02) !important; transition: all 0.15s ease !important; width: 100% !important; box-sizing: border-box !important;}
.feature-item:hover { border-color: #cbd5e1 !important; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.04) !important;}
.feature-item .badge { font-size: 0.72rem !important; padding: 2px 8px !important; line-height: 1.4 !important; display: inline-flex !important;}
.feature-item p { margin: 0 !important; font-size: 0.88rem !important; color: var(--text-body, #334155) !important; line-height: 1.5 !important; width: 100% !important;}
.feature-item:hover { border-color: #cbd5e1 !important; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.04) !important; transform: translateX(2px) !important;}
.feature-item .badge { flex-shrink: 0 !important; margin-top: 1px !important; font-size: 0.75rem !important;}
.feature-item p { margin: 0 !important; font-size: 0.92rem !important; color: var(--text-body, #334155) !important; line-height: 1.5 !important; flex-grow: 1 !important;}
answer { display: inline-block; font-family: var(--font-mono); font-weight: 800; font-size: 1.15rem; color: var(--accent-color); background: var(--accent-bg); border: 1px solid rgba(37, 99, 235, 0.25); padding: 2px 10px; border-radius: 6px; letter-spacing: -0.01em;}.gitattributes+24-9
chat_template.jinjaAdded+123
config.jsonAdded+83
configuration.jsonAdded+1
configuration_spark.pyAdded+118
generation_config.jsonAdded+15
merges.txtAdded
model.safetensorsAdded+3
modeling_spark.pyAdded+483
special_tokens_map.jsonAdded+6
tokenizer.jsonAdded
tokenizer_config.jsonAdded+14
vocab.jsonAdded
webui/config.jsonAdded+22
webui/requirements.txtAdded+4
webui/run_webui.shAdded+58
webui/server.pyAdded+442
webui/static/index.htmlAdded+1613
webui/static/theme.cssAdded+593