Files
alzeo/clipstral-server.py
T

276 lines
13 KiB
Python

#!/usr/bin/env python3
"""The Clipstral lane's server: Mistral's Multimodal Embed 1B on the CPU, POST /v1/embeddings on loopback.
Texts and images, in one space of 1,024 dimensions, each vector of norm 1. The request is the one of Mistral's own
embeddings API (docs.mistral.ai/api/endpoint/embeddings, read on 2026-12-01): `input` is a string, an image chunk
({"type": "image_url", "image_url": "data:image/png;base64,..."}, or "image_url": {"url": ...}), or a list of both. A
string that is the data: URL of an image is that image too, for the clients whose `input` holds strings alone (OpenAI's
SDK, LiteLLM). An image comes inside the request, in base64: the lane reaches no network, and an http URL is refused.
python3 -I clipstral-server.py --model-id <the snapshot's folder> [--host 127.0.0.1] [--port 30030] [--threads 10]
[--products bf16]
The proxy relays it the requests that name this model (docs/clipstral-lane.md); its routes, its batches and their turns are
vectors_server.py's. Of an image's file the decoder gets its pixels' part alone: what its metadata costs to read is its
sender's to choose.
"""
import base64
import io
import os
import re
import struct
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # python -I leaves its folder out
from vectors_server import MAX_INPUTS, Bad, Engine, Lane, main # noqa: E402
NAME = "mistral-multimodal-embed-1b"
DIM = 1024
MAX_IMAGE = 20 * 1024 * 1024 # of one image's file
MAX_PIXELS = 50_000_000 # of one image, decoded
MAX_SIDE = 65_535 # of one image, JPEG's own: the resize's weights are as wide as it
MAX_PARTS = 100_000 # segments, chunks or blocks of one image's file: what is read of it costs its size, not their number
MAX_SCANS = 100 # of one JPEG: a progressive one has ten or so, and each costs a pass over every pixel
FORMATS = ("PNG", "JPEG", "WEBP", "GIF")
NOT_PIXELS = {*range(0xE1, 0xEE), 0xEF, 0xFE} # a JPEG's segments no pixel is read with: EXIF, ICC, XMP, comments and the like
TURNS = {2: "FLIP_LEFT_RIGHT", 3: "ROTATE_180", 4: "FLIP_TOP_BOTTOM", 5: "TRANSPOSE", 6: "ROTATE_270", 7: "TRANSVERSE",
8: "ROTATE_90"} # what shows an image upright, by the orientation its EXIF says
DATA_URL = re.compile(r"data:image/[a-z0-9.+-]{1,64}(?:;[a-z0-9=._+-]{1,64}){0,8};base64,", re.IGNORECASE)
# -- the request -----------------------------------------------------------------------------------------------------------
def image_of(url, where):
"""The bytes of a data: URL."""
m = DATA_URL.match(url)
if not m:
raise Bad(f"{where}: image_url takes the image itself, as a data: URL in base64 (data:image/png;base64,...): "
"this lane reaches no network")
try:
return base64.b64decode("".join(url[m.end():].split()), validate=True)
except ValueError:
raise Bad(f"{where}: the data: URL is not valid base64") from None
def inputs_of(req):
"""What a request asks to embed, in its order: ("text", str) and ("image", bytes)."""
given = req.get("input")
if isinstance(given, (str, dict)):
given = [given]
if not isinstance(given, list) or not given:
raise Bad("'input' must be a string, an image chunk, or a list of them, and not empty")
if len(given) > MAX_INPUTS:
raise Bad(f"'input' holds {len(given)} entries, over {MAX_INPUTS}")
out = []
for i, x in enumerate(given):
where = f"input[{i}]"
if isinstance(x, dict) and x.get("type") == "text":
x = x.get("text")
if isinstance(x, str):
if DATA_URL.match(x):
out.append(("image", image_of(x, where)))
elif x.strip():
out.append(("text", x))
else:
raise Bad(f"{where} is an empty text")
elif isinstance(x, dict) and x.get("type") == "image_url":
url = x.get("image_url")
url = url.get("url") if isinstance(url, dict) else url
if not isinstance(url, str):
raise Bad(f"{where}: image_url must be a string, or an object with a 'url'")
out.append(("image", image_of(url, where)))
elif isinstance(x, (int, list)):
raise Bad(f"{where}: token ids are not taken (another model's ids would mean other words here): send the text")
else:
raise Bad(f"{where} must be a string or an image chunk ({{\"type\": \"image_url\", ...}})")
return out
def wants(req):
"""How the vectors are written: "float" or "base64". A vector this model does not make is refused, never approximated."""
for field in ("dimensions", "output_dimension"):
if req.get(field) not in (None, DIM):
raise Bad(f"'{field}' is {req[field]!r}: this model's vectors have {DIM} dimensions")
if req.get("output_dtype") not in (None, "float"):
raise Bad(f"'output_dtype' is {req['output_dtype']!r}: this lane writes floats")
fmt = req.get("encoding_format") or "float"
if fmt not in ("float", "base64"):
raise Bad(f"'encoding_format' is {fmt!r}: float or base64")
return fmt, None
# -- an image's file -------------------------------------------------------------------------------------------------------
# Pillow reads every piece of metadata of a file it opens, and some of them cost much more than they weigh: an EXIF block of
# 320 KB whose entries all point at the same bytes takes 8 GB, a GIF's comment its length squared (review of v1.60.0).
def upright(tiff):
"""The orientation an EXIF block says, 1 to 8, or None: that entry of its first directory, and nothing else of it."""
try:
order = {b"II*\0": "<", b"MM\0*": ">"}[bytes(tiff[:4])]
at = struct.unpack_from(order + "I", tiff, 4)[0]
for i in range(min(struct.unpack_from(order + "H", tiff, at)[0], 512)):
tag, kind, count, value = struct.unpack_from(order + "HHIH", tiff, at + 2 + 12 * i)
if tag == 0x0112:
return value if (kind, count) == (3, 1) and 1 <= value <= 8 else None
except (KeyError, struct.error):
pass
return None
# a marker after a JPEG's coded pixels: no stuffed 0xFF, no restart, no fill byte
MARK = re.compile(rb"\xff([^\x00\xd0-\xd7\xff])")
def end_of_jpeg(raw, i):
"""Where a JPEG ends, read from its first scan: at its end mark, as a decoder reads it. What follows is none of its
pixels: a phone's "motion photo" has its film there, in which the two bytes of a scan come by chance, and over 100
scans were counted in it (review of v1.60.0)."""
scans = 0
for _ in range(MAX_PARTS):
mark = MARK.search(raw, i)
if not mark:
return len(raw) # cut short: its decoder's to say
kind, i = mark.group(1)[0], mark.end()
if kind == 0xD9:
return i
scans += kind == 0xDA
if scans > MAX_SCANS:
raise ValueError("more scans than a JPEG has")
if kind >= 0xC0 and kind != 0xD8: # what lies in its segment is no marker
i += int.from_bytes(raw[i:i + 2], "big")
raise ValueError("more segments than a JPEG has")
def bare_jpeg(raw):
keep, turn, i = [raw[:2]], None, 2
for _ in range(MAX_PARTS):
i = raw.index(b"\xff", i)
while raw[i + 1] == 0xFF: # a marker may be preceded by any number of these
i += 1
kind, size = raw[i + 1], int.from_bytes(raw[i + 2:i + 4], "big")
if kind == 0xDA: # the first scan: from here to its end the file is the decoder's
return b"".join([*keep, raw[i:end_of_jpeg(raw, i)]]), turn
if kind < 0xC0 or 0xD0 <= kind <= 0xD9: # alone, with no segment behind it
i += 2
continue
part, i = raw[i:i + 2 + size], i + 2 + size
if kind == 0xE1 and turn is None and part[4:10] == b"Exif\0\0":
turn = upright(part[10:])
if kind not in NOT_PIXELS:
keep.append(part)
raise ValueError("more segments than a JPEG has")
def bare_png(raw):
keep, turn, i = [raw[:8]], None, 8
for _ in range(MAX_PARTS):
size, kind = int.from_bytes(raw[i:i + 4], "big"), raw[i + 4:i + 8]
if kind in (b"IHDR", b"PLTE", b"tRNS", b"IDAT", b"IEND"):
keep.append(raw[i:i + 12 + size])
elif kind == b"eXIf" and turn is None:
turn = upright(raw[i + 8:i + 8 + min(size, 65536)])
i += 12 + size
if kind == b"IEND" or i >= len(raw):
return b"".join(keep), turn
raise ValueError("more chunks than a PNG has")
def bare_gif(raw):
"""Its first frame: the rest of it, and its comments, are left."""
def table(flags):
return 6 << (flags & 7) if flags & 0x80 else 0
i = 13 + table(raw[10])
keep, left = [raw[:i]], MAX_PARTS
while left > 0:
start, kind, label = i, raw[i], raw[i + 1]
if kind not in (0x21, 0x2C):
raise ValueError("no frame")
i += 2 if kind == 0x21 else 11 + table(raw[i + 9])
while raw[i] and left > 0:
i, left = i + raw[i] + 1, left - 1
i, left = i + 1, left - 1
if kind == 0x2C or label == 0xF9: # the frame, and what says which of its colours is transparent
keep.append(raw[start:i])
if kind == 0x2C:
return b"".join(keep) + b";", None
raise ValueError("more blocks than a GIF's first frame has")
def bare(raw):
"""(the format, the file with what its pixels need alone, the orientation it says). An EXIF block of a WebP is read
once it is opened, whose decoder takes it as it comes."""
if raw[:3] == b"\xff\xd8\xff":
return ("JPEG", *bare_jpeg(raw))
if raw[:8] == b"\x89PNG\r\n\x1a\n":
return ("PNG", *bare_png(raw))
if raw[:6] in (b"GIF87a", b"GIF89a"):
return ("GIF", *bare_gif(raw))
if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
return "WEBP", raw, None
raise ValueError("no format this lane reads")
# -- the model -------------------------------------------------------------------------------------------------------------
class Clipstral(Engine):
"""Clipstral, its texts and its images."""
def load(self, folder):
import clipstral_model
self.lib = clipstral_model
return clipstral_model.Clipstral.load(folder)
def opened(self, raw, where):
"""An image of the request by its header, nothing of it decoded and none of it kept open: its file with the turn its
EXIF asks for, as any viewer shows it (a phone writes a portrait on its side), and the sides the model takes it
at."""
from PIL import Image
Image.MAX_IMAGE_PIXELS = None # the checks below stand in its place, with their words
if len(raw) > MAX_IMAGE:
raise Bad(f"{where} is a file of {len(raw)} bytes, over {MAX_IMAGE // (1024 * 1024)} MiB")
try:
kind, clean, turn = bare(raw)
with Image.open(io.BytesIO(clean), formats=(kind,)) as im:
w, h = im.size
if kind == "WEBP":
turn = upright((im.info.get("exif") or b"")[:65536].removeprefix(b"Exif\0\0"))
except MemoryError:
raise
except Exception: # noqa: BLE001 (what a decoder raises on a file that is not one)
raise Bad(f"{where} is not an image this lane reads ({', '.join(FORMATS)})") from None
if not w * h:
raise Bad(f"{where} is {w}x{h}: it holds nothing")
if w * h > MAX_PIXELS or max(w, h) > MAX_SIDE:
raise Bad(f"{where} is {w}x{h}, over {MAX_PIXELS // 1_000_000} million pixels or {MAX_SIDE:,} on a side")
return (kind, clean, turn), self.lib.sides(*((h, w) if turn in (5, 6, 7, 8) else (w, h)))
def decoded(self, kind, clean, turn):
"""An image of the request, whole and upright. A gray one of 16 bits is brought to 8: Pillow makes it white."""
from PIL import Image
im = Image.open(io.BytesIO(clean), formats=(kind,))
im.load()
if im.mode.startswith("I"):
im = im.convert("I").point(lambda v: v * (1 / 257)).convert("L")
return im.transpose(Image.Transpose[TURNS[turn]]) if turn in TURNS else im
def images(self, some, between=None):
"""The vectors of images of one size, [(where, what opened() gave)]: decoded one by one, so one image is held whole
at a time. between() is called after each, and after each layer."""
ready = []
for where, what in some:
try:
im = self.decoded(*what)
except MemoryError:
raise
except Exception as e: # noqa: BLE001 (what a decoder raises on a file that is not whole)
raise Bad(f"{where} cannot be read whole: {type(e).__name__}") from None
ready.append(self.lib.fit(im))
del im
if between:
between()
return self.numbers(self.model.images(ready, between))
LANE = Lane(name=NAME, owner="mistralai", server="qwen38-clipstral", port=30030, engine=Clipstral, inputs_of=inputs_of, wants=wants,
about="the Clipstral lane's server (see the module docstring)")
if __name__ == "__main__":
main(LANE)