110 lines
7.0 KiB
Python
110 lines
7.0 KiB
Python
"""Compare a D3 service on the existing real camera controls, using ordinary short questions."""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import statistics
|
|
import time
|
|
import urllib.request
|
|
|
|
|
|
def post(endpoint, image, question, choices=None, state=""):
|
|
field = {"type": "choice" if choices else "noul", "instructions": question}
|
|
if choices:
|
|
field["criteria"] = choices
|
|
payload = {"state": state, "questions": {"q": field}}
|
|
if image is not None:
|
|
payload["images"] = ["data:image/jpeg;base64," + base64.b64encode(image).decode()]
|
|
request = urllib.request.Request(endpoint, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers={"Content-Type": "application/json; charset=utf-8"})
|
|
started = time.perf_counter()
|
|
with urllib.request.urlopen(request, timeout=120) as response:
|
|
content = response.read()
|
|
elapsed = round((time.perf_counter() - started) * 1000, 2)
|
|
result = json.loads(content)
|
|
expected_hashes = [] if image is None else [hashlib.sha256(image).hexdigest()]
|
|
assert result["usage"]["image_sha256"] == expected_hashes
|
|
answer = result["answers"]["q"]
|
|
if "error" in answer:
|
|
raise RuntimeError(answer)
|
|
actual = answer["choice"] if choices else answer["noul"] > .5
|
|
return {"http_ms": elapsed, "actual": actual, "response": result}
|
|
|
|
|
|
def stats(runs):
|
|
values = sorted(row["http_ms"] for row in runs)
|
|
server = sorted(row["response"]["usage"]["server_ms"] for row in runs)
|
|
return {"count": len(runs), "mean_ms": round(statistics.mean(values), 2), "median_ms": round(statistics.median(values), 2), "p95_ms": values[math.ceil(.95 * len(values)) - 1], "max_ms": max(values), "server_mean_ms": round(statistics.mean(server), 2), "server_median_ms": round(statistics.median(server), 2), "server_p95_ms": server[math.ceil(.95 * len(server)) - 1], "under_200ms": sum(value < 200 for value in values), "under_500ms": sum(value < 500 for value in values)}
|
|
|
|
|
|
def main():
|
|
from PIL import Image
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--endpoint", default="http://127.0.0.1:8766/v1/systemone")
|
|
parser.add_argument("--count", type=int, default=5)
|
|
parser.add_argument("--warmup-count", type=int, default=1)
|
|
parser.add_argument("--image-root", type=Path)
|
|
parser.add_argument("--case", action="append", dest="selected_cases", help="Run only this case; repeat to select multiple cases")
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
if args.count < 1 or args.warmup_count < 1:
|
|
parser.error("--count and --warmup-count must be positive")
|
|
repo = Path(__file__).resolve().parents[1]
|
|
images = args.image_root or repo / "artifacts/imajev-benchmark"
|
|
colors = {"黄": "黄色", "绿": "绿色", "有红有蓝": "红色和蓝色都有"}
|
|
english_colors = {"yellow": "yellow", "green": "green", "red_and_blue": "both red and blue"}
|
|
cases = [
|
|
("非空盒_中文", "nonempty_crop-input.jpg", "盒子空了没?", None, False),
|
|
("非空盒_英文", "nonempty_crop-input.jpg", "Is the box empty?", None, False),
|
|
("空盒_中文", "empty_crop-input.jpg", "盒子空了没?", None, True),
|
|
("空盒_英文", "empty_crop-input.jpg", "Is the box empty?", None, True),
|
|
("无手_中文", "no_hand-input.jpg", "手里拿着东西吗?", None, False),
|
|
("无手_英文", "no_hand-input.jpg", "Is there a hand holding an object?", None, False),
|
|
("持物_中文", "hikvision-imajev-holding-20261112-194959-input.jpg", "手里拿着东西吗?", None, True),
|
|
("持物_英文", "hikvision-imajev-holding-20261112-194959-input.jpg", "Is there a hand holding an object?", None, True),
|
|
("颜色_中文", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "手里这东西是黄的、绿的,还是红蓝都有?", colors, "有红有蓝"),
|
|
("颜色_英文", "hikvision-imajev-color-20261112-195330-hand-crop-input.jpg", "What color is the object held in the hand?", english_colors, "red_and_blue"),
|
|
]
|
|
if args.selected_cases:
|
|
unknown = set(args.selected_cases) - {case[0] for case in cases}
|
|
if unknown:
|
|
parser.error(f"Unknown cases: {sorted(unknown)}")
|
|
cases = [case for case in cases if case[0] in args.selected_cases]
|
|
health_url = args.endpoint.rsplit("/v1/systemone", 1)[0] + "/health"
|
|
with urllib.request.urlopen(health_url, timeout=10) as response:
|
|
health = json.load(response)
|
|
report = {"model": health["model"], "endpoint": args.endpoint, "health": health, "warmup_count": args.warmup_count, "scope": "Prepared JPEG bytes without recompression; one question per request; per-case warmups excluded from statistics; HTTP timing excludes image preparation and server_ms comes from the service", "note": "The upstream D3 response has no automatic abstention/unknown field; confidence is not a correctness guarantee", "cases": []}
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
for name, filename, question, choices, expected in cases:
|
|
source = images / filename
|
|
# Reuse the exact prepared JPEG bytes from the Imajev test, without recompression.
|
|
data = source.read_bytes()
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
size = image.size
|
|
row = {"case": name, "input": str(source), "image_size": size, "image_sha256": hashlib.sha256(data).hexdigest(),
|
|
"question": question, "choices": choices, "expected": expected, "runs": []}
|
|
row["warmups"] = [post(args.endpoint, data, question, choices) for _ in range(args.warmup_count)]
|
|
row["warmup"] = row["warmups"][0]
|
|
assert all(run["response"]["model"] == report["model"] for run in row["warmups"]), "Served model changed during benchmark"
|
|
report["cases"].append(row)
|
|
for _ in range(args.count):
|
|
run = post(args.endpoint, data, question, choices)
|
|
assert run["response"]["model"] == report["model"], "Served model changed during benchmark"
|
|
assert run["response"]["model"] == report["model"], "Served model changed during benchmark"
|
|
run["correct"] = run["actual"] == expected
|
|
row["runs"].append(run)
|
|
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
row["summary"] = {**stats(row["runs"]), "correct": sum(run["correct"] for run in row["runs"])}
|
|
print(json.dumps({"case": name, "actual": row["runs"][0]["actual"], "answer": row["runs"][0]["response"]["answers"]["q"], **row["summary"]}, ensure_ascii=False), flush=True)
|
|
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
all_runs = [run for case in report["cases"] for run in case["runs"]]
|
|
report["summary"] = {**stats(all_runs), "correct": sum(run["correct"] for run in all_runs)}
|
|
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(json.dumps(report["summary"]), flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|