#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # Adapted from this workspace's GLM-OCR bundle (tt_glmocr/server/smoke_test.py, Apache-2.0). """Smoke test of a running DeepSeek-OCR family server (standard library only; Python 3.9+, no numpy / PIL). python3 code/tt_dsocr/server/smoke_test.py --url http://127.0.0.1:20000 --wait 3600 \\ [--manifest /deepseek-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 ``DSOCR_BACKEND=fake`` server instead) and, with ``--manifest``, the pinned ``DSOCR_VARIANT`` / ``DSOCR_ENGINE`` / ``DSOCR_DISPATCH`` / ``DSOCR_MODES`` / ``DSOCR_MAX_CROPS`` / ``DSOCR_PRECISION``; * every shipped sample (``samples/*``; the entry of the served model: ``sample.json`` top level = DeepSeek-OCR, ``variants[]`` = the others) whose mode is enabled through ``POST /ocr`` with its task and mode: HTTP 200, EOS reached, text not empty, the character error rate vs the sample's ``expected_text`` <= its ``max_cer`` (when the sample has one), the same request twice gives the same text (greedy determinism), the JSON-body form gives the same text; * ``POST /v1/chat/completions`` (data URL, the prompt of the ``free`` task, else of the default task) equals ``/ocr`` with that task; SSE streaming of both routes: the deltas join to the final text; ``format=markdown`` of the ``markdown`` (``parse``) task has no layout tags and ``format=json`` returns ``refs`` (label + pixel boxes; ``parse``: ``pages`` with blocks); ``task=locate`` returns JSON (models that offer it); * a multi-page model (``/info`` ``limits.max_pages`` > 1, Unlimited-OCR-2): two pages (multipart, JSON ``images``, chat with two ``image_url`` parts) give the same text with one ```` per page; other models refuse two images (400); * refusals: 400 for an unknown task / format / mode / field, temperature 5, top_k 1000, max_crops 99, no_repeat_ngram_size 1, locate without ref, a task the model does not offer, n=2, a prompt with an unpaired surrogate (chat and /ocr; /health stays 200); 415 for a text/plain body. """ from __future__ import annotations import argparse import importlib.util import json import sys import time from pathlib import Path from typing import Any, Dict, List HERE = Path(__file__).resolve().parent SAMPLES = HERE.parent / "samples" TAGS = ("<|ref|>", "<|/ref|>", "<|det|>", "<|/det|>", "", "", "", "") MULTIPAGE = ("table_sales", "formula_quad") # the two-page document of a multi-page model 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 dc = _load("dsocr_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(variant: str = "deepseek-ocr") -> List[Dict[str, Any]]: """The shipped samples with the served model's entry (``variants[variant]`` over the top level, which is DeepSeek-OCR's); a sample without an entry for another model is skipped.""" 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()) only = m.get("only") # a sample of some models only (the Korean pages: schift); its top level is their entry if only and variant not in only: continue ov = (m.pop("variants", None) or {}) if variant in ov: m.update(ov[variant]) elif variant != "deepseek-ocr" and not only: continue 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=3600.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 = dc.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 = dc.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)") conf = info.get("configuration") or {} 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 {}) for k in ("DSOCR_VARIANT", "DSOCR_ENGINE", "DSOCR_DISPATCH", "DSOCR_MODES", "DSOCR_MAX_CROPS", "DSOCR_PRECISION"): want, got = str(envs.get(k, "")), str(conf.get(k, "")) if not want or k not in conf: continue if k in ("DSOCR_ENGINE", "DSOCR_PRECISION", "DSOCR_MODES"): 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 = dc.get(url, "/v1/models") if st != 200: fails.append(f"/v1/models answered {st}") enabled = set((info.get("modes") or {}).keys()) or set(dc.MODES) variant = info.get("variant") or "deepseek-ocr" tasks = info.get("tasks") or {} default_task = (info.get("defaults") or {}).get("task") or "markdown" max_pages = int((info.get("limits") or {}).get("max_pages") or 1) m["variant"] = variant texts: Dict[str, str] = {} smp = [s for s in samples(variant) if s.get("mode", "gundam") in enabled] if not smp: fails.append(f"no sample under {SAMPLES} uses an enabled mode ({sorted(enabled)})") for s in smp: n = s["name"] q = {"task": s["task"], "mode": s["mode"], "format": "raw"} t1 = time.time() st, body, _ = dc.ocr(url, s["bytes_data"], **q) 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)") tm = body.get("timings") or {} if not all(k in tm for k in ("decode_ms", "tokens", "tokens_per_s")): fails.append(f"{n}: timings without decode_ms / tokens / tokens_per_s ({sorted(tm)})") exp = s.get("expected_text") if exp 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, _ = dc.ocr(url, s["bytes_data"], **q) 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, _ = dc.ocr_json(url, s["bytes_data"], **q) 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} chat_task = "free" if "free" in tasks else default_task s = by_task.get(chat_task) or (smp[0] if smp else None) if s is not None: img, mode = s["bytes_data"], s["mode"] prompt = tasks.get(chat_task, "Free OCR.").replace("\n", "") st, ref_body, _ = dc.ocr(url, img, task=chat_task, mode=mode, format="raw") ref_text = ref_body.get("text") if st == 200 and isinstance(ref_body, dict) else None st, body, _ = dc.chat(url, img, prompt, mode=mode) 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 content != ref_text: fails.append(f"chat content {content!r} != /ocr {chat_task} text {ref_text!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(dc.chat_stream(url, img, prompt, mode=mode, 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(dc.ocr_stream(url, img, task=chat_task, mode=mode)) 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}") md_task = "markdown" if "markdown" in tasks else ("parse" if "parse" in tasks else None) s = by_task.get(md_task) if md_task else None if s is not None: st, body, _ = dc.ocr(url, s["bytes_data"], task=md_task, mode=s["mode"], format="json") ok = st == 200 and isinstance(body, dict) and isinstance(body.get("json"), dict) if not ok or not isinstance(body["json"].get("refs"), list) or any(t in body["json"]["text"] for t in TAGS): fails.append(f"{md_task} task, json format: HTTP {st} {str(body)[:300]}") else: m["markdown_refs"] = body["json"]["refs"][:8] refs = body["json"]["refs"] if fake and not refs: fails.append(f"{md_task} task: no refs parsed") for r in refs: if not isinstance(r.get("label"), str) or not isinstance(r.get("boxes"), list): fails.append(f"{md_task} task: bad ref {r}") break if md_task == "parse" and variant != "unlimited-ocr-2": # schift-ocr-1-beta: det-only blocks blocks = body["json"].get("blocks") if not isinstance(blocks, list) or not blocks or \ any(not isinstance(b.get("label"), str) or not isinstance(b.get("text"), str) for b in blocks): fails.append(f"parse task, json format: blocks {str(blocks)[:300]}") elif md_task == "parse": pages = body["json"].get("pages") if not isinstance(pages, list) or (body.get("finish_reason") == "stop" and len(pages) != 1) or \ any(not isinstance(p.get("blocks"), list) for p in pages or []): fails.append(f"parse task, json format: pages {str(pages)[:300]}") st, body, _ = dc.ocr(url, s["bytes_data"], task=md_task, mode=s["mode"]) # format default: markdown if st != 200 or not isinstance(body, dict) or body.get("format") != "markdown" or \ any(t in body["text"] for t in TAGS): fails.append(f"{md_task} task, default format: HTTP {st} {str(body)[:300]}") if smp: s0 = smp[0] img = s0["bytes_data"] if "locate" in tasks: st, body, _ = dc.ocr(url, img, task="locate", ref="the text", mode=s0["mode"], max_new_tokens=64) m["locate"] = body.get("json") if isinstance(body, dict) else body if st != 200 or not isinstance(body, dict) or body.get("format") != "json" or \ not isinstance(body.get("json"), dict) or (fake and not body["json"].get("refs")): fails.append(f"locate: HTTP {st} {str(body)[:300]}") refusals = [({"task": "bogus"}, 400), ({"format": "xml"}, 400), ({"bogus": "1"}, 400), ({"mode": "huge"}, 400), ({"temperature": "5"}, 400), ({"top_k": "1000"}, 400), ({"max_crops": "99"}, 400), ({"no_repeat_ngram_size": "1"}, 400), ({"task": "locate"}, 400)] refusals += [({"task": t}, 400) for t in ("ocr", "describe", "parse") if t not in tasks][:1] for fields, want in refusals: st, body, _ = dc.ocr(url, img, **fields) if st != want: fails.append(f"/ocr {fields}: HTTP {st} (expected {want})") st, body, _ = dc.chat(url, img, "", n=2) if st != 400: fails.append(f"chat n=2: HTTP {st} (expected 400)") st, body, _ = dc._call(url + "/ocr", b"hello", "text/plain", 30) if st != 415: fails.append(f"text/plain body: HTTP {st} (expected 415)") # an unpaired surrogate in a prompt (valid JSON "\ud800"): 400 on both routes, the server stays healthy for path, doc in (("/v1/chat/completions", dc.chat_body(img, "read \ud800 this")), ("/ocr", {"image": dc.data_url(img), "prompt": "x\udfff"})): st, body, _ = dc._call(url + path, json.dumps(doc).encode("ascii"), "application/json", 60) if st != 400 or "surrogate" not in str(body): fails.append(f"lone surrogate in the prompt, {path}: HTTP {st} {str(body)[:200]} (expected 400)") st, _ = dc.get(url, "/health", 10) if st != 200: fails.append(f"/health after the refusals: HTTP {st}") two = [img, img] if max_pages >= 2: pages = [(SAMPLES / n / "sample.png").read_bytes() for n in MULTIPAGE] t1 = time.time() st, body, _ = dc.ocr(url, pages, format="raw") m["multipage_ms"] = round(1e3 * (time.time() - t1), 1) if st != 200 or not isinstance(body, dict): fails.append(f"two pages: HTTP {st} {str(body)[:300]}") else: raw = body["raw_text"] m["multipage_text"] = raw m["multipage_usage"] = body.get("usage") m["multipage_image"] = body.get("image") if body.get("finish_reason") == "stop" and raw.count("") < 2: fails.append(f"two pages: {raw.count('')} in the output {raw[:200]!r}") if (body.get("image") or {}).get("n_pages") != 2 or body.get("mode") != "base": fails.append(f"two pages: image {body.get('image')} mode {body.get('mode')} (expected 2 pages, base)") st2, b2, _ = dc.ocr_json(url, pages, format="raw") if st2 != 200 or not isinstance(b2, dict) or b2.get("raw_text") != raw: fails.append(f"two pages, JSON images: HTTP {st2}, a different text") st3, b3, _ = dc.chat(url, pages, "") if st3 != 200 or not isinstance(b3, dict) or b3["choices"][0]["message"]["content"] != raw: fails.append(f"two pages, chat: HTTP {st3}, a different text") st4, b4, _ = dc.ocr(url, pages, format="json") if st4 != 200 or not isinstance(b4, dict) or not isinstance((b4.get("json") or {}).get("pages"), list): fails.append(f"two pages, json format: HTTP {st4} {str(b4)[:300]}") elif b4.get("finish_reason") == "stop" and len(b4["json"]["pages"]) < 2: fails.append(f"two pages, json format: {len(b4['json']['pages'])} page(s)") st, body, _ = dc.ocr(url, [img] * (max_pages + 1)) if st != 400: fails.append(f"{max_pages + 1} pages: HTTP {st} (expected 400, DSOCR_MAX_PAGES={max_pages})") else: for name, fn in (("multipart", dc.ocr), ("JSON images", dc.ocr_json)): st, body, _ = fn(url, two) if st != 400: fails.append(f"two images ({name}): HTTP {st} (expected 400: one image per request)") st, body, _ = dc.chat(url, two, "") if st != 400: fails.append(f"two images (chat): HTTP {st} (expected 400: one image per request)") 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 {variant} {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())