cmvr-visual/inference/scripts/verify_existing_qwen.py

247 lines
11 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""Verify the existing Qwen endpoint with sequential math and real image inputs.
No service is started or changed. Images and the actual response report are written
inside the selected workspace. A successful HTTP response alone never passes the
visual checks.
"""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
import math
from pathlib import Path
import re
import sys
from typing import Any, Callable
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
VISUAL_PROMPT = (
"Inspect the actual attached image. Return one JSON object only, with these "
"required fields: background_color (a simple English color name), shape "
"(square or circle), shape_color (a simple English color name), subjects "
"(an array of visible subjects), scene (a short description), and ocr "
"(an array of visible text strings; use [] when there is no text). "
"Do not infer image contents from the filename."
)
EXPECTED_IMAGES = (
("red_blue_square.png", {"background_color": "red", "shape": "square", "shape_color": "blue"}),
("green_yellow_circle.png", {"background_color": "green", "shape": "circle", "shape_color": "yellow"}),
)
REQUIRED_FIELDS = {"background_color", "shape", "shape_color", "subjects", "scene", "ocr"}
ALIASES = {
"red": "red", "红": "red", "红色": "red",
"green": "green", "绿": "green", "绿色": "green",
"blue": "blue", "蓝": "blue", "蓝色": "blue",
"yellow": "yellow", "黄": "yellow", "黄色": "yellow",
"square": "square", "正方形": "square", "方块": "square",
"circle": "circle", "圆": "circle", "圆形": "circle", "圆圈": "circle",
}
def inside_workspace(workspace: Path, value: str | Path) -> Path:
path = Path(value).expanduser()
if not path.is_absolute():
path = workspace / path
path = path.resolve()
if not path.is_relative_to(workspace):
raise ValueError(f"Path must stay inside workspace: {value}")
return path
def parse_json(content: str) -> Any:
text = content.strip()
if text.startswith("```"):
text = re.sub(r"^```(?:json)?\s*", "", text, count=1, flags=re.IGNORECASE)
text = re.sub(r"\s*```$", "", text, count=1)
try:
return json.loads(text)
except (ValueError, TypeError):
return None
def canonical(value: Any) -> str | None:
return ALIASES.get(value.strip().casefold()) if isinstance(value, str) else None
def math_is_five(content: str, parsed: Any) -> bool:
if isinstance(parsed, (int, float)) and not isinstance(parsed, bool):
return math.isfinite(parsed) and parsed == 5
# The prompt requests an integer; also accept short conventional answer forms.
answer = re.fullmatch(
r"(?:2\s*\+\s*3\s*=\s*|(?:the\s+)?(?:answer|result)\s*(?:is\s*|[:=]\s*)"
r"|(?:答案|结果)\s*(?:是|为|[::=])?\s*)?"
r"(?:\\boxed\s*\{\s*)?5(?:\.0+)?\s*\}?\s*[.!。!]?",
content.strip(), re.IGNORECASE,
)
return answer is not None
def exception_response(error: Exception) -> Any:
raw = getattr(error, "raw_response", None)
if raw is not None:
return raw
response = getattr(error, "response", None)
if response is not None:
try:
return response.json()
except (ValueError, AttributeError):
return {"status_code": getattr(response, "status_code", None),
"body": getattr(response, "text", None)}
return None
def call_and_record(name: str, kind: str, operation: Callable[[], dict[str, Any]]) -> dict[str, Any]:
record: dict[str, Any] = {
"name": name, "kind": kind, "content": "", "reasoning_content": None,
"usage": {}, "raw_response": None, "parsed": None,
"checks": {}, "passed": False, "error": None,
}
try:
response = operation()
if not isinstance(response, dict):
raise TypeError("QwenClient must return a response dictionary")
record["raw_response"] = response.get("raw_response")
record["content"] = response.get("content", "")
record["reasoning_content"] = response.get("reasoning_content")
record["usage"] = response.get("usage", {})
if not isinstance(record["content"], str):
raise TypeError("QwenClient response content must be a string")
record["parsed"] = response.get("structured")
if record["parsed"] is None:
record["parsed"] = parse_json(record["content"])
except Exception as error:
if record["raw_response"] is None:
record["raw_response"] = exception_response(error)
record["error"] = {"type": type(error).__name__, "message": str(error)}
return record
def check_visual(record: dict[str, Any], expected: dict[str, str]) -> dict[str, str | None] | None:
parsed = record["parsed"]
# A single-object JSON array retains its original form in the report.
if isinstance(parsed, list) and len(parsed) == 1:
parsed = parsed[0]
is_object = isinstance(parsed, dict)
fields = {key: canonical(parsed.get(key)) for key in expected} if is_object else None
record["checks"] = {
"request_succeeded": record["error"] is None,
"structured_object": is_object,
"required_fields_present": is_object and REQUIRED_FIELDS.issubset(parsed),
**{f"{key}_matches": fields is not None and fields[key] == value
for key, value in expected.items()},
}
record["passed"] = all(record["checks"].values())
record["normalized_visual"] = fields
return fields
def generate_images(workspace: Path, output: Path) -> list[Path]:
from PIL import Image, ImageDraw
paths = [inside_workspace(workspace, output / name) for name, _ in EXPECTED_IMAGES]
for path, background, foreground, shape in (
(paths[0], (255, 0, 0), (0, 0, 255), "square"),
(paths[1], (0, 255, 0), (255, 255, 0), "circle"),
):
image = Image.new("RGB", (256, 256), background)
draw = ImageDraw.Draw(image)
if shape == "square":
draw.rectangle((64, 64, 191, 191), fill=foreground)
else:
draw.ellipse((64, 64, 191, 191), fill=foreground)
image.save(path, format="PNG")
return paths
def positive_timeout(value: str) -> float:
timeout = float(value)
if not math.isfinite(timeout) or timeout <= 0:
raise argparse.ArgumentTypeError("timeout must be a positive finite number")
return timeout
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", help="Existing Qwen API base; defaults to QWEN_API_BASE")
parser.add_argument("--model", help="Served model name; defaults to QWEN_MODEL")
parser.add_argument("--workspace-root", default="/workspace", help="Allowed workspace root")
parser.add_argument("--output-dir", default="outputs/verification",
help="Report/image directory, relative to the workspace or inside it")
parser.add_argument("--timeout", type=positive_timeout, default=120.0,
help="Timeout in seconds for each sequential request (default: 120)")
args = parser.parse_args(argv)
workspace = Path(args.workspace_root).expanduser().resolve()
report: dict[str, Any] = {
"schema_version": 1, "started_at": datetime.now(timezone.utc).isoformat(),
"workspace_root": str(workspace), "passed": False, "results": [],
"checks": {"math_correct": False, "first_image_matches": False,
"second_image_matches": False, "visual_outputs_differ": False},
"errors": [],
}
output: Path | None = None
try:
output = inside_workspace(workspace, args.output_dir)
output.mkdir(parents=True, exist_ok=True)
# Validate every final file before saving images or making any requests.
inside_workspace(workspace, output / "report.json")
images = generate_images(workspace, output)
from llm_services.qwen_client import QwenClient
client = QwenClient(base_url=args.base_url, model=args.model, api_key=None,
workspace_root=str(workspace), enable_thinking=False,
timeout=args.timeout)
question = "What is 2 + 3? Reply with only the integer answer."
result = call_and_record("math_2_plus_3", "math", lambda: client.solve_math(question))
result["question"] = question
result["checks"] = {
"request_succeeded": result["error"] is None,
"answer_is_5": math_is_five(result["content"], result["parsed"]),
}
result["passed"] = all(result["checks"].values())
report["results"].append(result)
report["checks"]["math_correct"] = result["passed"]
normalized = []
for index, (image_path, (_, expected)) in enumerate(zip(images, EXPECTED_IMAGES)):
result = call_and_record(image_path.stem, "vision",
lambda path=image_path: client.describe_image(path, VISUAL_PROMPT))
result.update({"image_path": str(image_path), "expected": expected, "prompt": VISUAL_PROMPT})
normalized.append(check_visual(result, expected))
report["results"].append(result)
report["checks"][("first_image_matches", "second_image_matches")[index]] = result["passed"]
report["checks"]["visual_outputs_differ"] = (
all(fields is not None and all(value is not None for value in fields.values())
for fields in normalized) and normalized[0] != normalized[1]
)
report["passed"] = all(report["checks"].values())
except Exception as error:
report["errors"].append({"type": type(error).__name__, "message": str(error)})
report["completed_at"] = datetime.now(timezone.utc).isoformat()
try:
# Invalid requested paths fail closed; a diagnostic may still be saved at
# the workspace root, never at an unvalidated external destination.
if output is None:
workspace.mkdir(parents=True, exist_ok=True)
report_path = inside_workspace(workspace, "verification_failure_report.json")
else:
report_path = inside_workspace(workspace, output / "report.json")
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
except (OSError, ValueError) as error:
print(f"FAILED: could not save verification report: {error}", file=sys.stderr)
return 1
print(f"{'PASSED' if report['passed'] else 'FAILED'}: {report_path}")
return 0 if report["passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())