File size: 11,671 Bytes
aa204f5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Smoke test of a running GLM-OCR server (standard library only; Python 3.9+, no numpy / PIL).
python3 code/tt_glmocr/server/smoke_test.py --url http://127.0.0.1:20000 --wait 1800 \\
[--manifest <out>/glm-ocr/tt_kernel_manifest.json] [--profile NAME] [--out smoke.json] [--allow-fake]
Checks (every failure is collected; prints ONE line ``PASS ...`` / ``FAIL ...``; exit code 0 / 1):
* ``/health`` ok (waiting up to ``--wait`` s); ``/info`` and ``/v1/models`` answer; ``/info`` reports ETH dispatch
and the 12x10 grid (``--allow-fake``: a ``GLMOCR_BACKEND=fake`` server instead) and, with ``--manifest``, the
pinned ``GLMOCR_ENGINE`` / ``GLMOCR_DISPATCH`` / ``GLMOCR_MAX_IMAGE_TOKENS`` / ``GLMOCR_PRECISION``;
* every shipped sample (``samples/*``) through ``POST /ocr`` with its task: HTTP 200, stop token reached, text not
empty, the character error rate vs the sample's ``expected_text`` <= its ``max_cer`` (unless PENDING), the same
request twice gives the same text (greedy determinism), the JSON-body form gives the same text;
* ``POST /v1/chat/completions`` (data URL) equals ``/ocr`` for the text sample; SSE streaming of both routes: the
deltas join to the final text; ``format=markdown`` of the formula is a ``$$`` block; ``task=extract`` with a
schema returns parsed JSON with the schema's keys;
* refusals: 400 for an unknown task / format / field, temperature 5, top_k 1000, n=2; 415 for a text/plain body.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any, Dict, List
HERE = Path(__file__).resolve().parent
SAMPLES = HERE.parent / "samples"
def _load(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
sys.modules[name] = mod
spec.loader.exec_module(mod)
return mod
gc = _load("glmocr_client", HERE / "client.py")
def edit_distance(a: str, b: str) -> int:
prev = list(range(len(b) + 1))
for i, x in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, y in enumerate(b, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y))
prev = cur
return prev[-1]
def cer(hyp: str, ref: str) -> float:
return (edit_distance(hyp, ref) / len(ref)) if ref else float(bool(hyp))
def samples() -> List[Dict[str, Any]]:
out = []
for d in sorted(p for p in SAMPLES.iterdir() if (p / "sample.json").is_file()):
m = json.loads((d / "sample.json").read_text())
m["name"] = d.name
m["bytes_data"] = (d / m["file"]).read_bytes()
out.append(m)
return out
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:20000")
ap.add_argument("--wait", type=float, default=1800.0)
ap.add_argument("--manifest")
ap.add_argument("--profile")
ap.add_argument("--out")
ap.add_argument("--allow-fake", action="store_true")
args = ap.parse_args()
url = args.url.rstrip("/")
fails: List[str] = []
m: Dict[str, Any] = {}
t0 = time.time()
while True:
st, h = gc.get(url, "/health", 10)
if st == 200 and isinstance(h, dict) and h.get("status") == "ok":
break
if isinstance(h, dict) and h.get("status") == "error":
print(f"FAIL server start-up error: {h.get('error')}")
return 1
if time.time() - t0 > args.wait:
print(f"FAIL /health not ok after {args.wait:.0f} s ({st}, {h})")
return 1
time.sleep(5)
m["ready_after_s"] = round(time.time() - t0, 1)
st, info = gc.get(url, "/info")
if st != 200 or not isinstance(info, dict):
fails.append(f"/info answered {st}")
info = {}
fake = info.get("backend") == "fake"
if fake and not args.allow_fake:
fails.append("the server runs the fake backend (use --allow-fake for a host test)")
dev = info.get("device") or {}
if not fake and (dev.get("dispatch") != "eth" or dev.get("grid") != "12x10"):
fails.append(f"device {dev.get('dispatch')} {dev.get('grid')} (expected eth 12x10)")
if args.manifest:
man = json.load(open(args.manifest))
c = man.get("container") or {}
envs = dict(((c.get("serve") or {}).get("env") or {}))
prof = args.profile or c.get("default_profile")
for p in c.get("serve_profiles") or []:
if p.get("name") == prof:
envs.update(p.get("env") or {})
conf = info.get("configuration") or {}
for k in ("GLMOCR_ENGINE", "GLMOCR_DISPATCH", "GLMOCR_MAX_IMAGE_TOKENS", "GLMOCR_PRECISION"):
want, got = str(envs.get(k, "")), str(conf.get(k, ""))
if not want or k not in conf:
continue
if k in ("GLMOCR_ENGINE", "GLMOCR_PRECISION"):
if not set(x for x in want.split(",") if x) <= set(got.split(",")):
fails.append(f"{k}: served {got!r}, package pins {want!r}")
elif want != got:
fails.append(f"{k}: served {got!r}, package pins {want!r}")
st, mods = gc.get(url, "/v1/models")
if st != 200:
fails.append(f"/v1/models answered {st}")
texts: Dict[str, str] = {}
smp = samples()
if not smp:
fails.append(f"no samples under {SAMPLES}")
for s in smp:
n = s["name"]
t1 = time.time()
st, body, _ = gc.ocr(url, s["bytes_data"], task=s["task"])
m[f"{n}_ms"] = round(1e3 * (time.time() - t1), 1)
if st != 200 or not isinstance(body, dict):
fails.append(f"{n}: HTTP {st} {str(body)[:200]}")
continue
texts[n] = body["text"]
m[f"{n}_text"] = body["text"]
m[f"{n}_usage"] = body.get("usage")
m[f"{n}_timings"] = body.get("timings")
if not body["text"].strip():
fails.append(f"{n}: empty text")
if body.get("finish_reason") != "stop":
fails.append(f"{n}: finish_reason {body.get('finish_reason')!r} (expected stop)")
exp = s.get("expected_text")
if exp and exp != "PENDING" and not fake:
e = cer(body["text"], exp)
m[f"{n}_cer"] = round(e, 4)
if e > float(s.get("max_cer", 0.02)):
fails.append(f"{n}: CER {e:.3f} vs the expected text ({body['text']!r} vs {exp!r})")
st2, body2, _ = gc.ocr(url, s["bytes_data"], task=s["task"])
if st2 != 200 or not isinstance(body2, dict) or body2.get("text") != body["text"]:
fails.append(f"{n}: a second identical request gave a different text")
st3, body3, _ = gc.ocr_json(url, s["bytes_data"], task=s["task"])
if st3 != 200 or not isinstance(body3, dict) or body3.get("text") != body["text"]:
fails.append(f"{n}: the JSON-body request gave a different text ({st3})")
by_task = {s["task"]: s for s in smp}
s = by_task.get("text") or (smp[0] if smp else None)
if s is not None:
img = s["bytes_data"]
st, body, _ = gc.chat(url, img, "")
if st != 200 or not isinstance(body, dict):
fails.append(f"chat: HTTP {st} {str(body)[:200]}")
else:
content = body["choices"][0]["message"]["content"]
m["chat_usage"] = body.get("usage")
if s["task"] == "text" and content != texts.get(s["name"]):
fails.append(f"chat content {content!r} != /ocr text {texts.get(s['name'])!r}")
if body["choices"][0]["finish_reason"] != "stop":
fails.append(f"chat finish_reason {body['choices'][0]['finish_reason']!r}")
try:
t1 = time.time()
chunks = list(gc.chat_stream(url, img, "", stream_options={"include_usage": True}))
m["chat_sse_ms"] = round(1e3 * (time.time() - t1), 1)
joined = "".join((c["choices"][0]["delta"].get("content") or "") for c in chunks if c.get("choices"))
if joined != content or not any(c.get("usage") for c in chunks):
fails.append(f"chat SSE: deltas {joined!r} != {content!r} or no usage chunk")
except Exception as e: # noqa: BLE001
fails.append(f"chat SSE: {type(e).__name__}: {e}")
try:
evs = list(gc.ocr_stream(url, img, task=s["task"]))
joined = "".join(e.get("text", "") for e in evs if e.get("type") == "delta")
done = [e for e in evs if e.get("type") == "done"]
m["ocr_sse_events"] = len(evs)
if not done or joined != done[-1]["raw_text"]:
fails.append(f"/ocr SSE: deltas {joined!r} != done {done[-1]['raw_text'] if done else None!r}")
except Exception as e: # noqa: BLE001
fails.append(f"/ocr SSE: {type(e).__name__}: {e}")
st, body, _ = gc.ocr(url, img, task="extract", schema={"invoice_number": "", "due_date": ""}, format="json")
m["extract"] = body.get("json") if isinstance(body, dict) else body
if st != 200 or not isinstance(body, dict) or not isinstance(body.get("json"), dict) or \
set(body["json"]) != {"invoice_number", "due_date"}:
fails.append(f"extract: HTTP {st} {str(body)[:300]}")
f = by_task.get("formula")
if f is not None:
st, body, _ = gc.ocr(url, f["bytes_data"], task="formula", format="markdown")
if st != 200 or not isinstance(body, dict) or not (body["text"].startswith("$$\n")
and body["text"].endswith("\n$$")):
fails.append(f"formula markdown: HTTP {st} {str(body)[:200]}")
if smp:
img = smp[0]["bytes_data"]
for fields, want in (({"task": "bogus"}, 400), ({"format": "xml"}, 400), ({"bogus": "1"}, 400),
({"temperature": "5"}, 400), ({"top_k": "1000"}, 400)):
st, body, _ = gc.ocr(url, img, **fields)
if st != want:
fails.append(f"/ocr {fields}: HTTP {st} (expected {want})")
st, body, _ = gc.chat(url, img, "", n=2)
if st != 400:
fails.append(f"chat n=2: HTTP {st} (expected 400)")
st, body, _ = gc._call(url + "/ocr", b"hello", "text/plain", 30)
if st != 415:
fails.append(f"text/plain body: HTTP {st} (expected 415)")
# a lone UTF-16 surrogate in the prompt (valid JSON, not text): 400, and the server stays healthy
import base64 as _b64
lone = json.dumps({"image": _b64.b64encode(img).decode(), "prompt": "\ud800 read"}).encode()
st, body, _ = gc._call(url + "/ocr", lone, "application/json", 60)
m["lone_surrogate_status"] = st
if st != 400:
fails.append(f"lone surrogate prompt: HTTP {st} (expected 400)")
hs, _, _ = gc._call(url + "/health", None, None, 30)
if hs != 200:
fails.append(f"/health after the refusals: HTTP {hs}")
m["backend"] = info.get("backend")
m["engine"] = info.get("engine")
m["device"] = dev
m["fails"] = fails
if args.out:
Path(args.out).write_text(json.dumps(m, indent=1, ensure_ascii=False))
if fails:
print("FAIL " + "; ".join(fails))
return 1
print(f"PASS {info.get('backend')} {dev.get('dispatch')} {dev.get('grid')} " +
" ".join(f"{s['name']} {m.get(s['name'] + '_ms')} ms" for s in smp) +
f": {texts.get(smp[0]['name']) if smp else ''!r}")
return 0
if __name__ == "__main__":
sys.exit(main())
|