okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-141-fixb: Python, docs and bench fixes and portsef8071303

main
2.6 KiB69 linesraw
1#!/usr/bin/env python3
2"""Correctness check for the vision path: render a code word, ask the model to read it.
3
4This configuration runs the image encoder on the CPU (`VISION=cpu`), so this checks that
5path. The picture is rendered with Pillow (no downloaded assets), sent the way an
6OpenAI-compatible client sends one (an `image_url` with a `data:` URL), and the answer is
7compared with the code that was drawn.
8"""
9import argparse
10import base64
11import io
12import json
13import urllib.request
14from pathlib import Path
15
16from PIL import Image, ImageDraw, ImageFont
17
18CODE = "K7QX-4291"
19QUESTION = ("Read the code printed in the image and reply with that code only, "
20            "exactly as written, with no other words.")
21
22
23def render() -> Image.Image:
24    """A code word in black on white, big enough to be unambiguous at the encoder's 300 tokens."""
25    image = Image.new("RGB", (900, 260), "white")
26    ImageDraw.Draw(image).text((40, 60), CODE, fill="black", font=ImageFont.load_default(size=110))
27    return image
28
29
30def main():
31    parser = argparse.ArgumentParser(description=__doc__)
32    parser.add_argument("--url", default="http://127.0.0.1:8080")
33    parser.add_argument("--out", type=Path, default=Path("/data/bench64"))
34    args = parser.parse_args()
35    args.out.mkdir(parents=True, exist_ok=True)
36
37    image = render()
38    image.save(args.out / "image-check.png")
39    buffer = io.BytesIO()
40    image.save(buffer, format="PNG")
41    data_url = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
42
43    body = json.dumps({
44        "model": "strata",
45        "messages": [{"role": "user", "content": [
46            {"type": "text", "text": QUESTION},
47            {"type": "image_url", "image_url": {"url": data_url}},
48        ]}],
49        "temperature": 0,
50        "reasoning_effort": "none",
51        "max_tokens": 64,
52    }).encode()
53
54    request = urllib.request.Request(args.url + "/v1/chat/completions", data=body,
55                                     headers={"Content-Type": "application/json"})
56    with urllib.request.urlopen(request, timeout=900) as response:
57        payload = json.load(response)
58    answer = payload["choices"][0]["message"]["content"].strip()
59    with urllib.request.urlopen(args.url + "/metrics", timeout=30) as response:
60        engine = json.load(response)["requests"][0]
61
62    result = {"expected": CODE, "answer": answer, "found": CODE in answer,
63              "usage": payload.get("usage"), "engine": engine}
64    (args.out / "image-check.json").write_text(json.dumps(result, indent=2) + "\n")
65    print(json.dumps(result, indent=2))
66
67
68if __name__ == "__main__":
69    main()