Download code/tt_glmocr/tests/test_host_server.py from changh95/GLM-OCR: direct link, hf CLI and curl.
- Browser
- Download file 21 kB
-
https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tests/test_host_server.py
- Command line
-
hf download hf://changh95/GLM-OCR/code/tt_glmocr/tests/test_host_server.py
-
curl -L -o test_host_server.py https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tests/test_host_server.py
21 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Host tests of the HTTP server on the fake backend (no device, no weights): routes, SSE, errors, the queue, the | |
| main-thread open / close of the chip (a fake chip), and the stdlib client + smoke test against a live uvicorn: | |
| TT_VISIBLE_DEVICES=none python -m pytest bundles/glm-ocr/code/tt_glmocr/tests/test_host_server.py | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| import socket | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| from dataclasses import replace | |
| import numpy as np | |
| import pytest | |
| CODE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| sys.path.insert(0, CODE) | |
| from tt_glmocr import config as C # noqa: E402 | |
| from tt_glmocr.backends import FakeBackend # noqa: E402 | |
| SAMPLES = os.path.join(CODE, "tt_glmocr", "samples") | |
| LINE_PNG = open(os.path.join(SAMPLES, "line_en", "sample.png"), "rb").read() | |
| DATA_URL = "data:image/png;base64," + base64.b64encode(LINE_PNG).decode() | |
| FAKE = {"GLMOCR_BACKEND": "fake"} | |
| def _app(env=None, factory=None): | |
| from tt_glmocr.server.app import create_app | |
| app = create_app(model_factory=factory) | |
| app.state.glmocr.config_loader = lambda: C.resolve_config(dict(FAKE, **(env or {}))) | |
| return app | |
| def client(): | |
| from fastapi.testclient import TestClient | |
| with TestClient(_app()) as c: | |
| yield c | |
| def _chat(text=None, image=DATA_URL, **kw): | |
| content = [] | |
| if image is not None: | |
| content.append({"type": "image_url", "image_url": {"url": image}}) | |
| if text is not None: | |
| content.append({"type": "text", "text": text}) | |
| return dict({"model": "glm-ocr", "messages": [{"role": "user", "content": content}]}, **kw) | |
| def _sse(r): | |
| lines = [ln for ln in r.iter_lines() if ln.startswith("data: ")] | |
| assert lines[-1] == "data: [DONE]", lines[-3:] | |
| return [json.loads(ln[6:]) for ln in lines[:-1]] | |
| def test_import_has_no_heavy_side_effects(): | |
| code = ("import sys, tt_glmocr.server.app as a; assert a.app; " | |
| "assert not [m for m in sys.modules if m.split('.')[0] in ('torch', 'ttnn', 'numpy', 'PIL')], " | |
| "sorted(m for m in sys.modules if m.split('.')[0] in ('torch', 'ttnn', 'numpy', 'PIL'))") | |
| env = dict(os.environ, PYTHONPATH=os.pathsep.join([CODE] + [p for p in sys.path if p])) | |
| subprocess.check_call([sys.executable, "-c", code], env=env) | |
| def test_health_info_models(client): | |
| r = client.get("/health") | |
| assert r.status_code == 200 and r.json()["status"] == "ok" and r.json()["backend"] == "fake" | |
| assert client.get("/v1/health").status_code == 200 | |
| i = client.get("/info").json() | |
| assert i["model"] == "glm-ocr" and i["backend"] == "fake" and i["weights"]["repo"] == "zai-org/GLM-OCR" | |
| assert i["configuration"]["GLMOCR_MAX_IMAGE_TOKENS"] == "6144" and i["limits"]["max_new_tokens"] == 8192 | |
| assert i["buckets"]["prefill_rows"][-1] == 7296 and i["defaults"]["temperature"] == 0.0 | |
| assert client.get("/v1/models").json()["data"][0]["id"] == "glm-ocr" | |
| assert "POST /ocr" in client.get("/").json()["routes"] | |
| # ---------------------------------------------------------------------------------------------- chat | |
| def test_chat_completion(client): | |
| r = client.post("/v1/chat/completions", json=_chat()) | |
| assert r.status_code == 200, r.text | |
| j = r.json() | |
| assert j["object"] == "chat.completion" and j["id"].startswith("chatcmpl-") and j["model"] == "glm-ocr" | |
| ch = j["choices"][0] | |
| assert ch["message"] == {"role": "assistant", "content": FakeBackend.TEXT} and ch["finish_reason"] == "stop" | |
| u = j["usage"] | |
| assert u["prompt_tokens_details"]["image_tokens"] == 50 and u["total_tokens"] == u["prompt_tokens"] + u[ | |
| "completion_tokens"] | |
| assert j["image"]["resized_width"] == 700 and "total_ms" in j["timings"] | |
| assert client.get("/info").json()["last_request"]["usage"] == { | |
| "prompt_tokens": u["prompt_tokens"], "image_tokens": 50, "completion_tokens": u["completion_tokens"], | |
| "total_tokens": u["total_tokens"]} | |
| def test_chat_prompt_selects_the_task(client): | |
| j = client.post("/v1/chat/completions", json=_chat("Table Recognition:")).json() | |
| assert j["choices"][0]["message"]["content"] == FakeBackend.TABLE | |
| j = client.post("/v1/chat/completions", json=_chat("What is written?")).json() | |
| assert j["choices"][0]["message"]["content"] == "Fake reply to: What is written?" | |
| raw = client.post("/v1/chat/completions", json=_chat(image=base64.b64encode(LINE_PNG).decode())).json() | |
| assert raw["choices"][0]["message"]["content"] == FakeBackend.TEXT | |
| body = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": DATA_URL}]}]} | |
| assert client.post("/v1/chat/completions", json=body).status_code == 200 | |
| def test_chat_max_tokens(client): | |
| j = client.post("/v1/chat/completions", json=_chat(max_tokens=5)).json() | |
| assert j["choices"][0]["finish_reason"] == "length" and j["choices"][0]["message"]["content"] == "Fake " | |
| j = client.post("/v1/chat/completions", json=_chat(max_completion_tokens=4, max_tokens=100)).json() | |
| assert j["usage"]["completion_tokens"] == 4 | |
| def test_chat_stream(client): | |
| with client.stream("POST", "/v1/chat/completions", | |
| json=_chat(stream=True, stream_options={"include_usage": True})) as r: | |
| assert r.status_code == 200 and r.headers["content-type"].startswith("text/event-stream") | |
| chunks = _sse(r) | |
| assert all(c["object"] == "chat.completion.chunk" for c in chunks) | |
| assert chunks[0]["choices"][0]["delta"] == {"role": "assistant", "content": ""} | |
| content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks if c["choices"]) | |
| assert content == FakeBackend.TEXT | |
| fin = [c for c in chunks if c["choices"] and c["choices"][0]["finish_reason"]] | |
| assert len(fin) == 1 and fin[0]["choices"][0]["finish_reason"] == "stop" | |
| assert chunks[-1]["choices"] == [] and chunks[-1]["usage"]["completion_tokens"] > 0 | |
| assert len({c["id"] for c in chunks}) == 1 | |
| def test_chat_refusals(client, extra, status): | |
| r = client.post("/v1/chat/completions", json=_chat(**extra)) | |
| assert r.status_code == status, r.text | |
| j = r.json() | |
| assert j["detail"] and j["error"]["code"] == status and j["error"]["type"] == "invalid_request_error" | |
| def test_chat_bad_messages(client): | |
| two = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": DATA_URL}}, | |
| {"type": "image_url", "image_url": {"url": DATA_URL}}]}]} | |
| for body in (two, {"messages": "hi"}, {"messages": [{"role": "system", "content": "x"}]}, {}, | |
| _chat(image="data:image/png;base64,!!!"), _chat(image="http://example.com/a.png"), | |
| _chat(image="/etc/hostname"), _chat(image=base64.b64encode(b"not an image").decode())): | |
| r = client.post("/v1/chat/completions", json=body) | |
| assert r.status_code == 400, (body, r.text) | |
| r = client.post("/v1/chat/completions", content=b"{not json", headers={"content-type": "application/json"}) | |
| assert r.status_code == 422 | |
| assert client.post("/v1/chat/completions", json=[1, 2]).status_code == 422 | |
| # ignored OpenAI fields | |
| assert client.post("/v1/chat/completions", json=_chat(user="u1", metadata={"a": 1}, n=1, stop=None, | |
| presence_penalty=0)).status_code == 200 | |
| # ---------------------------------------------------------------------------------------------- /ocr | |
| def test_ocr_multipart(client): | |
| r = client.post("/ocr", files={"file": ("a.png", LINE_PNG, "image/png")}) | |
| assert r.status_code == 200, r.text | |
| j = r.json() | |
| assert j["text"] == FakeBackend.TEXT and j["task"] == "text" and j["format"] == "raw" and j["model"] == "glm-ocr" | |
| assert j["finish_reason"] == "stop" and j["usage"]["image_tokens"] == 50 and j["image"]["width"] == 709 | |
| r = client.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data={"task": "table", "format": "markdown"}) | |
| assert r.json()["text"] == FakeBackend.TABLE and r.json()["format"] == "markdown" | |
| r = client.post("/ocr", files={"image": ("a.png", LINE_PNG)}, | |
| data={"schema": json.dumps({"name": "", "total": ""}), "format": "json", "temperature": "0", | |
| "max_new_tokens": "200", "seed": "", "max_image_tokens": "40"}) | |
| j = r.json() | |
| assert r.status_code == 200 and j["task"] == "extract" and j["json"] == {"name": "fake", "total": "fake"} | |
| assert j["image"]["image_tokens"] <= 40 and json.loads(j["text"]) == j["json"] | |
| def test_ocr_json_and_raw_body(client): | |
| body = {"image": DATA_URL, "task": "extract", "schema": {"invoice": {"number": ""}}, "max_tokens": 300} | |
| j = client.post("/ocr", json=body).json() | |
| assert j["json"] == {"invoice": {"number": "fake"}} and j["json_error"] is None | |
| j = client.post("/ocr", json={"image": base64.b64encode(LINE_PNG).decode(), "task": "formula"}).json() | |
| assert j["text"] == FakeBackend.FORMULA | |
| r = client.post("/ocr?task=formula&format=markdown", content=LINE_PNG, headers={"content-type": "image/png"}) | |
| assert r.status_code == 200 and r.json()["text"] == FakeBackend.FORMULA | |
| r = client.post("/ocr?max_new_tokens=3", content=LINE_PNG, headers={"content-type": "application/octet-stream"}) | |
| assert r.json()["finish_reason"] == "length" and r.json()["raw_text"] == "Fak" | |
| def test_ocr_stream(client): | |
| with client.stream("POST", "/ocr", files={"file": ("a.png", LINE_PNG)}, data={"stream": "true"}) as r: | |
| assert r.status_code == 200 | |
| evs = _sse(r) | |
| deltas = [e["text"] for e in evs if e["type"] == "delta"] | |
| done = evs[-1] | |
| assert done["type"] == "done" and "".join(deltas) == done["raw_text"] == FakeBackend.TEXT | |
| assert "🙂" in deltas and all("�" not in d for d in deltas) | |
| assert done["usage"]["completion_tokens"] == len(done["raw_text"].encode()) + 1 | |
| def test_ocr_refusals(client, kind, payload, status): | |
| if kind == "form": | |
| r = client.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data=payload) | |
| else: | |
| r = client.post("/ocr", json=payload) | |
| assert r.status_code == status, r.text | |
| def test_ocr_bad_bodies(client): | |
| assert client.post("/ocr", data={"task": "text"}, files={"other": ("x.txt", b"x")}).status_code == 400 | |
| assert client.post("/ocr", files={"file": ("a.png", b"")}).status_code == 400 | |
| assert client.post("/ocr", files={"file": ("a.png", b"not an image")}).status_code == 400 | |
| assert client.post("/ocr", content=b"hello", headers={"content-type": "text/plain"}).status_code == 415 | |
| assert client.post("/ocr", content=b"{", headers={"content-type": "application/json"}).status_code == 422 | |
| r = client.post("/ocr", content=b"--x\r\n", headers={"content-type": "multipart/form-data; boundary=zz"}) | |
| assert r.status_code in (400, 422) | |
| assert client.post("/ocr", content=b"", headers={"content-type": "image/png"}).status_code == 400 | |
| def test_size_limits(): | |
| from fastapi.testclient import TestClient | |
| with TestClient(_app({"GLMOCR_MAX_BODY_MB": "1", "GLMOCR_MAX_INPUT_MEGAPIXELS": "0.5"})) as c: | |
| r = c.post("/ocr", content=b"\0" * (2 << 20), headers={"content-type": "image/png"}) | |
| assert r.status_code == 413 and r.json()["error"]["code"] == 413 | |
| from PIL import Image | |
| b = io.BytesIO() | |
| Image.fromarray(np.full((800, 800, 3), 255, np.uint8)).save(b, format="PNG") | |
| r = c.post("/ocr", files={"file": ("big.png", b.getvalue())}) | |
| assert r.status_code == 413 and "MEGAPIXELS" in r.json()["detail"] | |
| def test_queue_full_and_timeouts(): | |
| from fastapi.testclient import TestClient | |
| with TestClient(_app({"GLMOCR_QUEUE_DEPTH": "0"})) as c: | |
| st = c.app.state.glmocr | |
| gate, started = threading.Event(), threading.Event() | |
| st.worker.submit(lambda j: (started.set(), gate.wait(30)), kind="block") | |
| assert started.wait(10) | |
| r = c.post("/ocr", files={"file": ("a.png", LINE_PNG)}) | |
| assert r.status_code == 429 and r.headers["retry-after"] == "2" | |
| assert c.get("/health").json()["queue"]["running"] == "block" | |
| gate.set() | |
| time.sleep(0.2) | |
| assert c.post("/ocr", files={"file": ("a.png", LINE_PNG)}).status_code == 200 | |
| def test_not_ready_is_503(): | |
| from fastapi.testclient import TestClient | |
| c = TestClient(_app()) # no lifespan: the model is never built | |
| r = c.get("/health") | |
| assert r.status_code == 503 and r.json()["status"] == "starting" | |
| assert c.post("/ocr", files={"file": ("a.png", LINE_PNG)}).status_code == 503 | |
| assert c.post("/v1/chat/completions", json=_chat()).status_code == 503 | |
| assert c.get("/info").json()["status"] == "starting" | |
| def test_startup_failure_refuses_to_start(): | |
| from fastapi.testclient import TestClient | |
| from tt_glmocr.server.app import create_app, load_config | |
| app = create_app() | |
| app.state.glmocr.config_loader = lambda: load_config({"GLMOCR_MAX_IMAGE_TOKENS": "1"}) | |
| with pytest.raises(RuntimeError, match="GLMOCR_MAX_IMAGE_TOKENS"): | |
| with TestClient(app): | |
| pass | |
| assert app.state.glmocr.error and not app.state.glmocr.ready | |
| # ---------------------------------------------------------------------------------------------- the chip's thread | |
| def _patch_chip(monkeypatch, seen, fail_build=False): | |
| from tt_glmocr.api import GlmOcr | |
| from tt_glmocr.server import app as A | |
| from tt_glmocr.ttaw import device as D | |
| def fake_open(device_id=0, **kw): | |
| seen["open"] = (threading.get_ident(), device_id, kw.get("dispatch")) | |
| seen.setdefault("order", []).append("open") | |
| return "chip" | |
| def fake_close(dev): | |
| seen["close"] = (threading.get_ident(), dev) | |
| seen.setdefault("order", []).append("close") | |
| def fake_factory(cfg, device=None): | |
| seen["build"] = (threading.get_ident(), device, cfg.backend) | |
| if fail_build: | |
| raise RuntimeError("engine build failed") | |
| m = GlmOcr.from_config(replace(cfg, backend="fake")) | |
| orig = m.close | |
| def close(): | |
| seen.setdefault("order", []).append("model.close") | |
| seen["model_close"] = threading.get_ident() | |
| orig() | |
| m.close = close | |
| return m | |
| monkeypatch.setattr(D, "open_device", fake_open) | |
| monkeypatch.setattr(D, "close_device", fake_close) | |
| monkeypatch.setattr(A, "default_model_factory", fake_factory) | |
| def test_chip_opened_and_closed_on_the_main_thread(monkeypatch): | |
| """The default factory path: the chip is opened and closed on the lifespan's thread (the main thread under | |
| uvicorn), the model is built, run and released on the device thread. UMD's per-chip lock must be released by the | |
| thread that took it, and tt-metal releases it at exit on the main thread.""" | |
| from fastapi.testclient import TestClient | |
| from tt_glmocr.server import app as A | |
| seen = {} | |
| _patch_chip(monkeypatch, seen) | |
| app = A.create_app() | |
| app.state.glmocr.config_loader = lambda: C.resolve_config({"GLMOCR_BACKEND": "device", "TT_DEVICE_ID": "0"}) | |
| with TestClient(app) as c: | |
| assert c.get("/health").json()["status"] == "ok" | |
| assert c.post("/ocr", files={"file": ("a.png", LINE_PNG)}).json()["text"] == FakeBackend.TEXT | |
| assert seen["open"][1:] == (0, "eth") and seen["build"][1:] == ("chip", "device") | |
| assert seen["close"][1] == "chip" | |
| assert seen["open"][0] == seen["close"][0] # the same thread opens and closes the chip | |
| assert seen["build"][0] != seen["open"][0] # the model is built on the device thread | |
| assert seen["model_close"] == seen["build"][0] # and released there, before the chip closes | |
| assert seen["order"] == ["open", "model.close", "close"] | |
| def test_chip_closed_when_the_build_fails(monkeypatch): | |
| from fastapi.testclient import TestClient | |
| from tt_glmocr.server import app as A | |
| seen = {} | |
| _patch_chip(monkeypatch, seen, fail_build=True) | |
| app = A.create_app() | |
| app.state.glmocr.config_loader = lambda: C.resolve_config({"GLMOCR_BACKEND": "device"}) | |
| with pytest.raises(RuntimeError, match="engine build failed"): | |
| with TestClient(app): | |
| pass | |
| assert seen["order"] == ["open", "close"] and seen["open"][0] == seen["close"][0] | |
| assert "engine build failed" in app.state.glmocr.error | |
| # ---------------------------------------------------------------------------------------------- live server | |
| def _free_port() -> int: | |
| s = socket.socket() | |
| s.bind(("127.0.0.1", 0)) | |
| p = s.getsockname()[1] | |
| s.close() | |
| return p | |
| def test_client_and_smoke_test_against_a_live_server(monkeypatch, tmp_path): | |
| import uvicorn | |
| from tt_glmocr.server.app import create_app | |
| for k in list(os.environ): | |
| if k.startswith("GLMOCR_") or k == "TT_MESH_SHAPE": | |
| monkeypatch.delenv(k, raising=False) | |
| monkeypatch.setenv("GLMOCR_BACKEND", "fake") | |
| port = _free_port() | |
| server = uvicorn.Server(uvicorn.Config(create_app(), host="127.0.0.1", port=port, log_level="warning", | |
| lifespan="on")) | |
| th = threading.Thread(target=server.run, daemon=True) | |
| th.start() | |
| try: | |
| t0 = time.time() | |
| while not server.started: | |
| assert time.time() - t0 < 60 and th.is_alive(), "uvicorn did not start" | |
| time.sleep(0.05) | |
| url = f"http://127.0.0.1:{port}" | |
| out = tmp_path / "smoke.json" | |
| p = subprocess.run([sys.executable, os.path.join(CODE, "tt_glmocr", "server", "smoke_test.py"), "--url", url, | |
| "--wait", "30", "--allow-fake", "--out", str(out)], capture_output=True, text=True, | |
| timeout=300) | |
| assert p.returncode == 0 and p.stdout.startswith("PASS"), p.stdout + p.stderr | |
| m = json.loads(out.read_text()) | |
| assert m["fails"] == [] and m["extract"] == {"invoice_number": "fake", "due_date": "fake"} | |
| p = subprocess.run([sys.executable, os.path.join(CODE, "tt_glmocr", "server", "client.py"), | |
| os.path.join(SAMPLES, "table_sales", "sample.png"), "--url", url, "--task", "table"], | |
| capture_output=True, text=True, timeout=120) | |
| assert p.returncode == 0 and p.stdout.strip() == FakeBackend.TABLE, p.stdout + p.stderr | |
| quick = os.path.join(os.path.dirname(CODE), "examples", "quickstart.py") # the repo root's examples/ | |
| if os.path.isfile(quick): | |
| p = subprocess.run([sys.executable, quick, os.path.join(SAMPLES, "line_en", "sample.png"), url], | |
| capture_output=True, text=True, timeout=120) | |
| assert p.returncode == 0 and FakeBackend.TEXT in p.stdout, p.stdout + p.stderr | |
| finally: | |
| server.should_exit = True | |
| th.join(30) | |
| def test_lone_surrogate_is_a_400(client): | |
| """A lone UTF-16 surrogate (a valid JSON escape, not text) in the prompt / schema is a 400, not a 500.""" | |
| import json as _json | |
| def post(path, body): # json.dumps escapes the surrogate as \ud800 (valid JSON); httpx would refuse to encode it | |
| return client.post(path, content=_json.dumps(body).encode(), headers={"content-type": "application/json"}) | |
| body = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": DATA_URL}}, | |
| {"type": "text", "text": "Text Recognition:\ud800"}]}]} | |
| r = post("/v1/chat/completions", body) | |
| assert r.status_code == 400 and "Unicode" in r.json()["detail"], r.text | |
| r = post("/ocr", {"image": DATA_URL, "prompt": "\udc00 read"}) | |
| assert r.status_code == 400, r.text | |
| r = post("/ocr", {"image": DATA_URL, "task": "extract", "schema": {"a\ud800": ""}}) | |
| assert r.status_code == 400, r.text | |
| assert client.get("/health").status_code == 200 | |