"""Test the same real camera frames against Imajev, one question per HTTP request.""" import argparse import hashlib import io import json from pathlib import Path import statistics import time import urllib.error import urllib.request import uuid def post(endpoint, image, question_id, question): boundary = uuid.uuid4().hex request = {"state": {}, "questions": {question_id: {"type": "noul", "instructions": question}}} body = (f'--{boundary}\r\nContent-Disposition: form-data; name="request"\r\n\r\n'.encode() + json.dumps(request).encode() + f'\r\n--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="camera.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'.encode() + image + f'\r\n--{boundary}--\r\n'.encode()) req = urllib.request.Request(endpoint, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) started = time.perf_counter() with urllib.request.urlopen(req, timeout=180) as response: content = response.read() elapsed = (time.perf_counter() - started) * 1000 return json.loads(content), elapsed def main(): from PIL import Image parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--endpoint", default="http://127.0.0.1:8765/v1/systemone") parser.add_argument("--count", type=int, default=5) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() root = Path(__file__).resolve().parents[1] / "artifacts/laya-box-benchmark" # Both were already inspected: the retake contains objects; the later hand-holding capture has an empty box and no hands. cases = [ ("nonempty_full", "hikvision-box-retake.jpg", None, "empty", "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box.", False), ("nonempty_crop", "hikvision-box-retake-crop.jpg", None, "empty", "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box.", False), ("empty_crop", "hikvision-hand-holding.jpg", (1060, 490, 1510, 1140), "empty", "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box.", True), ("no_hand", "hikvision-hand-holding.jpg", None, "holding", "Is there a visible hand holding an object in this image?", False), ("nonempty_opposite", "hikvision-box-retake-crop.jpg", None, "nonempty", "Are there any objects inside the open cardboard box?", True), ] report = {"endpoint": args.endpoint, "image_max_edge": 512, "timing_scope": "HTTP send to complete response; excludes image preparation; one untimed warmup per case recorded separately", "cases": []} args.output.parent.mkdir(parents=True, exist_ok=True) for name, filename, crop, question_id, question, expected in cases: source = root / filename with Image.open(source) as original: image = original.convert("RGB") if crop: image = image.crop(crop) image.thumbnail((512, 512)) buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=95) data = buffer.getvalue() digest = hashlib.sha256(data).hexdigest() prepared = args.output.parent / f"{name}-input.jpg" prepared.write_bytes(data) row = {"case": name, "source": str(source), "crop_xyxy": crop, "input": str(prepared), "upload_sha256": digest, "input_size": list(image.size), "question_id": question_id, "question": question, "expected_yes": expected, "runs": []} warmup, elapsed = post(args.endpoint, data, question_id, question) row["warmup"] = {"http_ms": round(elapsed, 2), "response": warmup} report["cases"].append(row) print(json.dumps({"case": name, "stage": "warmup", "http_ms": round(elapsed, 2), "answer": warmup["answers"][question_id]}, ensure_ascii=False), flush=True) for index in range(args.count): result, elapsed = post(args.endpoint, data, question_id, question) if result["usage"]["images"][0]["sha256"] != digest: raise RuntimeError("Server image hash does not match upload") answer = result["answers"][question_id] probability = answer["noul"] run = {"run": index + 1, "http_ms": round(elapsed, 2), "server_ms": result["usage"]["total_ms"], "yes_probability": probability, "unknown_probability": answer["unknown_probability"], "abstained": answer["abstained"], "prediction_yes": probability >= .5, "correct": not answer["abstained"] and (probability >= .5) == expected, "response": result} row["runs"].append(run) args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") print(json.dumps({"case": name, **{key: value for key, value in run.items() if key != "response"}}, ensure_ascii=False), flush=True) durations = [run["http_ms"] for run in row["runs"]] row["summary"] = {"mean_http_ms": round(statistics.mean(durations), 2), "min_http_ms": min(durations), "max_http_ms": max(durations), "under_200ms": sum(ms < 200 for ms in durations), "correct_count": sum(run["correct"] for run in row["runs"])} args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") print(json.dumps({"case": name, **row["summary"]}), flush=True) if __name__ == "__main__": main()