"""
build_report.py
对 face/test_img/girl 与 face/test_img/man 下的照片批量预测脸型,
在照片上标注 face_width / face_height 等特征,并生成 HTML 报告。
用法:
./venv/bin/python face/build_report.py
输出:
static/face_shape_report.html
static/face_shape_report/images/*.jpg
"""
from __future__ import annotations
import html
import re
import shutil
import sys
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Dict, List
import cv2
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from face.face_shape_classifier import classify_from_image # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
SRC_DIRS = {
"女": ROOT / "face/test_img/girl",
"男": ROOT / "face/test_img/man",
}
OUT_DIR = ROOT / "static/face_shape_report"
IMG_DIR = OUT_DIR / "images"
OUT_HTML = ROOT / "static/face_shape_report.html"
MAX_IMAGE_SIDE = 900
JPEG_QUALITY = 90
SHAPE_ORDER = ["圆形脸", "心形脸", "菱形脸", "鹅蛋脸", "方形脸", "长形脸", "瓜子脸"]
SHAPE_COLORS = {
"圆形脸": "#e67e22",
"心形脸": "#e74c3c",
"菱形脸": "#9b59b6",
"鹅蛋脸": "#27ae60",
"方形脸": "#2980b9",
"长形脸": "#16a085",
"瓜子脸": "#c0392b",
}
FEATURE_KEYS = [
"face_width",
"face_height",
"jaw_angle",
"taper_ratio",
"forehead_ratio",
"cheekbone_ratio",
"jaw_ratio",
"chin_ratio",
"chin_sharpness",
"width_uniformity",
"face_curve_score",
]
def natural_key(path: Path):
m = re.search(r"(\d+)", path.stem)
return (0, int(m.group(1))) if m else (1, path.stem)
def analyze_all() -> tuple[List[Dict], Dict[str, Counter]]:
if IMG_DIR.exists():
shutil.rmtree(IMG_DIR)
IMG_DIR.mkdir(parents=True)
rows: List[Dict] = []
summary = {"女": Counter(), "男": Counter(), "all": Counter()}
for gender, src in SRC_DIRS.items():
prefix = "girl" if gender == "女" else "man"
paths = sorted(
[p for p in src.iterdir() if p.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp"}],
key=natural_key,
)
for path in paths:
m = re.search(r"(\d+)", path.stem)
out_name = f"{prefix}_{int(m.group(1)) if m else 0:02d}.jpg"
dest = IMG_DIR / out_name
item = {
"gender": gender,
"file": path.name,
"img_src": f"face_shape_report/images/{out_name}",
"ok": False,
"predicted": None,
"display": None,
"confidence": None,
"score": None,
"top3": [],
"features": {},
"error": None,
}
try:
result = classify_from_image(path, return_details=True, return_annotated=True)
annotated = result["annotated"]
h, w = annotated.shape[:2]
if max(h, w) > MAX_IMAGE_SIDE:
scale = MAX_IMAGE_SIDE / max(h, w)
annotated = cv2.resize(
annotated, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA
)
cv2.imwrite(str(dest), annotated, [int(cv2.IMWRITE_JPEG_QUALITY), JPEG_QUALITY])
item.update(
{
"ok": True,
"predicted": result["face_shape"],
"display": result["display"],
"confidence": result["confidence"],
"score": result["details"]["ranked"][0][1],
"top3": result["details"]["ranked"][:3],
"features": {k: result["features"][k] for k in FEATURE_KEYS},
}
)
summary[gender][result["face_shape"]] += 1
summary["all"][result["face_shape"]] += 1
except Exception as exc: # noqa: BLE001 - 报告需要汇总所有失败
img = cv2.imread(str(path))
if img is not None:
cv2.imwrite(str(dest), img, [int(cv2.IMWRITE_JPEG_QUALITY), JPEG_QUALITY])
item["error"] = str(exc)
summary[gender]["检测失败"] += 1
summary["all"]["检测失败"] += 1
rows.append(item)
print(f"[{gender}] {path.name} -> {item['display'] or 'ERR ' + str(item['error'])}")
return rows, summary
def count_table(counter: Counter) -> str:
if not counter:
return "
无数据
"
total = sum(counter.values())
parts = []
for shape, n in sorted(counter.items(), key=lambda x: (-x[1], x[0])):
color = SHAPE_COLORS.get(shape, "#7f8c8d")
pct = n / total * 100
parts.append(
f"
{html.escape(shape)}"
f"
"
f"{n}({pct:.0f}%)
"
)
return "".join(parts)
def fmt_feat(key: str, value: float) -> str:
if key in {"face_width", "face_height"}:
return f"{value:.1f}px"
if key == "jaw_angle":
return f"{value:.1f}°"
return f"{value:.3f}"
def card(item: Dict) -> str:
if not item["ok"]:
return f"""
{html.escape(item['file'])}
检测失败
{html.escape(item['error'] or '')}
"""
color = SHAPE_COLORS.get(item["predicted"], "#34495e")
top3 = "".join(
f"
{html.escape(name)}{score:.1f}
" for name, score in item["top3"]
)
feat_html = "".join(
f"
{html.escape(k)}
{html.escape(fmt_feat(k, v))}
"
for k, v in item["features"].items()
)
return f"""