PaddleOCR-VL / code /tt_paddleocr /tests /test_host_server.py
changh95's picture
tt-model push paddleocr-vl (container)
22e0325 verified
Raw History Blame Contribute Delete
10.8 kB
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the HTTP server on the fake backend (no device, no weights).
TT_VISIBLE_DEVICES=none python -m pytest code/tt_paddleocr/tests/test_host_server.py
"""
import base64
import json
import os
import subprocess
import sys
import pytest
from fastapi.testclient import TestClient
HERE = os.path.dirname(os.path.abspath(__file__))
SAMPLES = os.path.join(os.path.dirname(HERE), "samples")
CODE = os.path.dirname(os.path.dirname(HERE))
def b64(name="table_simple.png"):
return base64.b64encode(open(os.path.join(SAMPLES, name), "rb").read()).decode()
def chat_body(text="OCR:", img=None, **kw):
d = {"model": "paddleocr-vl", "messages": [{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + (img or b64())}},
{"type": "text", "text": text}]}]}
d.update(kw)
return d
@pytest.fixture(scope="module")
def client():
os.environ["PADDLEOCR_BACKEND"] = "fake"
os.environ["PADDLEOCR_PROFILE"] = "1.6"
os.environ["PADDLEOCR_QUEUE_DEPTH"] = "4"
from tt_paddleocr.server.app import create_app
with TestClient(create_app()) as c:
yield c
for k in ("PADDLEOCR_BACKEND", "PADDLEOCR_PROFILE", "PADDLEOCR_QUEUE_DEPTH"):
os.environ.pop(k, None)
def sse(text):
out = []
for line in text.splitlines():
if line.startswith("data: ") and line != "data: [DONE]":
out.append(json.loads(line[6:]))
return out
def test_import_has_no_side_effects():
code = ("import sys, tt_paddleocr.server.app as a; assert a.app; "
"bad = [m for m in ('ttnn', 'torch') if m in sys.modules]; assert not bad, bad")
r = subprocess.run([sys.executable, "-c", code], cwd=CODE, capture_output=True, text=True,
env=dict(os.environ, PYTHONPATH=os.pathsep.join([CODE] + [p for p in [os.environ.get("PYTHONPATH")] if p])))
assert r.returncode == 0, r.stderr[-2000:]
def test_health_info_models(client):
h = client.get("/health").json()
assert h["status"] == "ok" and h["profile"] == "1.6"
i = client.get("/info").json()
assert i["backend"] == "fake" and i["task_prompts"]["spotting"] == "Spotting:" and i["configuration"]["PADDLEOCR_PROFILE"] == "1.6"
assert i["limits"]["max_patches"] == 8192 and i["buckets"]["vision"][-1] == 8192
m = client.get("/v1/models").json()
assert m["data"][0]["id"] == "paddleocr-vl" and m["data"][0]["root"] == "PaddlePaddle/PaddleOCR-VL-1.6"
assert client.get("/").status_code == 200
@pytest.mark.parametrize("text,task", [("OCR:", "ocr"), ("Table Recognition:", "table"), ("formula", "formula"),
("", "ocr"), ("Chart Recognition:", "chart"), ("Seal Recognition:", "seal")])
def test_chat_task_selection(client, text, task):
r = client.post("/v1/chat/completions", json=chat_body(text))
assert r.status_code == 200, r.text
d = r.json()
assert d["object"] == "chat.completion" and d["paddleocr"]["task"] == task
assert d["choices"][0]["finish_reason"] == "stop" and d["choices"][0]["message"]["role"] == "assistant"
assert d["usage"]["total_tokens"] == d["usage"]["prompt_tokens"] + d["usage"]["completion_tokens"]
def test_chat_table_html_and_custom_prompt(client):
d = client.post("/v1/chat/completions", json=chat_body("Table Recognition:")).json()
assert d["paddleocr"]["result"]["html"].startswith("<table>")
d = client.post("/v1/chat/completions", json=chat_body("What is in the picture?")).json()
assert d["paddleocr"]["task"] == "custom"
d = client.post("/v1/chat/completions", json=chat_body("anything", task="table")).json()
assert d["paddleocr"]["task"] == "table"
def test_chat_stream(client):
r = client.post("/v1/chat/completions", json=chat_body("OCR:", stream=True,
stream_options={"include_usage": True}))
assert r.status_code == 200 and r.headers["content-type"].startswith("text/event-stream")
ev = sse(r.text)
assert ev[0]["choices"][0]["delta"]["role"] == "assistant"
content = "".join(e["choices"][0]["delta"].get("content", "") for e in ev if e.get("choices"))
fin = [e for e in ev if e.get("choices") and e["choices"][0]["finish_reason"]]
assert fin and fin[0]["choices"][0]["finish_reason"] == "stop" and r.text.rstrip().endswith("data: [DONE]")
assert ev[-1]["usage"]["completion_tokens"] > 0 and ev[-1]["choices"] == []
full = client.post("/v1/chat/completions", json=chat_body("OCR:")).json()["choices"][0]["message"]["content"]
assert content == full
def test_chat_length_stop(client):
d = client.post("/v1/chat/completions", json=chat_body("OCR:", max_tokens=2)).json()
assert d["choices"][0]["finish_reason"] == "length" and d["usage"]["completion_tokens"] == 2
@pytest.mark.parametrize("mut,status", [
(lambda b: b.update(n=2), 400), (lambda b: b.update(stop=["x"]), 400), (lambda b: b.update(bogus=1), 400),
(lambda b: b.update(temperature=5), 400), (lambda b: b.update(top_k=1000), 400),
(lambda b: b.update(max_tokens=0), 400), (lambda b: b.update(frequency_penalty=0.5), 400),
(lambda b: b["messages"].insert(0, {"role": "system", "content": "be nice"}), 400),
(lambda b: b["messages"].append({"role": "assistant", "content": "x"}), 400),
(lambda b: b["messages"][0].update(content="no image"), 400),
(lambda b: b["messages"][0]["content"].append(dict(b["messages"][0]["content"][0])), 400),
(lambda b: b["messages"][0]["content"][0]["image_url"].update(url="data:image/png;base64,!!!"), 400),
(lambda b: b["messages"][0]["content"][0]["image_url"].update(url="https://example.com/x.png"), 400),
(lambda b: b["messages"][0]["content"][0]["image_url"].update(url="data:image/png;base64,aGVsbG8="), 400),
(lambda b: b.update(task="layout"), 400), (lambda b: b.update(max_pixels=10 ** 9), 400),
(lambda b: b.update(task="custom"), 400),
])
def test_chat_refusals(client, mut, status):
b = chat_body("OCR:")
mut(b)
r = client.post("/v1/chat/completions", json=b)
assert r.status_code == status, (r.status_code, r.text)
def test_chat_lone_surrogate_is_400(client):
body = {"messages": [{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + b64()}},
{"type": "text", "text": "read \ud800 this"}]}]}
r = client.post("/v1/chat/completions", content=json.dumps(body).encode(),
headers={"content-type": "application/json"})
assert r.status_code == 400, (r.status_code, r.text)
def test_chat_stream_refusal_is_http_400(client):
r = client.post("/v1/chat/completions", json=chat_body("OCR:", stream=True, temperature=9))
assert r.status_code == 400
def test_chat_empty_system_message_ignored(client):
b = chat_body("OCR:")
b["messages"].insert(0, {"role": "system", "content": ""})
assert client.post("/v1/chat/completions", json=b).status_code == 200
def test_ocr_json_multipart_raw(client):
r = client.post("/ocr", json={"image": b64(), "task": "table", "return_tokens": True})
assert r.status_code == 200, r.text
d = r.json()
assert d["task"] == "table" and d["tokens"][-1] == 2 and d["result"]["rows"][0] == ["Model", "Score"]
assert set(d["timings"]) >= {"preprocess", "request", "total"}
files = {"file": ("t.png", open(os.path.join(SAMPLES, "text_en_line.png"), "rb"), "image/png")}
r = client.post("/ocr", files=files, data={"task": "spotting", "max_new_tokens": "64"})
assert r.status_code == 200, r.text
assert len(r.json()["result"]["items"]) == 2
raw = open(os.path.join(SAMPLES, "formula_1.png"), "rb").read()
r = client.post("/ocr?task=formula", content=raw, headers={"content-type": "image/png"})
assert r.status_code == 200 and r.json()["result"]["latex"]
r = client.post("/v1/ocr", json={"image": "data:image/png;base64," + b64(), "task": "seal"})
assert r.status_code == 200 and r.json()["task"] == "seal"
def test_ocr_stream(client):
r = client.post("/ocr", json={"image": b64("text_zh_line.png"), "stream": True})
ev = sse(r.text)
deltas = "".join(e["delta"] for e in ev if e["type"] == "delta")
done = [e for e in ev if e["type"] == "done"]
assert done and done[0]["text"] == deltas and done[0]["stop"] == "eos"
@pytest.mark.parametrize("body,ctype,status", [
({"task": "ocr"}, "json", 400), ({"image": b64(), "foo": 1}, "json", 400),
({"image": b64(), "task": "nope"}, "json", 400), (b"x", "text/plain", 415), (b"{", "application/json", 422),
({"image": b64(), "prompt": "OCR \ud800"}, "json-ascii", 400), # lone surrogate: valid JSON, not text (F4)
])
def test_ocr_refusals(client, body, ctype, status):
if ctype == "json":
r = client.post("/ocr", json=body)
elif ctype == "json-ascii": # json.dumps escapes the surrogate as \ud800 (what a client sends)
r = client.post("/ocr", content=json.dumps(body).encode(), headers={"content-type": "application/json"})
else:
r = client.post("/ocr", content=body, headers={"content-type": ctype})
assert r.status_code == status, (r.status_code, r.text)
def test_body_limit():
os.environ.update(PADDLEOCR_BACKEND="fake", PADDLEOCR_MAX_BODY_MB="1")
from tt_paddleocr.server.app import create_app
try:
with TestClient(create_app()) as c:
r = c.post("/ocr", content=b"0" * (2 << 20), headers={"content-type": "image/png"})
assert r.status_code == 413
finally:
os.environ.pop("PADDLEOCR_MAX_BODY_MB", None)
def test_vl_profile_tasks():
os.environ.update(PADDLEOCR_BACKEND="fake", PADDLEOCR_PROFILE="vl")
from tt_paddleocr.server.app import create_app
try:
with TestClient(create_app()) as c:
assert c.post("/v1/chat/completions", json=chat_body("Spotting:")).status_code == 400
d = c.post("/v1/chat/completions", json=chat_body("Chart Recognition:")).json()
assert d["paddleocr"]["task"] == "chart" and c.get("/info").json()["profile"] == "vl"
finally:
os.environ.pop("PADDLEOCR_PROFILE", None)
def test_bad_config_refuses_start():
os.environ.update(PADDLEOCR_BACKEND="fake", PADDLEOCR_PROFILE="9.9")
from tt_paddleocr.server.app import create_app
try:
with pytest.raises(RuntimeError):
with TestClient(create_app()):
pass
finally:
os.environ.pop("PADDLEOCR_PROFILE", None)
def test_mesh_shape():
from tt_paddleocr.server.app import load_config, parse_mesh_shape
assert parse_mesh_shape("1x1") == parse_mesh_shape("(1, 1)") == parse_mesh_shape("1,1") == (1, 1)
with pytest.raises(RuntimeError):
load_config({"TT_MESH_SHAPE": "1x2"})