Download code/tt_glmocr/tests/test_host_api.py from changh95/GLM-OCR: direct link, hf CLI and curl.
- Browser
- Download file 17.5 kB
-
https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tests/test_host_api.py
- Command line
-
hf download hf://changh95/GLM-OCR/code/tt_glmocr/tests/test_host_api.py
-
curl -L -o test_host_api.py https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tests/test_host_api.py
17.5 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Host tests of the Python API on the fake backend (no device, no weights), the output formats and image decoding: | |
| TT_VISIBLE_DEVICES=none python -m pytest bundles/glm-ocr/code/tt_glmocr/tests/test_host_api.py | |
| ``GLMOCR_TEST_CPU=1`` also runs the CPU reference backend on one sample (needs the checkpoint; about a minute). | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| import sys | |
| import threading | |
| import numpy as np | |
| import pytest | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) | |
| from tt_glmocr import config as C # noqa: E402 | |
| from tt_glmocr import frontend as FE # noqa: E402 | |
| from tt_glmocr import postprocess as PP # noqa: E402 | |
| from tt_glmocr.api import ByteTokenizer, Detokenizer, GlmOcr, InputError, load_image, parse_messages # noqa: E402 | |
| from tt_glmocr.backends import FakeBackend # noqa: E402 | |
| MODEL = os.environ.get("GLMOCR_MODEL_DIR") or os.environ.get("GLMOCR_MODEL") or "" # a local checkpoint dir (optional) | |
| HAVE_TOK = os.path.isfile(os.path.join(MODEL, "tokenizer.json")) | |
| SAMPLES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "samples") | |
| LINE = os.path.join(SAMPLES, "line_en", "sample.png") | |
| def _png(arr) -> bytes: | |
| from PIL import Image | |
| b = io.BytesIO() | |
| Image.fromarray(arr).save(b, format="PNG") | |
| return b.getvalue() | |
| def model(): | |
| m = GlmOcr.from_config(C.resolve_config({"GLMOCR_BACKEND": "fake"})) | |
| yield m | |
| m.close() | |
| def small(): | |
| """A small compiled configuration: 256 image tokens, 16 prompt tokens, 1024 KV positions.""" | |
| m = GlmOcr.from_config(C.resolve_config({"GLMOCR_BACKEND": "fake", "GLMOCR_MAX_IMAGE_TOKENS": "256", | |
| "GLMOCR_MAX_PROMPT_TOKENS": "64", "GLMOCR_MAX_CONTEXT": "1024", | |
| "GLMOCR_MAX_NEW_TOKENS": "2048", "GLMOCR_DEFAULT_MAX_NEW_TOKENS": "512"})) | |
| yield m | |
| m.close() | |
| # ---------------------------------------------------------------------------------------------- tasks | |
| def test_task_presets(model): | |
| r = model.ocr(LINE) | |
| assert r.task == "text" and r.text == FakeBackend.TEXT and r.raw_text == r.text and r.finish_reason == "stop" | |
| assert r.usage["image_tokens"] == 50 and r.usage["completion_tokens"] == len(r.tokens) + 1 | |
| assert r.usage["total_tokens"] == r.usage["prompt_tokens"] + r.usage["completion_tokens"] | |
| assert r.image == {"width": 709, "height": 64, "resized_width": 700, "resized_height": 56, "image_tokens": 50, | |
| "patches": 200, "grid": [2, 25], "min_pixels": 12544, "max_pixels": 9633792} | |
| assert model.ocr(LINE, task="table").text == FakeBackend.TABLE | |
| assert model.ocr(LINE, task="formula").text == FakeBackend.FORMULA | |
| assert model.ocr(LINE, prompt="Read it").text == "Fake reply to: Read it" | |
| r = model.ocr(LINE, prompt="Table Recognition:") | |
| assert r.task == "table" and r.text == FakeBackend.TABLE | |
| for k in ("preprocess_ms", "first_token_ms", "generate_ms", "total_ms", "vision_ms", "prefill_ms", "decode_ms", | |
| "n_tokens"): | |
| assert k in r.timings, k | |
| assert model.last_timings == r.timings | |
| def test_resolve_prompt(model): | |
| assert model.resolve_prompt(None, None, None) == ("text", "Text Recognition:") | |
| assert model.resolve_prompt("formula", None, None) == ("formula", "Formula Recognition:") | |
| assert model.resolve_prompt("table", "custom", None) == ("table", "custom") | |
| t, p = model.resolve_prompt(None, None, {"name": "", "address": {"city": ""}}) | |
| assert t == "extract" and p == '请按下列JSON格式输出图中信息:\n{\n "name": "",\n "address": {\n "city": ""\n }\n}' | |
| assert model.resolve_prompt("extract", None, '{"a": ""}')[1] == PP.EXTRACT_PREFACE + '{\n "a": ""\n}' | |
| for bad in (("ocr", None, None), ("extract", None, None), ("table", None, {"a": ""}), (None, "x", {"a": ""}), | |
| (None, None, "not json"), (None, None, []), (None, 5, None)): | |
| with pytest.raises(InputError): | |
| model.resolve_prompt(*bad) | |
| def test_extract_json(model): | |
| schema = {"invoice_number": "", "date": "", "items": [{"name": "", "qty": ""}]} | |
| r = model.ocr(LINE, task="extract", schema=schema) | |
| assert r.task == "extract" and r.text.startswith("```json") and r.json_error is None | |
| assert r.json == {"invoice_number": "fake", "date": "fake", "items": [{"name": "fake", "qty": "fake"}]} | |
| r = model.ocr(LINE, schema=json.dumps(schema), output_format="json") | |
| assert r.output_format == "json" and json.loads(r.text) == r.json and r.json["date"] == "fake" | |
| r = model.ocr(LINE, prompt="Read it", output_format="json") | |
| assert r.json is None and r.json_error and r.text == "Fake reply to: Read it" | |
| def test_markdown_format(model): | |
| assert model.ocr(LINE, task="formula", output_format="markdown").text == FakeBackend.FORMULA | |
| assert model.ocr(LINE, task="table", output_format="markdown").text == FakeBackend.TABLE | |
| with pytest.raises(InputError): | |
| model.ocr(LINE, output_format="xml") | |
| # ---------------------------------------------------------------------------------------------- streaming | |
| def _check_stream(m, **kw): | |
| s = m.ocr_stream(LINE, **kw) | |
| deltas = list(s) | |
| assert s.result is not None and "".join(deltas) == s.result.raw_text | |
| assert all(d and "�" not in d for d in deltas), deltas | |
| return deltas, s.result | |
| def test_stream_utf8_byte_tokens(model): | |
| deltas, r = _check_stream(model) | |
| assert r.text == FakeBackend.TEXT | |
| assert "é" in deltas and "你" in deltas and "🙂" in deltas # multi-byte characters arrive whole | |
| got = [] | |
| r2 = model.ocr(LINE, on_delta=got.append) | |
| assert got == deltas and r2.text == r.text | |
| def test_stream_utf8_real_tokenizer(): | |
| m = GlmOcr.from_config(C.resolve_config({"GLMOCR_BACKEND": "fake", "GLMOCR_MODEL_DIR": MODEL})) | |
| deltas, r = _check_stream(m) | |
| assert r.text == FakeBackend.TEXT and r.usage["prompt_tokens"] == 62 | |
| deltas, r = _check_stream(m, task="table") | |
| assert r.text == FakeBackend.TABLE | |
| def test_detokenizer_units(): | |
| tok = ByteTokenizer() | |
| for text in ("a🙂b", "你好", "plain", "é\nü", "🙂🙂"): | |
| d = Detokenizer(tok) | |
| out = [d.push(t) for t in tok.encode(text)] | |
| out.append(d.flush()) | |
| assert "".join(out) == text and all("�" not in x for x in out) | |
| d = Detokenizer(tok) | |
| assert d.push(0xF0) == "" and d.push(0x9F) == "" # an incomplete character is held back | |
| assert d.flush() == "�" # and emitted as the full decode gives it at the end | |
| def test_cancel(model): | |
| ev = threading.Event() | |
| ev.set() | |
| r = model.ocr(LINE, cancel=ev) | |
| assert r.finish_reason == "cancelled" and len(r.tokens) == 1 | |
| def test_max_new_tokens(model, small): | |
| r = model.ocr(LINE, max_new_tokens=5) | |
| assert r.finish_reason == "length" and r.raw_text == FakeBackend.TEXT[:5] and r.usage["completion_tokens"] == 5 | |
| for bad in (0, -1, 8193, "x", 1.5, True): | |
| with pytest.raises(InputError): | |
| model.ocr(LINE, max_new_tokens=bad) | |
| p = small.prepare(LINE) | |
| assert p.max_new_tokens == 512 # GLMOCR_DEFAULT_MAX_NEW_TOKENS | |
| p = small.prepare(LINE, max_new_tokens=2048) | |
| assert p.max_new_tokens == 1024 - p.prompt.L # clipped to the KV room | |
| assert small.ocr(LINE, max_new_tokens=2048).sampling["max_new_tokens"] == 1024 - p.prompt.L | |
| # ---------------------------------------------------------------------------------------------- caps | |
| def test_sampling_validation(model): | |
| sp = model.sampling() | |
| assert (sp.temperature, sp.top_k, sp.top_p, sp.repetition_penalty, sp.seed) == (0.0, 0, 1.0, 1.0, None) | |
| sp = model.sampling(temperature=0.7, top_k=64, top_p=0.9, repetition_penalty=1.1) | |
| assert sp.seed is not None and 0 <= sp.seed < 2 ** 63 | |
| assert model.sampling(temperature=0.5, seed=7).seed == 7 | |
| for bad in ({"temperature": 3}, {"temperature": -0.1}, {"temperature": float("nan")}, {"top_k": 65}, | |
| {"top_k": -1}, {"top_p": 0}, {"top_p": 1.5}, {"repetition_penalty": 0.5}, | |
| {"repetition_penalty": 2.5}, {"seed": -1}, {"seed": 2 ** 64}, {"temperature": "hot"}): | |
| with pytest.raises(InputError): | |
| model.sampling(**bad) | |
| def test_pixel_limits(model, small): | |
| assert model.pixel_limits() == (12544, 9633792) | |
| assert model.pixel_limits(max_image_tokens=100) == (12544, 156800) | |
| assert model.pixel_limits(max_pixels=200000, min_pixels=20000) == (20000, 200000) | |
| for bad in ({"max_pixels": 1000}, {"max_pixels": 9633793}, {"max_image_tokens": 7}, | |
| {"max_image_tokens": 6145}, {"max_pixels": 200000, "max_image_tokens": 100}, | |
| {"min_pixels": 1000}, {"min_pixels": 300000, "max_pixels": 200000}): | |
| with pytest.raises(InputError): | |
| model.pixel_limits(**bad) | |
| assert small.pixel_limits() == (12544, 2 * 784 * 256) | |
| with pytest.raises(InputError): | |
| small.pixel_limits(max_image_tokens=300) | |
| def test_image_token_budget(model, small): | |
| big = np.full((2400, 1800, 3), 255, np.uint8) | |
| big[100:200, 100:1700] = 0 | |
| r = model.ocr(big) | |
| assert r.image["image_tokens"] <= 6144 and r.image["width"] == 1800 | |
| r = model.ocr(big, max_image_tokens=100) | |
| assert r.image["image_tokens"] <= 100 and r.image["max_pixels"] == 156800 | |
| r = small.ocr(big) | |
| assert r.image["image_tokens"] <= 256 | |
| r = model.ocr(big, max_pixels=C.tokens_to_max_pixels(64), min_pixels=C.OFFICIAL_MIN_PIXELS) | |
| assert r.image["image_tokens"] <= 64 | |
| def test_prompt_token_cap(small): | |
| with pytest.raises(InputError, match="GLMOCR_MAX_PROMPT_TOKENS"): | |
| small.ocr(LINE, prompt="x" * 65) # byte tokenizer: one token per character | |
| assert small.ocr(LINE, prompt="x" * 64).finish_reason == "stop" | |
| def test_text_only_and_aspect(model): | |
| r = model.ocr(None, prompt="Hello") | |
| assert r.image is None and r.usage["image_tokens"] == 0 and r.text == "Fake reply to: Hello" | |
| with pytest.raises(InputError, match="resize"): | |
| model.ocr(np.zeros((28, 28 * 201, 3), np.uint8)) | |
| # ---------------------------------------------------------------------------------------------- image decoding | |
| def test_load_image_sources(tmp_path): | |
| rgb = np.random.default_rng(0).integers(0, 256, (40, 60, 3), dtype=np.uint8) | |
| data = _png(rgb) | |
| for src in (data, bytearray(data), "data:image/png;base64," + base64.b64encode(data).decode(), | |
| base64.b64encode(data).decode(), rgb): | |
| im = load_image(src) | |
| assert im.mode == "RGB" and im.size == (60, 40) | |
| np.testing.assert_array_equal(np.asarray(im), rgb) | |
| p = tmp_path / "x.png" | |
| p.write_bytes(data) | |
| assert load_image(str(p)).size == (60, 40) and load_image(p).size == (60, 40) | |
| with pytest.raises(InputError): | |
| load_image(str(p), allow_paths=False) # the server never reads paths: base64 decoding fails | |
| gray = load_image(rgb[..., 0]) | |
| assert gray.mode == "RGB" and np.asarray(gray)[0, 0, 0] == rgb[0, 0, 0] | |
| def test_load_image_alpha_exif_16bit(): | |
| from PIL import Image | |
| rgba = np.zeros((20, 30, 4), np.uint8) # black text on a transparent background | |
| rgba[5:10, 5:20, 3] = 255 | |
| im = np.asarray(load_image(_png(rgba))) | |
| assert (im[0, 0] == 255).all() and (im[6, 6] == 0).all() # composited onto white (transformers convert_to_rgb) | |
| assert (np.asarray(load_image(rgba))[0, 0] == 255).all() | |
| # EXIF orientation 6 (rotate 90 CW to display): a 30 x 20 stored image is shown 20 x 30 | |
| b = io.BytesIO() | |
| exif = Image.Exif() | |
| exif[0x0112] = 6 | |
| Image.fromarray(np.zeros((20, 30, 3), np.uint8)).save(b, format="JPEG", exif=exif.tobytes()) | |
| assert load_image(b.getvalue()).size == (20, 30) | |
| g16 = (np.arange(20 * 30, dtype=np.uint16).reshape(20, 30) * 100).astype(np.uint16) | |
| b = io.BytesIO() | |
| Image.fromarray(g16).save(b, format="PNG") | |
| im = np.asarray(load_image(b.getvalue())) | |
| assert im.dtype == np.uint8 and im[-1, -1, 0] == round(int(g16[-1, -1]) * 255 / 65535) | |
| def test_load_image_errors(): | |
| for bad, status in ((b"not an image", 400), (b"", 400), ("data:image/png;base64,@@@", 400), | |
| ("data:image/png,raw", 400), ("http://example.com/x.png", 400), (12, 400), | |
| (np.zeros((4, 4, 3), np.float32), 400)): | |
| with pytest.raises(InputError) as e: | |
| load_image(bad) | |
| assert e.value.status == status | |
| big = _png(np.zeros((1200, 1000, 3), np.uint8)) | |
| with pytest.raises(InputError) as e: | |
| load_image(big, max_pixels=1e6) | |
| assert e.value.status == 413 | |
| trunc = _png(np.random.default_rng(1).integers(0, 256, (200, 200, 3), dtype=np.uint8))[:500] | |
| with pytest.raises(InputError): | |
| load_image(trunc) | |
| # ---------------------------------------------------------------------------------------------- messages / formats | |
| def test_parse_messages(): | |
| img, text = parse_messages([{"role": "system", "content": "x"}, {"role": "user", "content": [ | |
| {"type": "text", "text": "Table Recognition:"}, {"type": "image_url", "image_url": {"url": "data:abc"}}]}]) | |
| assert img == "data:abc" and text == "Table Recognition:" | |
| for bad in (None, [], "hi", [{"role": "assistant", "content": "x"}], ["x"], | |
| [{"role": "user", "content": [{"type": "image_url", "image_url": "a"}, | |
| {"type": "image_url", "image_url": "b"}]}], | |
| [{"role": "user", "content": [{"type": "audio", "audio": "a"}]}], | |
| [{"role": "user", "content": 5}]): | |
| with pytest.raises(InputError): | |
| parse_messages(bad) | |
| def test_postprocess_helpers(): | |
| assert PP.parse_json_output('```json\n{"a": 1}\n```') == ({"a": 1}, None) | |
| assert PP.parse_json_output('Here: {"a": [1, 2]} done') == ({"a": [1, 2]}, None) | |
| assert PP.parse_json_output("[1, 2]") == ([1, 2], None) | |
| assert PP.parse_json_output('{"a": NaN}')[0] is None # strict JSON only (the HTTP answer must serialize) | |
| v, err = PP.parse_json_output("no json here") | |
| assert v is None and "not valid JSON" in err | |
| assert PP.normalize_inline_formula("area$ x^2 $is") == "area $x^2$ is" | |
| assert PP.clean_content("a.......b____c") == "a...b___c" | |
| loop = "abcdefghij" * 300 | |
| assert PP.clean_repeated_content(loop) == "abcdefghij" | |
| md = PP.format_markdown("line one\nline two\n\n• item", "text") | |
| assert md == "line one\n\nline two\n\n• item" | |
| assert PP.format_markdown("• item", "text") == "- item" | |
| assert PP.format_markdown("1.first", "text") == "1. first" | |
| assert PP.format_markdown("x^2", "formula") == "$$\nx^2\n$$" | |
| assert PP.format_markdown("\\[x^2\\]", "formula") == "$$\nx^2\n$$" | |
| assert PP.format_markdown("<table><tr><td>1</td></tr></table>", "table") == "<table><tr><td>1</td></tr></table>" | |
| assert PP.apply_format("x", "text", "raw") == ("x", None, None) | |
| with pytest.raises(ValueError): | |
| PP.schema_prompt("{") | |
| def test_info(model): | |
| i = model.info | |
| assert i["model"] == "glm-ocr" and i["backend"] == "fake" and i["weights"]["revision"] == C.WEIGHTS_REVISION | |
| assert i["limits"]["max_image_tokens"] == 6144 and i["defaults"]["max_new_tokens"] == 4096 | |
| assert set(i["tasks"]) == {"text", "table", "formula", "extract"} and i["formats"] == ["raw", "markdown", "json"] | |
| def test_no_heavy_imports_for_the_fake_backend(): | |
| import subprocess | |
| code = ("import sys; from tt_glmocr import config as C; from tt_glmocr.api import GlmOcr; " | |
| "m = GlmOcr.from_config(C.resolve_config({'GLMOCR_BACKEND': 'fake'})); " | |
| "assert 'ttnn' not in sys.modules and 'torch' not in sys.modules; " | |
| "r = m.ocr(None, prompt='hi'); assert r.text == 'Fake reply to: hi'; " | |
| "assert 'ttnn' not in sys.modules") | |
| here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| env = dict(os.environ, PYTHONPATH=os.pathsep.join([here] + [p for p in sys.path if p])) | |
| subprocess.check_call([sys.executable, "-c", code], env=env) | |
| def test_cpu_backend_line(): | |
| m = GlmOcr.from_config(C.resolve_config({"GLMOCR_BACKEND": "cpu", "GLMOCR_MODEL_DIR": MODEL})) | |
| s = m.ocr_stream(LINE, max_new_tokens=40) | |
| deltas = list(s) | |
| r = s.result | |
| assert r.finish_reason == "stop" and "".join(deltas) == r.raw_text | |
| assert r.text == "Invoice No. 2026-0417, due 15 December 2026." # the official fp32 output of this image | |
| assert r.usage["prompt_tokens"] == 62 and r.timings["n_tokens"] == r.usage["completion_tokens"] | |
| def test_lone_surrogate_prompt_is_input_error(model): | |
| """A lone surrogate in the prompt (or an extraction schema) is an InputError (HTTP 400), not a tokenizer crash.""" | |
| img = _png(np.full((64, 64, 3), 255, np.uint8)) | |
| for kw in ({"prompt": "read \ud800"}, {"task": "extract", "schema": {"k\udfff": ""}}): | |
| with pytest.raises(InputError) as e: | |
| model.prepare(img, **kw) | |
| assert e.value.status == 400 and "Unicode" in str(e.value) | |