chore: 添加前端还原工具并完善提交流程,移除旧指南
- 添加前端还原技能、截图比较工具和可复现测试 - 添加技能副本同步脚本及回归测试 - 补充提交前 SSH 配置与远程连通性检查 - 删除旧 CLI 指南并清理失效的 ESLint 配置 - 忽略 Python 缓存、虚拟环境和本地工具配置
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare equal-sized screenshots without resizing or hiding differences."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def unit_ratio(value):
|
||||
number = float(value)
|
||||
if not math.isfinite(number) or not 0 <= number <= 1:
|
||||
raise argparse.ArgumentTypeError("must be a finite number between 0 and 1")
|
||||
return number
|
||||
|
||||
|
||||
def channel_tolerance(value):
|
||||
number = int(value)
|
||||
if not 0 <= number <= 255:
|
||||
raise argparse.ArgumentTypeError("must be an integer between 0 and 255")
|
||||
return number
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--reference", required=True, type=Path)
|
||||
parser.add_argument("--actual", required=True, type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--channel-tolerance", default=0, type=channel_tolerance)
|
||||
parser.add_argument("--max-diff-ratio", default=0.0, type=unit_ratio)
|
||||
parser.add_argument("--allow-lossy", action="store_true",
|
||||
help="Explicitly allow JPEG captures; decoded-pixel equality is not lossless render equality")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
try:
|
||||
from PIL import Image, ImageChops, ImageStat
|
||||
except ImportError:
|
||||
print("Pillow is required. Install it in your tool environment: python -m pip install Pillow", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
try:
|
||||
reference_path = args.reference.resolve(strict=True)
|
||||
actual_path = args.actual.resolve(strict=True)
|
||||
output_path = args.output.resolve()
|
||||
if output_path.exists():
|
||||
raise ValueError("Output directory already exists; choose a new directory to preserve evidence")
|
||||
|
||||
def load_image(path):
|
||||
with Image.open(path) as source:
|
||||
image_format = source.format
|
||||
allowed = {"PNG", "JPEG"} if args.allow_lossy else {"PNG"}
|
||||
if image_format not in allowed:
|
||||
raise ValueError(f"Expected PNG; JPEG requires --allow-lossy: {path}")
|
||||
if getattr(source, "n_frames", 1) != 1:
|
||||
raise ValueError(f"Animated PNG is not supported: {path}")
|
||||
rgba = source.convert("RGBA")
|
||||
background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
|
||||
return Image.alpha_composite(background, rgba).convert("RGB"), image_format
|
||||
|
||||
reference, reference_format = load_image(reference_path)
|
||||
actual, actual_format = load_image(actual_path)
|
||||
lossy_input = "JPEG" in (reference_format, actual_format)
|
||||
result = {
|
||||
"reference": str(reference_path),
|
||||
"actual": str(actual_path),
|
||||
"reference_size": list(reference.size),
|
||||
"actual_size": list(actual.size),
|
||||
"channel_tolerance": args.channel_tolerance,
|
||||
"max_diff_ratio": args.max_diff_ratio,
|
||||
"reference_format": reference_format,
|
||||
"actual_format": actual_format,
|
||||
"lossy_input": lossy_input,
|
||||
"warning": ("JPEG compression is present. Metrics describe decoded captures, not lossless render fidelity."
|
||||
if lossy_input else None),
|
||||
"comparison": "RGB after alpha compositing onto white; no resize, blur, mask, or color-profile conversion",
|
||||
}
|
||||
|
||||
if reference.size != actual.size:
|
||||
result.update(status="FAIL", reason="Image dimensions differ; no resampling performed")
|
||||
else:
|
||||
delta = ImageChops.difference(reference, actual)
|
||||
red, green, blue = delta.split()
|
||||
max_channel_delta = ImageChops.lighter(ImageChops.lighter(red, green), blue)
|
||||
lookup = [255 if value > args.channel_tolerance else 0 for value in range(256)]
|
||||
mask = max_channel_delta.point(lookup)
|
||||
diff_pixels = mask.histogram()[255]
|
||||
pixel_count = reference.width * reference.height
|
||||
diff_ratio = diff_pixels / pixel_count
|
||||
mean_error = sum(ImageStat.Stat(delta).mean) / 3
|
||||
passed = diff_ratio <= args.max_diff_ratio
|
||||
result.update(
|
||||
status="PASS" if passed else "FAIL",
|
||||
pixel_count=pixel_count,
|
||||
diff_pixels=diff_pixels,
|
||||
diff_ratio=diff_ratio,
|
||||
mean_absolute_rgb_error=mean_error,
|
||||
max_channel_error=max_channel_delta.getextrema()[1],
|
||||
difference_bbox=list(mask.getbbox()) if mask.getbbox() else None,
|
||||
)
|
||||
marked = actual.copy()
|
||||
marked.paste((255, 0, 0), mask=mask)
|
||||
overlay = Image.blend(reference, actual, 0.5)
|
||||
|
||||
# Reserve a fresh directory only after validating and loading both inputs.
|
||||
output_path.mkdir(parents=True, exist_ok=False)
|
||||
if reference.size == actual.size:
|
||||
marked.save(output_path / "diff.png")
|
||||
overlay.save(output_path / "overlay.png")
|
||||
result["diff_image"] = str(output_path / "diff.png")
|
||||
result["overlay_image"] = str(output_path / "overlay.png")
|
||||
report_path = output_path / "result.json"
|
||||
report_path.write_text(json.dumps(result, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"status": result["status"], "report": str(report_path)}, ensure_ascii=True))
|
||||
return 0 if result["status"] == "PASS" else 1
|
||||
except (OSError, ValueError, Image.DecompressionBombError) as error:
|
||||
print(f"Screenshot comparison failed: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user