File size: 9,476 Bytes
22e0325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Smoke test of a running PaddleOCR-VL server (standard library only; Python 3.9+, no numpy).

    python3 code/tt_paddleocr/server/smoke_test.py --url http://127.0.0.1:20000 --wait 1800 \\
        [--manifest <out>/paddleocr-vl/tt_kernel_manifest.json] [--profile 1.6] [--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`` / ``/v1/models`` answer; ``/info`` reports ETH dispatch and
    the 12x10 grid (``--allow-fake``: a fake-backend server instead) and, with ``--manifest``, the profile's pins
    (``PADDLEOCR_PROFILE``, ``PADDLEOCR_ENGINE``, ``PADDLEOCR_DISPATCH``);
  * the shipped samples (``samples/samples.json``: an English and a Chinese text line, a table, a formula) through
    ``/ocr`` with their task: the output matches the official float32 output of the profile (character error rate
    <= 0.10; the rendered text when no official output is recorded: <= 0.30); greedy determinism (same request
    twice); the table answer converts to HTML;
  * ``/v1/chat/completions`` (non-streamed and SSE: the deltas join to the text), seeded sampling reproducible;
  * ``repetition_penalty`` 1.3 answered (200; device: decode engine mk-host or ttnn);
  * refusals: 400 for an unknown task, temperature 5, a lone-surrogate prompt, n = 2, no image.
"""
from __future__ import annotations

import argparse
import importlib.util
import json
import sys
import time
import unicodedata
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


pc = _load("paddleocr_client", HERE / "client.py")


def norm(s: str) -> str:
    s = unicodedata.normalize("NFKC", s or "")
    return "".join(ch for ch in s if not ch.isspace())


def cer(hyp: str, ref: str) -> float:
    r, h = norm(ref), norm(hyp)
    if not r:
        return float(len(h) > 0)
    d = list(range(len(h) + 1))
    for i in range(1, len(r) + 1):
        prev, d[0] = d[0], i
        for j in range(1, len(h) + 1):
            cur = min(d[j] + 1, d[j - 1] + 1, prev + (r[i - 1] != h[j - 1]))
            prev, d[j] = d[j], cur
    return d[len(h)] / len(r)


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 = pc.get(url + "/health", 10)
        if st == 200 and h and h.get("status") == "ok":
            break
        if h 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 = pc.get(url + "/info")
    if st != 200 or not info:
        fails.append(f"/info answered {st}")
        info = {}
    fake = info.get("backend") == "fake"
    dev = info.get("device") or {}
    if not (fake and args.allow_fake):
        if dev.get("dispatch") != "eth" or dev.get("grid") != "12x10":
            fails.append(f"device {dev.get('dispatch')} {dev.get('grid')} (expected eth 12x10)")
    profile = info.get("profile")
    tasks = info.get("tasks") 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_name = args.profile or c.get("default_profile")
        for p in c.get("serve_profiles") or []:
            if p.get("name") == prof_name:
                envs.update(p.get("env") or {})
        conf = info.get("configuration") or {}
        for k in ("PADDLEOCR_PROFILE", "PADDLEOCR_ENGINE", "PADDLEOCR_DISPATCH"):
            if k in envs and k in conf and str(envs[k]) != str(conf[k]) and not (
                    k == "PADDLEOCR_ENGINE" and set(str(envs[k]).split(",")) <= set(str(conf[k]).split(","))):
                fails.append(f"{k}: served {conf.get(k)!r}, package pins {envs[k]!r}")
    st, _ = pc.get(url + "/v1/models")
    if st != 200:
        fails.append(f"/v1/models answered {st}")
    meta = json.load(open(SAMPLES / "samples.json"))["samples"]
    for name, s in meta.items():
        img = (SAMPLES / s["file"]).read_bytes()
        st, body, ms = pc.ocr(url, img, task=s["task"])
        key = name.rsplit(".", 1)[0]
        m[f"{key}_ms"] = round(ms, 1)
        if st != 200 or not isinstance(body, dict):
            fails.append(f"{name}: HTTP {st} {str(body)[:200]}")
            continue
        m[f"{key}_text"] = body["text"]
        m[f"{key}_timings"] = body.get("timings")
        exp = (s.get("expected_fp32_official") or {}).get(profile)
        if exp is not None:
            e, lim = cer(body["text"], exp), 0.10
        else:
            ref = s["rendered_text"]
            if isinstance(ref, list):
                ref = "".join("".join(r) for r in ref)
            e, lim = cer(body["text"], ref), 0.30
        m[f"{key}_cer"] = round(e, 4)
        if not fake and e > lim:
            fails.append(f"{name}: CER {e:.3f} > {lim} ({body['text']!r} vs {exp!r})")
        if s["task"] == "table" and not str((body.get("result") or {}).get("html", "")).startswith("<table>"):
            fails.append(f"{name}: no table HTML")
        st2, body2, _ = pc.ocr(url, img, task=s["task"])
        if st2 != 200 or not isinstance(body2, dict) or body2.get("text") != body["text"]:
            fails.append(f"{name}: a second identical request gave a different answer")
    img = (SAMPLES / "text_en_line.png").read_bytes()
    st, body, ms = pc.chat(url, img, "OCR:")
    m["chat_ms"] = round(ms, 1)
    text = None
    if st != 200 or not isinstance(body, dict):
        fails.append(f"chat: HTTP {st} {str(body)[:200]}")
    else:
        text = body["choices"][0]["message"]["content"]
        if body["choices"][0]["finish_reason"] not in ("stop", "length"):
            fails.append(f"chat: finish_reason {body['choices'][0]['finish_reason']!r}")
    try:
        t1 = time.time()
        evs = list(pc.chat_stream(url, img, "OCR:"))
        joined = "".join((ch.get("delta") or {}).get("content") or "" for e in evs for ch in e.get("choices") or [])
        m["chat_sse_ms"] = round(1e3 * (time.time() - t1), 1)
        m["chat_sse_chunks"] = len(evs)
        if text is not None and joined != text:
            fails.append(f"SSE: deltas {joined!r} != {text!r}")
    except Exception as e:  # noqa: BLE001
        fails.append(f"SSE: {type(e).__name__}: {e}")
    s1 = pc.ocr(url, img, temperature=0.8, top_p=0.9, seed=1234)
    s2 = pc.ocr(url, img, temperature=0.8, top_p=0.9, seed=1234)
    if s1[0] != 200 or s2[0] != 200 or s1[1].get("text") != s2[1].get("text"):
        fails.append(f"seeded sampling not reproducible ({s1[0]}, {s2[0]})")
    # repetition_penalty: served on every profile (megakernel logits + host sampler, engine "mk-host")
    st, body, ms = pc.ocr(url, img, repetition_penalty=1.3)
    m["penalty_ms"] = round(ms, 1)
    if st != 200 or not isinstance(body, dict):
        fails.append(f"repetition_penalty 1.3: HTTP {st} {str(body)[:200]}")
    else:
        m["penalty_text"] = body.get("text")
        m["penalty_engine"] = (body.get("timings") or {}).get("engine_dec")
        if not fake and m["penalty_engine"] not in ("mk-host", "ttnn"):
            fails.append(f"repetition_penalty 1.3: engine {m['penalty_engine']!r}")
    for params, want in ((dict(task="layout"), 400), (dict(temperature=5), 400),
                         (dict(prompt="OCR \ud800"), 400),  # a lone surrogate (valid JSON) is not text
                         (dict(task="spotting" if "spotting" not in tasks else "nope"), 400)):
        st, body, _ = pc.ocr(url, img, **params)
        if st != want:
            fails.append(f"{params}: HTTP {st} (expected {want})")
    st, body, _ = pc._call(url + "/v1/chat/completions", dict(pc.chat_body(img), n=2), 60)
    if st != 400:
        fails.append(f"chat n=2: HTTP {st} (expected 400)")
    st, body, _ = pc._call(url + "/v1/chat/completions",
                           {"messages": [{"role": "user", "content": "OCR:"}]}, 60)
    if st != 400:
        fails.append(f"chat without image: HTTP {st} (expected 400)")
    m["profile"] = profile
    m["device"] = dev
    m["engine"] = info.get("engine")
    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 profile {profile} {dev.get('dispatch')} {dev.get('grid')} en {m.get('text_en_line_ms')} ms "
          f"table {m.get('table_simple_ms')} ms: {m.get('text_en_line_text')!r}")
    return 0


if __name__ == "__main__":
    sys.exit(main())