Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
coli chat: sixel with the picture's own palette, and /save
JustVugg2444d7a7f95b
diff --git a/c/coli b/c/coliindex 03b00f20..af4f0ef5 100755--- a/c/coli+++ b/c/coli@@ -2007,6 +2007,7 @@ IMAGE_CHAT_COMMANDS = {"steps": "N denoising steps (more is slower and usually cleaner)","seed": "N|random fix the seed to reproduce an image, or a new one each time","render": "MODE how images are drawn: kitty | iterm | sixel | blocks | none",+ "save": "[PATH] a copy of the last image: a folder, or a file name (.png is added)","help": " this list","quit": " leave (also :q)",}@@ -2246,9 +2247,10 @@ def image_settings(a, info):if problem: sys.exit(f"{C.yel}--seed: {problem}{C.r}")return {"width": width, "height": height, "steps": steps, "seed": seed}-def generate_image(backend, prompt, settings, protocol, out=None, stream=None):+def generate_image(backend, prompt, settings, protocol, out=None, stream=None, last=None):"""One image: progress, the picture drawn in the terminal, the PNG on disk.- Returns the saved path, or None when it was cancelled or failed (said)."""+ Returns the saved path, or None when it was cancelled or failed (said).+ `last`, when given, is filled with the PNG and where it went, for /save."""import term_imagefrom image_engine import (ImageCancelled, ImageEngineError, random_seed, save_png,image_dir)@@ -2297,10 +2299,41 @@ def generate_image(backend, prompt, settings, protocol, out=None, stream=None):print(f" {C.dgray}└─ {result['width']}x{result['height']} · seed {result['seed']} · "f"{result['steps']} steps · {elapsed:.0f}s{(' (' + parts + ')') if parts else ''}{C.r}",file=stream)+ if last is not None:+ last.update(png=result["png"], path=path, prompt=prompt, seed=result["seed"])if path:print(f" {C.grn}✓{C.r} saved {path}\n", file=stream)return path++def save_last_image(last, where):+ """/save: the last image, where the user says. A folder keeps the automatic+ name, a name gets .png when it has no extension, a Windows path pasted into+ WSL is translated like an attachment's, and an existing file is never+ overwritten: the images folder already holds every picture, so /save only+ ever adds a copy. Returns (path, None) or (None, why)."""+ if not last.get("png"):+ return None, "no image yet: describe one first"+ if not where:+ return (last["path"], None) if last.get("path") else (None, "give a path: /save PATH")+ target = to_local_path(where)+ if os.path.isdir(target):+ name = os.path.basename(last["path"]) if last.get("path") else f"colibri-s{last['seed']}.png"+ target = os.path.join(target, name)+ elif not os.path.splitext(target)[1]:+ target += ".png"+ if os.path.exists(target):+ return None, f"{target} already exists: choose another name"+ folder = os.path.dirname(os.path.abspath(target))+ if not os.path.isdir(folder):+ return None, f"no such folder: {folder}"+ try:+ with open(target, "xb") as handle:+ handle.write(last["png"])+ except OSError as error:+ return None, f"cannot write {target}: {error}"+ return target, None+def image_repl(a, backend, model_id):"""coli chat for an image model: every line is a prompt, every answer a picture."""import term_image@@ -2312,7 +2345,7 @@ def image_repl(a, backend, model_id):print(f" {C.grn}✦ {model_id}{C.r} {C.dim}· {backend.mode} · images are saved to "f"{image_dir()}{C.r}")print(f" {C.dim}describe an image and press Enter · Ctrl-C stops it · /size /steps /seed · "- f"/help · :q exits{C.r}")+ f"/save · /help · :q exits{C.r}")print(f" {C.dim}{settings['width']}x{settings['height']} · {settings['steps']} steps · seed "f"{settings['seed'] if settings['seed'] is not None else 'random'} · drawn with "f"{protocol} ({why}){C.r}\n")@@ -2321,6 +2354,7 @@ def image_repl(a, backend, model_id):{"size": presets, "seed": ["random"],"render": list(term_image.PROTOCOLS)})w = term_w() - 4+ last = {} # the last image, for /savewhile True:if TTY:print(f" {C.dgray}╭{'─'*w}╮{C.r}")@@ -2375,6 +2409,12 @@ def image_repl(a, backend, model_id):if problem: print(f" {C.yel} {problem}, or /seed random{C.r}\n"); continuesettings["seed"] = seedprint(f" {C.dim}✦ seed {seed}: the same prompt now gives the same image{C.r}\n"); continue+ if name == "save":+ path, why = save_last_image(last, rest.strip())+ if why: print(f" {C.yel} {why}{C.r}\n")+ elif rest.strip(): print(f" {C.grn}✓{C.r} saved {path}\n")+ else: print(f" {C.dim}✦ the last image is at {path} (/save PATH for a copy elsewhere){C.r}\n")+ continueif name == "render":choice = rest.strip().lower()if choice not in term_image.PROTOCOLS:@@ -2382,7 +2422,7 @@ def image_repl(a, backend, model_id):protocol = choiceprint(f" {C.dim}✦ images drawn with {protocol}{C.r}\n"); continueprint(f"\n {C.teal}◆ colibri{C.r}")- generate_image(backend, msg, settings, protocol)+ generate_image(backend, msg, settings, protocol, last=last)if not backend.alive:print(f" {C.yel}the engine is gone; start coli chat again{C.r}"); breakdiff --git a/c/term_image.py b/c/term_image.pyindex f159337f..4ade1a0d 100644--- a/c/term_image.py+++ b/c/term_image.py@@ -385,24 +385,6 @@ def render_iterm(png, columns, indent=" ", name="colibri.png", env=None):_BAYER4 = (0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5)-_LEVELS = (6, 7, 6) # 252 colours: sixel terminals allow 256---def _sixel_tables():- tables = []- for c, levels in enumerate(_LEVELS):- weight = (_LEVELS[1] * _LEVELS[2], _LEVELS[2], 1)[c]- step = 255 / (levels - 1)- per_threshold = []- for d in _BAYER4:- bias = (d + 0.5) / 16 - 0.5- per_threshold.append([min(levels - 1, max(0, int(v / step + 0.5 + bias))) * weight- for v in range(256)])- tables.append(per_threshold)- return tables---_SIXEL_TABLES = None_SIXEL_CHARS = bytes(range(63, 127))_SIXEL_RUN = re.compile(r"(.)\1{3,}")@@ -412,40 +394,86 @@ def _run_length(match):return f"!{len(run)}{run[0]}"+def _median_cut(histogram, colours):+ """Up to `colours` boxes over a {15-bit colour: count} histogram, cut where+ the pixels are: each time the box with the widest spread (weighted by how+ many pixels it holds) is split at the weighted median of its widest axis.+ Returns (palette of 8-bit RGB tuples, {15-bit colour: palette index})."""+ def spread(box):+ best = None+ for shift in (10, 5, 0):+ values = [(key >> shift) & 31 for key, _count in box]+ extent = max(values) - min(values)+ if best is None or extent > best[0]:+ best = (extent, shift)+ return best++ boxes = [list(histogram.items())]+ while len(boxes) < colours:+ scored = []+ for index, box in enumerate(boxes):+ if len(box) < 2:+ continue+ extent, shift = spread(box)+ if extent:+ scored.append((extent * sum(count for _key, count in box), index, shift))+ if not scored:+ break+ _score, index, shift = max(scored)+ box = sorted(boxes.pop(index), key=lambda item: (item[0] >> shift) & 31)+ half, running, cut = sum(count for _key, count in box) / 2, 0, 1+ for position, (_key, count) in enumerate(box):+ running += count+ if running >= half:+ cut = min(max(position + 1, 1), len(box) - 1)+ break+ boxes += [box[:cut], box[cut:]]+ palette, lookup = [], {}+ for index, box in enumerate(boxes):+ total = sum(count for _key, count in box) or 1+ channel = []+ for shift in (10, 5, 0):+ mean = sum((((key >> shift) & 31) * 8 + 4) * count for key, count in box) / total+ channel.append(int(mean + 0.5))+ palette.append(tuple(channel))+ for key, _count in box:+ lookup[key] = index+ return palette, lookup++def render_sixel(pixels, width, height, channels, max_width_px, max_height_px=None,indent=" "):- """DEC sixel with a fixed 6x7x6 palette and a 4x4 ordered dither.-- A fixed palette costs nothing to choose and never needs a second pass over- the image; the dither hides the banding it would otherwise leave in the- smooth gradients generated images are full of. Bands of six rows are+ """DEC sixel with a palette chosen from the picture itself.++ A fixed palette (the first version: 6x7x6 colours and a 4x4 ordered dither)+ showed as grain all over a photograph. Here the 255 colours come from a+ median cut of the picture's own 15-bit histogram, and each pixel takes the+ colour of the box its 15-bit value fell in, so no nearest-colour search runs+ per pixel. A light 4x4 ordered offset before the 15-bit truncation keeps the+ smooth gradients of generated images from banding. Bands of six rows areencoded colour by colour with run-length compression."""- global _SIXEL_TABLES- if _SIXEL_TABLES is None:- _SIXEL_TABLES = _sixel_tables()max_height_px = max_height_px or 10**6new_width, new_height = fit(width, height, max_width_px, max_height_px)small = resize(pixels, width, height, channels, new_width, new_height)rgb = flatten(small, new_width, new_height, channels)- red, green, blue = _SIXEL_TABLES- index = bytearray(new_width * new_height)+ keys = [0] * (new_width * new_height)+ histogram = {}for y in range(new_height):row_base = y * new_width- threshold_row = (y & 3) * 4+ bayer_row = (y & 3) * 4for x in range(new_width):- d = threshold_row + (x & 3)+ offset = _BAYER4[bayer_row + (x & 3)] >> 1 # 0..7, under one 5-bit stepp = (row_base + x) * 3- index[row_base + x] = (red[d][rgb[p]] + green[d][rgb[p + 1]] +- blue[d][rgb[p + 2]])- used = set(index)+ key = (min(255, rgb[p] + offset) >> 3) << 10 | (min(255, rgb[p + 1] + offset) >> 3) << 5 \+ | (min(255, rgb[p + 2] + offset) >> 3)+ keys[row_base + x] = key+ histogram[key] = histogram.get(key, 0) + 1+ palette, lookup = _median_cut(histogram, 255)+ index = bytes(lookup[key] for key in keys)out = [indent, "\x1bPq", f'"1;1;{new_width};{new_height}']- levels = _LEVELS- for colour in sorted(used):- r = colour // (levels[1] * levels[2])- g = colour // levels[2] % levels[1]- b = colour % levels[2]- out.append(f"#{colour};2;{r * 100 // (levels[0] - 1)};{g * 100 // (levels[1] - 1)};"- f"{b * 100 // (levels[2] - 1)}")+ for colour in sorted(set(index)):+ r, g, b = palette[colour]+ out.append(f"#{colour};2;{r * 100 // 255};{g * 100 // 255};{b * 100 // 255}")translate = bytes.maketrans(bytes(range(64)), _SIXEL_CHARS)for band in range(0, new_height, 6):masks = {}diff --git a/c/tests/test_qwen_image_cli.py b/c/tests/test_qwen_image_cli.pyindex 26908b0d..f1d51b83 100644--- a/c/tests/test_qwen_image_cli.py+++ b/c/tests/test_qwen_image_cli.py@@ -128,7 +128,7 @@ class LauncherTest(unittest.TestCase):def test_image_commands_share_the_completion_machinery(self):self.assertEqual(set(self.cli.IMAGE_CHAT_COMMANDS),- {"size", "steps", "seed", "render", "help", "quit"})+ {"size", "steps", "seed", "render", "save", "help", "quit"})self.assertEqual(self.cli.chat_command("/size 1024x576"), ("size", "1024x576"))@@ -220,6 +220,30 @@ class CommandsTest(unittest.TestCase):self.assertIn("1024x576", result.stdout) # /size lists the presetsself.assertIn("seed 7", result.stdout)+ def test_chat_save_copies_the_last_image(self):+ # The picture is always saved in the images folder; /save adds a copy+ # where the user says: a folder keeps the name, a bare name gets .png,+ # and an existing file is never overwritten.+ import tempfile+ with tempfile.TemporaryDirectory() as elsewhere:+ named = Path(elsewhere) / "poster"+ script = (f"/save {named}\n" # nothing yet+ "/size 256x256\n/steps 2\n/seed 9\nan owl on a branch\n"+ f"/save\n/save {named}\n/save {named}\n/save {elsewhere}\n"+ f"/save {elsewhere}/missing/x.png\n:q\n")+ result = run_coli(["chat", "--model", self.model, "--no-attach"], self.env,+ stdin=script)+ self.assertEqual(result.returncode, 0, result.stderr)+ auto = sorted(self.images.glob("*.png"))+ self.assertEqual(len(auto), 1, result.stdout)+ self.assertIn("no image yet", result.stdout)+ self.assertIn(f"the last image is at {auto[0]}", result.stdout)+ copy = named.with_suffix(".png")+ self.assertEqual(copy.read_bytes(), auto[0].read_bytes())+ self.assertIn("already exists", result.stdout)+ self.assertEqual((Path(elsewhere) / auto[0].name).read_bytes(), auto[0].read_bytes())+ self.assertIn("no such folder", result.stdout)+def test_chat_attached_to_a_running_serve(self):from openai_server import APIServerengine = image_engine.ImageEngine(STUB, self.model, env=stub_env(),diff --git a/docs/qwen-image.md b/docs/qwen-image.mdindex 2fbd5e7e..5c01379c 100644--- a/docs/qwen-image.md+++ b/docs/qwen-image.md@@ -96,6 +96,7 @@ Commands (TAB completes them, and the sizes after `/size`):| `/seed N` | fixed seed: the same prompt then gives the same image || `/seed random` | a new seed for every image (the default) || `/render MODE` | how images are drawn: `kitty`, `iterm`, `sixel`, `blocks`, `none` |+| `/save [PATH]` | a copy of the last image where you want it: a folder (the name is kept) or a file name (`.png` is added); never overwrites. Alone, it says where the image already is || `/help`, `/quit` | the list, and leave (`:q` works too) |The first size, steps and seed can also be given as flags:@@ -142,7 +143,9 @@ time, the prompt and the seed:````COLI_IMAGE_DIR=/some/folder` puts them elsewhere. Nothing is overwritten: a-second image with the same name gets `-2`, `-3`, ...+second image with the same name gets `-2`, `-3`, ... The path is printed under+every image, and `/save PATH` in `coli chat` keeps a copy of the last one where+you choose (a Windows path such as `C:\Users\me\Desktop` works from WSL).## Terminal support