Download code/tt_glmocr/server/smoke_test.py from changh95/GLM-OCR: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/server/smoke_test.py
- Command line
-
hf download hf://changh95/GLM-OCR/code/tt_glmocr/server/smoke_test.py
-
curl -L -o smoke_test.py https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/server/smoke_test.py
11.7 kB
| #!/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()) | |