Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2cee2f7277 | ||
|
|
14562d4869 | ||
|
|
3f8d90d963 | ||
|
|
a3587a2561 | ||
|
|
0c7bcfc83d | ||
|
|
e0d1a5f628 | ||
|
|
6c611359bc | ||
|
|
b215f81ca3 | ||
|
|
3e4fc758ea | ||
|
|
cace9d6cd4 | ||
|
|
ee33632f44 | ||
|
|
e3bd3a8916 | ||
|
|
1ff493a1a3 | ||
|
|
d1af9101c6 | ||
|
|
718372dc07 | ||
|
|
3a7c3fa07b | ||
|
|
b61ea6f33b | ||
|
|
b354c8c627 | ||
|
|
fd9c41430c | ||
|
|
5101bb5f6b | ||
|
|
ff4019c570 | ||
|
|
5226e23989 | ||
|
|
c462fd3634 | ||
|
|
ab6b0cb0bb | ||
|
|
94cdfd6de5 |
@@ -53,3 +53,28 @@ static/report_hairline_v2.zip
|
||||
# local_test 运行期日志 / pid(不入 git)
|
||||
local_test/hair_service.log
|
||||
local_test/hair_service.pid
|
||||
|
||||
# benchmark 原始输出(含结果图+原图,体积大,不入 git)
|
||||
benchmark_out/
|
||||
|
||||
# benchmark 部署的 HTML 报告(图片 base64 内嵌,体积大,不入 git)
|
||||
static/hairstyle_thumbs/
|
||||
|
||||
# 网关运行期日志(不入 git)
|
||||
gateway.log
|
||||
|
||||
# 工作流备份文件(不入 git)
|
||||
*.json.bak.*
|
||||
|
||||
# 分辨率对比测试产物(out/ 下结果图+原图副本+日志,体积大,不入 git)
|
||||
# 仅忽略 out/ 与运行期文件;测试脚本与 HTML 报告仍入库
|
||||
image/compare_test/out/
|
||||
image/res_test/out/
|
||||
image/wave_test/out/
|
||||
image/compare_test/progress.json
|
||||
image/res_test/progress.json
|
||||
image/wave_test/progress.json
|
||||
image/compare_test/batch_test.log
|
||||
image/res_test/batch_test.log
|
||||
image/wave_test/batch_test.log
|
||||
image/compare_test/http.log
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"16": {
|
||||
"class_type": "UNETLoader",
|
||||
"class_type": "UnetLoaderGGUF",
|
||||
"inputs": {
|
||||
"unet_name": "flux-2-klein-4b-fp8.safetensors",
|
||||
"unet_name": "flux-2-klein-9b-Q4_K_M.gguf",
|
||||
"weight_dtype": "fp8_e4m3fn_fast"
|
||||
}
|
||||
},
|
||||
@@ -15,7 +15,7 @@
|
||||
"61": {
|
||||
"class_type": "CLIPLoader",
|
||||
"inputs": {
|
||||
"clip_name": "qwen_3_4b.safetensors",
|
||||
"clip_name": "qwen_3_8b_fp8mixed.safetensors",
|
||||
"type": "flux2",
|
||||
"device": "cpu"
|
||||
}
|
||||
@@ -29,7 +29,7 @@
|
||||
"60": {
|
||||
"class_type": "JjkText",
|
||||
"inputs": {
|
||||
"text": "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜"
|
||||
"text": "填充遮罩区域的头发,人物增加一点磨皮"
|
||||
}
|
||||
},
|
||||
"22": {
|
||||
|
||||
@@ -4,80 +4,100 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Overview
|
||||
|
||||
"旷视五接口" — a FastAPI facial analysis API service providing 5 endpoints for face measurement, hair growth simulation (C-end and B-end), user feature extraction, and hairline PNG generation. Currently a **Mock v1**: all endpoints return hardcoded sample data; real ML logic is pending.
|
||||
旷视接口服务 — FastAPI 人像分析/生发服务,**一个仓库、两种部署角色**:
|
||||
|
||||
- **Base URL (prod)**: `https://hair.xiangsilian.com`
|
||||
- **Swagger docs**: `https://hair.xiangsilian.com/docs`
|
||||
- **Internal**: uvicorn on `127.0.0.1:8000` behind nginx reverse proxy
|
||||
- **worker**(`app.py` + `face_analysis/` + `hairline/`):跑真实算法(本地模型 + ComfyUI + change_hair),监听 `0.0.0.0:8187`。**本机(GPU 机)即 worker 角色**,不跑网关。
|
||||
- **网关**(`gateway/`):外网机器上的薄反向代理,负责鉴权/健康检查/派发,并把 worker 返回的 `*_base64` 落盘改写为 `*_url`。接口4(豆包)和接口99(人脸特殊点,纯 CPU)在网关本机实现,不转发 worker。
|
||||
|
||||
> 历史包袱:`app.py` 的 FastAPI `description` 和 `docs/接口文档.md` 部分示例仍写「Mock 第一版」字样,实际全部接口已是真实算法实现。**架构以 `docs/实现说明.md` 为准,契约以 `docs/接口文档.md` 为准。**
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Development server
|
||||
./venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000 --reload
|
||||
# ---- worker(本机)----
|
||||
./run_worker.sh # 后台启动(0.0.0.0:8187,日志 worker.log)
|
||||
FOREGROUND=1 ./run_worker.sh # 前台调试
|
||||
./stop_worker.sh # 停止
|
||||
sudo systemctl restart hair-worker # systemd 方式(生产)
|
||||
journalctl -u hair-worker -f
|
||||
|
||||
# Or via the start script
|
||||
./start.sh
|
||||
# ---- 依赖服务(worker 之前要先起)----
|
||||
sudo systemctl start comfyui # ComfyUI 127.0.0.1:8188(Flux-2 生图)
|
||||
cd /home/ubuntu/change_hair && bash start_all.sh start # 换发型三件套 8801/32678/57860
|
||||
|
||||
# Production (systemd)
|
||||
sudo systemctl restart hair
|
||||
sudo systemctl status hair
|
||||
journalctl -u hair -f
|
||||
|
||||
# Install dependencies (uses Tencent Cloud PyPI mirror)
|
||||
./venv/bin/pip install -r requirements.txt
|
||||
# ---- 测试 ----
|
||||
./venv/bin/pytest tests/ # 单元测试(conftest 会准备 fixtures)
|
||||
./venv/bin/python -m hairline.comfyui tests/output/comfy_input.png # 手动跑一次生发工作流
|
||||
```
|
||||
|
||||
依赖装在 `./venv`(Python 3.10,torch 2.7.1+cu128,RTX 4090 CUDA 可用)。`requirements.txt` 里的 torch 2.2.2/5090 注释是旧机器的记录,本机 venv 实际是 cu128 版。
|
||||
|
||||
## Architecture
|
||||
|
||||
**Single-file app** — `app.py` (~555 lines) contains the entire server: FastAPI app creation, Pydantic models, all 5 endpoint handlers, and health check routes. There are no separate routers, services, or middleware modules.
|
||||
### 接口一览(worker 侧路由,`app.py`)
|
||||
|
||||
### Endpoints
|
||||
| 接口 | 路径 | 实现位置 | 说明 |
|
||||
|------|------|----------|------|
|
||||
| 1 | `POST /api/v1/face/measure` | `face_analysis/` | 四庭七眼测量 + 标注 PNG |
|
||||
| 6 | `POST /api/v1/face/measure-v2` | 同上(`variant="v6"`) | 接口1 去顶庭变体 |
|
||||
| 2 | `POST /api/v1/hair/grow` | `hairline/service.py` | C端生发。**female 1..5** 走 change_hair swapHair + Flux-2 整帧重绘(接口12 final 管线);**female 6/7 与 male 全部**走 ComfyUI `add_hair.json` inpaint |
|
||||
| 7 | `POST /api/v1/hair/grow-v2`(hidden/deprecated) | 同上 | 同接口2,用 `add_hair2.json` 工作流 |
|
||||
| 3 | `POST /api/v1/hair/grow-b` | `hairline/marker_detect.py` | B端马克笔划线生发(黑帽响应 + Dijkstra) |
|
||||
| 4 | `POST /api/v1/face/features` | worker 有实现;生产走**网关本机**(豆包) | 用户特征 |
|
||||
| 5 | `POST /api/v1/hairline/generate` | `hairline/service.py` | 发际线 PNG 三档(middle/high/low)+ 生发 |
|
||||
| 9 | `POST /api/v1/head/mask` | `face_analysis/head_mask.py` | 头发遮罩 + 分步可视化(BiSeNet/SegFormer 双路) |
|
||||
| 10 | `POST /api/v1/head/band` | `face_analysis/head_band.py` | 头部外缘膨胀带遮罩 |
|
||||
| 11 | `POST /api/v1/hairline/grow` | `face_analysis/hairline_grow.py` | 发际线生发(接口9 遮罩 + change_hair + 接缝融合),不含重绘 |
|
||||
| 12 | `POST /api/v1/hairline/grow_v2` | 同上 | 接口11 final + 发际线重绘带 → Flux-2 保色重绘 |
|
||||
| 12f | `POST /api/v1/hairline/grow_v2_final` | 同上(`_V2_FINAL_DEFAULTS`) | 精简版:仅图片 + hairline_id,取整帧重绘 |
|
||||
| 12f2 | `POST /api/v1/hairline/grow_v2_final_v2` | 同上 | 同上,取 B 局部加发+全脸美颜 |
|
||||
| 99 | `POST /api/v1/face/special-points` | `face_analysis/special_points.py`(网关直接 import 本机实现 + `_if99_lock` 单路排队;worker 保留同路径备份) | 固定编号关键点 + 发际线特殊点(射线求交头发 mask)像素坐标 |
|
||||
| 代理 | `POST /api/swapHair/v1`、`/hairColor/v2` | httpx 转发 127.0.0.1:8801 | 解决测试页 CORS |
|
||||
| 工具 | `POST /api/v1/redraw` | `hairline/redraw.py` | 直接 ComfyUI 重绘(图+遮罩+prompt) |
|
||||
| 调试 | `POST /api/v1/debug/grow-timing`、`GET /api/v1/debug/hairline_log` | — | 免鉴权,分步计时/下载日志 |
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|--------|------|---------|
|
||||
| POST | `/api/v1/face/measure` | 四庭七眼 measurement + annotated PNG |
|
||||
| POST | `/api/v1/hair/grow` | C-end hair growth (user-facing) |
|
||||
| POST | `/api/v1/hair/grow-b` | B-end hair growth (doctor/operator, with marked image) |
|
||||
| POST | `/api/v1/face/features` | User facial feature analysis |
|
||||
| POST | `/api/v1/hairline/generate` | Hairline PNG generation |
|
||||
| GET | `/health` | Health check (excluded from OpenAPI schema) |
|
||||
| GET | `/` | Service info (excluded from OpenAPI schema) |
|
||||
配套测试页在 `static/test_interface{1..12}*.html`,经 `/static` 挂载。
|
||||
|
||||
### Image input convention (all endpoints)
|
||||
### 关键模式
|
||||
|
||||
Every endpoint accepts images via **exactly one** of three mutually exclusive fields:
|
||||
- `image_file` — multipart file upload (≤ 1 MB)
|
||||
- `image_url` — HTTP/HTTPS URL string
|
||||
- `image_base64` — base64 string with `data:image/...;base64,` prefix
|
||||
- **统一信封**:`ok(data)` / `err(code, message)` 构造 `{code, message, request_id, data}`;业务错误 HTTP 一律 200。错误码:1001 无人像 / 1002 分辨率低 / 1003 非正面 / 1004 gender 非法 / 1005 多人 / 1006 >1MB / 1007 参数或处理失败 / 1008 格式不支持。
|
||||
- **图片三选一**:每个接口 `image_file`(multipart) / `image_url` / `image_base64`(带 `data:` 前缀)严格互斥,由 `resolve_image_bytes()` 统一处理(0 个或多个 → 1007)。接口3 是 `marked_image_*`。
|
||||
- **阻塞算法进线程池**:所有推理 handler 用 `run_in_threadpool(...)`,避免卡事件循环。
|
||||
- **内网鉴权**:HTTP 中间件校验 `/api/*` 的 `X-Internal-Token` 头,密码来自 `worker_config.json` 的 `accept_passwords`(或环境变量 `WORKER_ACCEPT_PASSWORDS`)。豁免前缀见 `_AUTH_EXEMPT`(health/docs/static/debug/redraw/swapHair/hairColor)。
|
||||
- **发型序号映射**:`hairline/service.py` 的 `_HAIRSTYLE_ORDER` 显式定义 1..7 顺序(不靠文件名字母序);female 1..5 → change_hair `chang_*` 映射在 `_FEMALE_KEY_TO_CHANG`。
|
||||
- **接口12 固化参数**:`_V2_FINAL_DEFAULTS`(app.py)是生产默认值(push=0.8cm / two_stage / color_match=关 等),接口2 female 重绘也复用它。
|
||||
|
||||
Endpoint 3 (B-end) has **two** sets of image params: `marked_image_*` (the marked-up image) and `original_image_*` (the original photo). Each set follows the same three-way exclusive rule independently.
|
||||
### 外部依赖(worker 视角)
|
||||
|
||||
### Unified response structure
|
||||
| 依赖 | 地址 | 用途 | 配置 |
|
||||
|------|------|------|------|
|
||||
| ComfyUI | `http://127.0.0.1:8188`(`COMFYUI_URL`) | Flux-2 生图/重绘,走 HTTP API(`hairline/comfyui.py`) | Basic Auth `admin`,密码:`COMFYUI_PASSWORD` → `worker_config.json.comfyui_password` → `password.txt` |
|
||||
| change_hair | `http://127.0.0.1:8801`(`SWAP_HAIR_URL`/`HAIR_GROW_URL`/`CHANGE_HAIR_BASE`) | 换发型(SD WebUI + LoRA)、hairGrow | 服务目录 `/home/ubuntu/change_hair`,`start_all.sh` 启停 |
|
||||
|
||||
```json
|
||||
{"code": 0, "message": "success", "request_id": "mock-request-id", "data": {...}}
|
||||
```
|
||||
ComfyUI 工作流 JSON 在仓库根:`add_hair.json`(接口2/3/5 生发)、`add_hair2.json`(接口7)、`0716add-hair-api.json`(接口12/2女 重绘)、`hair_repaint.json`。节点约定:**26** 输入图 / **6** seed / **60** 提示词 / **16** unet(.gguf 自动切 UnetLoaderGGUF)/ **61** CLIP(4b↔9b 自动配套)。
|
||||
|
||||
Error codes: 1001–1008 (see `app.py` docstring or `docs/接口文档.md`).
|
||||
### 性能/显存相关的坑
|
||||
|
||||
### Key code patterns
|
||||
- 三个生发接口共用**同一提示词字符串**以命中 ComfyUI 的 CLIP 文本条件缓存——prompt 变了会触发 Flux(7.7G)+qwen CLIP(3.9G) 互相挤显存重载(每次 +4s)。
|
||||
- 接口2 女性重绘管线默认把输入长边压到 `REDRAW_MAX_SIDE`(env,默认 1024)再放大回原尺寸;`redraw_max_side=0` 表示不缩图。
|
||||
- `comfyui.run(front=True)` 可插队(接口2 对时延敏感);超时 `COMFY_TIMEOUT`(默认 600s)。
|
||||
|
||||
- `ok(data)` / `err(code, msg)` — helper functions at module level that build the standard response envelope
|
||||
- `ImageJsonBody` — Pydantic model for JSON-based image params (URL/base64); form-upload endpoints use FastAPI `Form()` / `File()` parameters directly
|
||||
- `SAMPLE_IMAGE_URL` — `https://hair.xiangsilian.com/static/sample.jpg`, returned as the image URL in all mock responses
|
||||
- Static files (`/static/*`) are mounted via `app.mount("/static", StaticFiles(directory="static"), name="static")`
|
||||
- All 5 POST endpoints use `multipart/form-data` with both `File` and `Form` fields — there are no JSON-body POST endpoints despite `ImageJsonBody` being defined (it exists for the OpenAPI schema but the actual handlers use `Form()` for all params)
|
||||
## Deployment(本机 = gpu_worker)
|
||||
|
||||
### Deployment
|
||||
systemd 单元(仓库根有副本,实装在 `/etc/systemd/system/`):
|
||||
|
||||
- **Process manager**: systemd (`hair.service` → `ExecStart` runs uvicorn directly from venv)
|
||||
- **Reverse proxy**: nginx (`nginx/hair.conf`) proxies port 80 → `127.0.0.1:8000` for `hair.xiangsilian.com`
|
||||
- **Python**: venv at `./venv`, dependencies in `requirements.txt`
|
||||
- **PyPI mirror**: Tencent Cloud (`mirrors.cloud.tencent.com`), configured in `pip.conf`
|
||||
| 服务 | 端口 | 说明 |
|
||||
|------|------|------|
|
||||
| `comfyui.service` | 127.0.0.1:8188 | `ComfyUI/venv` 的 `main.py --cache-classic --fast` |
|
||||
| `hair-worker.service` | 0.0.0.0:8187 | 本仓库 `app:app`(Wants comfyui + change_hair-hair) |
|
||||
| `change_hair-{webui,photo,hair}.service` | 57860 / 32678 / 8801 | conda envs `sdwebui`/`py310`/`my_hair`,依赖顺序 webui→photo→hair |
|
||||
|
||||
### Documentation
|
||||
网关机另行部署 `gateway/`(config:`workers` 列表 + `shared_password` + `ark` key),见 `gateway/config.example.json` 与 `docs/网关待改动.md`。
|
||||
|
||||
- `docs/接口文档.md` — complete API documentation (inputs, outputs, examples, error codes)
|
||||
- `docs/旷视具体需求.md` — original requirements spec (converted from `.docx`)
|
||||
- The FastAPI app's `description` docstring in `app.py` is an additional source of API docs visible in Swagger UI
|
||||
## Documentation
|
||||
|
||||
- `docs/接口文档.md` — 对外 API 契约(唯一权威)
|
||||
- `docs/实现说明.md` — 架构总览 + 各接口实现简述 + 部署要点
|
||||
- `docs/发际线增强算法.md`、`docs/发际线生发遮罩算法_pushed模式.md` — 接口11/12 算法推导
|
||||
- `docs/gpu-worker改动说明.md`、`docs/网关待改动.md` — worker↔网关 协同变更记录
|
||||
- `OFFLINE_ASSETS.md` — 离线模型权重/字体清单
|
||||
|
||||
@@ -170,10 +170,10 @@
|
||||
},
|
||||
"16": {
|
||||
"inputs": {
|
||||
"unet_name": "flux-2-klein-4b-fp8.safetensors",
|
||||
"unet_name": "flux-2-klein-9b-Q4_K_M.gguf",
|
||||
"weight_dtype": "fp8_e4m3fn_fast"
|
||||
},
|
||||
"class_type": "UNETLoader",
|
||||
"class_type": "UnetLoaderGGUF",
|
||||
"_meta": {
|
||||
"title": "UNet加载器"
|
||||
}
|
||||
@@ -410,7 +410,7 @@
|
||||
},
|
||||
"60": {
|
||||
"inputs": {
|
||||
"text": "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜"
|
||||
"text": "填充遮罩区域的头发,人物增加一点磨皮"
|
||||
},
|
||||
"class_type": "JjkText",
|
||||
"_meta": {
|
||||
@@ -419,7 +419,7 @@
|
||||
},
|
||||
"61": {
|
||||
"inputs": {
|
||||
"clip_name": "qwen_3_4b.safetensors",
|
||||
"clip_name": "qwen_3_8b_fp8mixed.safetensors",
|
||||
"type": "flux2",
|
||||
"device": "cpu"
|
||||
},
|
||||
|
||||
@@ -2,15 +2,20 @@
|
||||
|
||||
接口 1(四庭七眼测量)已为**真实算法实现**(见 face_analysis 包);接口 2~5 仍为 Mock。
|
||||
拆分架构:worker 跑算法、返回 `annotated_image_base64`(不落盘、不拼 URL,由网关完成)。
|
||||
worker 对 `/api/*` 校验内网鉴权头 `X-Internal-Token`,`/health` 供网关探测不校验。
|
||||
worker 对 `/api/*` 校验内网鉴权头 `X-Internal-Token`,`/health` 供网关探测不校验
|
||||
(深检:磁盘水位 + 下游依赖 TCP 探测,异常返回 503 degraded,见 _load_health_cfg)。
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from io import BytesIO
|
||||
from typing import Any, List, Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -146,7 +151,7 @@ _AUTH_EXEMPT = ("/health", "/docs", "/openapi.json", "/redoc", "/static",
|
||||
# ---------------------------------------------------------------------------
|
||||
# change_hair 代理路由(解决 CORS 问题)
|
||||
# ---------------------------------------------------------------------------
|
||||
_CHANGE_HAIR_BASE = "http://127.0.0.1:8801"
|
||||
_CHANGE_HAIR_BASE = os.getenv("CHANGE_HAIR_BASE", "http://127.0.0.1:8801")
|
||||
|
||||
|
||||
@app.post("/api/swapHair/v1", tags=["change_hair"])
|
||||
@@ -402,10 +407,11 @@ def _run_face_measure_data(image, variant="v1"):
|
||||
|
||||
result = measure_face(landmarks, hair_mask, w, h, head_pose=head_pose)
|
||||
data = result.to_response()
|
||||
vd = result.vertical
|
||||
if variant == "v6":
|
||||
vd = result.vertical
|
||||
# 接口6 是三庭:去掉顶庭相关字段(top_court_cm / ratios.top_court),
|
||||
# 比例分母按上/中/下三庭。发际线贴近头顶时已在 measure 修正,hairline 正常返回。
|
||||
base_px = vd["upper_court_px"] + vd["middle_court_px"] + vd["lower_court_px"]
|
||||
# 接口6 是三庭:去掉顶庭相关字段(top_court_cm / ratios.top_court / landmarks.hair_top)
|
||||
data["four_courts"]["ratios"] = {
|
||||
"upper_court": round(vd["upper_court_px"] / base_px, 3),
|
||||
"middle_court": round(vd["middle_court_px"] / base_px, 3),
|
||||
@@ -430,11 +436,13 @@ def _run_face_measure_data(image, variant="v1"):
|
||||
data["seven_eyes"][f"eye{i + 2}"] = (
|
||||
None if (a is None or b is None) else round((b - a) / pc, 2))
|
||||
if variant != "v6":
|
||||
# 接口1 额外算 eye1/eye7(左/右耳外段),需耳朵分割端线
|
||||
# 接口1 额外算 eye1/eye7(左/右耳外段),需耳朵分割端线。
|
||||
# 竖向范围上界用头顶(hair_top 始终可用)。
|
||||
from face_analysis.annotation import _ear_edges_from_mask
|
||||
top_y = vd["hair_top"][1]
|
||||
head_l, head_r = _ear_edges_from_mask(
|
||||
ear_mask, hair_mask,
|
||||
result.vertical["hair_top"][1], result.vertical["chin_tip"][1],
|
||||
top_y, vd["chin_tip"][1],
|
||||
lcx, rcx, (lcx + rcx) / 2)
|
||||
data["seven_eyes"]["eye1"] = (
|
||||
None if (head_l is None) else round((lcx - head_l) / pc, 2))
|
||||
@@ -696,10 +704,11 @@ async def face_measure_v2(
|
||||
- 发际线类型 `hairline_type`(英文 key)
|
||||
- 顺序 `order`(本期固定 `1..N`,不排序)
|
||||
|
||||
> **female 走「换发型」模式**:生发图 `grown_image_base64` 由换发型(change_hair)
|
||||
> **female 走「换发型」模式**:1..5 的生发图 `grown_image_base64` 由换发型(change_hair)
|
||||
> + Flux-2 整帧重绘(= 接口12 final 管线,整帧美颜+整帧重绘)生成,其余参数用固化默认值。
|
||||
> **male 仍走原生发(ComfyUI add_hair)管线**。入参与返回结构不变。
|
||||
> female 依赖 change_hair 与 ComfyUI(:8188) 均在跑。
|
||||
> **6/7(bigflower/clasicalflower)与 male 一样走原生发(ComfyUI add_hair)管线**。
|
||||
> **male 全部走原生发(ComfyUI add_hair)管线**。入参与返回结构不变。
|
||||
> female 1..5 依赖 change_hair 与 ComfyUI(:8188) 均在跑。
|
||||
|
||||
{_image_fields_desc}
|
||||
|
||||
@@ -707,15 +716,15 @@ async def face_measure_v2(
|
||||
|
||||
---
|
||||
|
||||
- **gender**(必填):`male` / `female`。决定返回的贴图集合(female 5 张 / male 4 张)。
|
||||
- **gender**(必填):`male` / `female`。决定返回的贴图集合(female 7 张 / male 7 张)。
|
||||
非法或缺失返回 `1004`。
|
||||
- **hair_style**(必填):发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数量。
|
||||
`female`:1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave;
|
||||
`male`:1=ellipse, 2=inverse_arc, 3=m, 4=straight。越界/非法返回 `1007`。
|
||||
`female`:1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave, 6=bigflower, 7=clasicalflower;
|
||||
`male`:1=ellipse, 2=inverse_arc, 3=m, 4=straight, 5=heart, 6=Softpetal, 7=wave。越界/非法返回 `1007`。
|
||||
- **beauty_enabled**:本期保留但不生效。
|
||||
|
||||
`hairline_type` 取值:`ellipse` / `flower` / `heart` / `straight` / `wave`(female),
|
||||
`ellipse` / `m` / `straight` / `inverse_arc`(male)。
|
||||
`hairline_type` 取值:`ellipse` / `flower` / `heart` / `straight` / `wave` / `bigflower` / `clasicalflower`(female),
|
||||
`ellipse` / `m` / `straight` / `inverse_arc` / `heart` / `Softpetal` / `wave`(male)。
|
||||
""",
|
||||
responses={
|
||||
200: {
|
||||
@@ -754,17 +763,19 @@ async def hair_grow(
|
||||
image_url: Optional[str] = Form(default=None, description="图片 URL"),
|
||||
image_base64: Optional[str] = Form(default=None, description="图片 base64(需带 data:image/...;base64, 前缀)"),
|
||||
gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"),
|
||||
hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填),如 1,2,3。female:1-5 male:1-4"),
|
||||
hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填),如 1,2,3。female:1-7 male:1-7"),
|
||||
beauty_enabled: bool = Form(default=False, description="是否开启美颜(本期不生效)"),
|
||||
use_mask: bool = Form(default=True, description="是否启用 inpaint 遮罩(测试对比用)。false 时用干净原图生成(空遮罩,不烧模板线)"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,人物增加一点磨皮", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
flux_model: Optional[str] = Form(default=None, description="Flux 模型文件名(切换模型用)。None=工作流默认;如 flux-2-klein-9b-Q5_K_M.gguf / flux-2-klein-9b-Q4_K_M.gguf / flux2.0/flux-2-klein-9b-fp8.safetensors"),
|
||||
redraw_max_side: Optional[int] = Form(default=None, description="重绘压图长边像素。None=默认896;0=不缩图(原图直送);其他如 768/640/1024"),
|
||||
):
|
||||
# 1. gender 必填校验(非法/缺失 → 1004)
|
||||
if gender not in ("male", "female"):
|
||||
return err(1004, "gender 必填且只能为 male / female")
|
||||
|
||||
# 2. hair_style 必填校验(解析逗号分隔,越界 → 1007)
|
||||
max_styles = {"female": 5, "male": 4}[gender]
|
||||
max_styles = {"female": 7, "male": 7}[gender]
|
||||
hair_styles = _parse_hair_styles(hair_style, max_styles)
|
||||
if hair_styles is None:
|
||||
return err(1007, f"hair_style 必填且为 1..{max_styles} 的整数(逗号分隔),收到 {hair_style!r}")
|
||||
@@ -786,11 +797,13 @@ async def hair_grow(
|
||||
if gender == "female":
|
||||
from hairline.service import generate_grow_results_swap
|
||||
items = await run_in_threadpool(
|
||||
generate_grow_results_swap, image, hair_styles, _V2_FINAL_DEFAULTS)
|
||||
generate_grow_results_swap, image, hair_styles, _V2_FINAL_DEFAULTS,
|
||||
redraw_max_side=redraw_max_side, unet_name=flux_model, prompt=prompt)
|
||||
else:
|
||||
from hairline.service import generate_grow_results
|
||||
items = await run_in_threadpool(
|
||||
generate_grow_results, image, gender, use_mask, prompt, hair_styles)
|
||||
generate_grow_results, image, gender, use_mask, prompt, hair_styles,
|
||||
unet_name=flux_model)
|
||||
if items is None:
|
||||
return err(1001, "无法识别人像")
|
||||
|
||||
@@ -809,6 +822,149 @@ async def hair_grow(
|
||||
return err(1007, f"处理失败:{ex}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 调试接口:接口2 女性生发 分步计时
|
||||
# ---------------------------------------------------------------------------
|
||||
@app.post(
|
||||
"/api/v1/debug/grow-timing",
|
||||
summary="调试-接口2女性生发分步计时",
|
||||
tags=["调试"],
|
||||
include_in_schema=False,
|
||||
)
|
||||
async def debug_grow_timing(
|
||||
image_file: Optional[UploadFile] = File(default=None),
|
||||
image_url: Optional[str] = Form(default=None),
|
||||
image_base64: Optional[str] = Form(default=None),
|
||||
hair_style: str = Form(default="2", description="发型序号(花瓣=2),逗号分隔多选"),
|
||||
webui_steps: Optional[int] = Form(default=None, description="swapHair webui img2img 采样步数,None=服务端默认(15),可填10/15/20/25对比"),
|
||||
redraw_max_side: Optional[int] = Form(default=None, description="ComfyUI重绘分辨率(长边像素)。None=默认896;0=原图不缩;其他如640/768/1024"),
|
||||
redraw_prompt: Optional[str] = Form(default=None, description="ComfyUI重绘提示词,None=默认'填充遮罩区域的头发,人物增加一点磨皮'"),
|
||||
):
|
||||
"""单图跑接口2女性生发,返回每个步骤的耗时 + 结果图,用于定位性能瓶颈。
|
||||
|
||||
步骤拆分:
|
||||
1. extract_context:人脸关键点检测 + 头发分割 + 发际线几何
|
||||
2. [每个发型] generate_hairline_redraw:
|
||||
2a. compute_mask:发际线遮罩计算
|
||||
2b. _call_swap:调 change_hair 换发型(内含 webui SD1.5 推理,远程或本机)
|
||||
2c. _composite:接缝融合(多频段/羽化)
|
||||
3. [每个发型] _call_local_redraw:调本机 ComfyUI 用 Flux.2 重绘
|
||||
"""
|
||||
import time as _time
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
|
||||
raw, e = await resolve_image_bytes(image_file, image_url, image_base64)
|
||||
if e is not None:
|
||||
return e
|
||||
image = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR)
|
||||
if image is None:
|
||||
return err(1008, "图片格式不支持(仅 JPG / PNG)")
|
||||
|
||||
try:
|
||||
max_styles = 7
|
||||
hair_styles = _parse_hair_styles(hair_style, max_styles)
|
||||
if hair_styles is None:
|
||||
return err(1007, f"hair_style 必须为 1..{max_styles}")
|
||||
|
||||
t_total0 = _time.perf_counter()
|
||||
timings = {"total_ms": 0, "extract_context_ms": 0, "per_hairstyle": []}
|
||||
|
||||
# 步骤1: extract_context
|
||||
t0 = _time.perf_counter()
|
||||
from hairline.service import extract_context as _ec, _call_local_redraw, _REDRAW_MAX_SIDE # noqa
|
||||
from face_analysis.hairline_grow import generate_hairline_redraw, NoFaceError # noqa
|
||||
from face_analysis.head_mask import SEGFORMER_HAIR # noqa
|
||||
ctx = await run_in_threadpool(_ec, image)
|
||||
timings["extract_context_ms"] = int((_time.perf_counter() - t0) * 1000)
|
||||
if ctx is None:
|
||||
return err(1001, "无法识别人像")
|
||||
|
||||
hair_mask_reuse = (ctx["parse_map"] == SEGFORMER_HAIR)
|
||||
h, w = image.shape[:2]
|
||||
eff_side = _REDRAW_MAX_SIDE if redraw_max_side is None else redraw_max_side
|
||||
redraw_img, hair_mask_redraw = image, hair_mask_reuse
|
||||
downscale_info = None
|
||||
if eff_side > 0 and max(h, w) > eff_side:
|
||||
from hairline.service import _downscale_max_side
|
||||
redraw_img, _rs = _downscale_max_side(image, eff_side)
|
||||
_nh, _nw = redraw_img.shape[:2]
|
||||
if hair_mask_redraw is not None:
|
||||
hair_mask_redraw = cv2.resize(hair_mask_reuse.astype(np.uint8), (_nw, _nh),
|
||||
interpolation=cv2.INTER_NEAREST).astype(bool)
|
||||
downscale_info = {"from": f"{w}x{h}", "to": f"{_nw}x{_nh}", "max_side": eff_side}
|
||||
|
||||
textures_map = None
|
||||
from hairline.service import get_texture_map, _FEMALE_KEY_TO_CHANG, load_texture_rgba, build_overlay_layer, load_ext_mesh
|
||||
textures = get_texture_map()["female"]
|
||||
items = [(s, textures[s - 1]) for s in hair_styles]
|
||||
|
||||
for order, (key, white_path) in items:
|
||||
hs_t0 = _time.perf_counter()
|
||||
entry = {"hairline_type": key, "order": order}
|
||||
chang_id = _FEMALE_KEY_TO_CHANG.get(key)
|
||||
entry["chang_id"] = chang_id
|
||||
entry["ok"] = False
|
||||
entry["error"] = None
|
||||
entry["grown_b64"] = None
|
||||
if chang_id is None:
|
||||
entry["error"] = f"无对应 chang_id"
|
||||
timings["per_hairstyle"].append(entry)
|
||||
continue
|
||||
try:
|
||||
# 2a/2b/2c: generate_hairline_redraw (内部含 mask+swap+blend)
|
||||
t0 = _time.perf_counter()
|
||||
data = await run_in_threadpool(
|
||||
generate_hairline_redraw, redraw_img, chang_id,
|
||||
hair_mask=hair_mask_redraw, webui_steps=webui_steps, **_V2_FINAL_DEFAULTS)
|
||||
t_redraw_pipeline = _time.perf_counter() - t0
|
||||
_tm = data.get("timings_ms") or {}
|
||||
entry["mask_ms"] = _tm.get("mask", 0)
|
||||
entry["swap_ms"] = _tm.get("swap", 0)
|
||||
entry["blend_ms"] = _tm.get("blend", 0)
|
||||
entry["redraw_pipeline_ms"] = int(t_redraw_pipeline * 1000)
|
||||
|
||||
steps = data.get("steps") or {}
|
||||
final_b64 = steps.get("final_base64") or ""
|
||||
mask_b64 = steps.get("redraw_band_mask_base64") or ""
|
||||
if not final_b64 or not mask_b64:
|
||||
entry["error"] = f"final/遮罩缺失(final={len(final_b64)} mask={len(mask_b64)})"
|
||||
timings["per_hairstyle"].append(entry)
|
||||
continue
|
||||
if final_b64.startswith("data:"):
|
||||
final_b64 = final_b64.split(",", 1)[1]
|
||||
if mask_b64.startswith("data:"):
|
||||
mask_b64 = mask_b64.split(",", 1)[1]
|
||||
|
||||
# 3: ComfyUI 重绘
|
||||
t0 = _time.perf_counter()
|
||||
# max_side: 0 或 None 都让 _call_local_redraw 用默认逻辑(外层已控制分辨率)
|
||||
_ms = redraw_max_side if redraw_max_side is not None and redraw_max_side > 0 else None
|
||||
grown_png = await run_in_threadpool(
|
||||
_call_local_redraw,
|
||||
base64.b64decode(final_b64), base64.b64decode(mask_b64),
|
||||
max_side=_ms, prompt=redraw_prompt)
|
||||
entry["comfyui_redraw_ms"] = int((_time.perf_counter() - t0) * 1000)
|
||||
if grown_png:
|
||||
entry["grown_b64"] = "data:image/jpeg;base64," + _png_to_jpg_b64(grown_png)
|
||||
entry["ok"] = True
|
||||
else:
|
||||
entry["error"] = "ComfyUI 重绘返回空"
|
||||
except NoFaceError:
|
||||
entry["error"] = "未检出人脸"
|
||||
except Exception as ex: # noqa: BLE001
|
||||
entry["error"] = str(ex)[:150]
|
||||
entry["hairstyle_total_ms"] = int((_time.perf_counter() - hs_t0) * 1000)
|
||||
timings["per_hairstyle"].append(entry)
|
||||
|
||||
timings["total_ms"] = int((_time.perf_counter() - t_total0) * 1000)
|
||||
timings["downscale"] = downscale_info
|
||||
timings["image_size"] = f"{w}x{h}"
|
||||
return ok(timings)
|
||||
except Exception as ex: # noqa: BLE001
|
||||
logger.exception("debug/grow-timing 异常")
|
||||
return err(1007, f"处理失败:{ex}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 接口 7:C 端生发 v2 —— 已弃用(add_hair2.json 用 Klein-9b 大模型,会把常驻的
|
||||
# Klein-4b/Flux 挤出显存,导致接口2/3/5 耗时抖动;且业务已不再调用)。
|
||||
@@ -868,7 +1024,7 @@ async def hair_grow_b(
|
||||
marked_image_url: Optional[str] = Form(default=None, description="划线图片 URL"),
|
||||
marked_image_base64: Optional[str] = Form(default=None, description="划线图片 base64"),
|
||||
use_mask: bool = Form(default=True, description="是否画发际线(测试对比用)。false 时跳过划线检测、直接送划线图"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,人物增加一点磨皮", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
):
|
||||
# 划线图三选一取图(只需这一张)
|
||||
marked_raw, e = await resolve_image_bytes(marked_image_file, marked_image_url, marked_image_base64)
|
||||
@@ -994,13 +1150,18 @@ async def face_features(
|
||||
---
|
||||
|
||||
**入参**(同接口2:先选性别,再多选发型):
|
||||
- 必填 `gender`(`male`/`female`),决定发型集合(female 5 / male 4)。
|
||||
- 必填 `gender`(`male`/`female`),决定发型集合(female 7 / male 7)。
|
||||
- 必填 `hair_style`(发型序号,逗号分隔如 `1,2,3`),决定返回哪些发际线类型。缺失/越界/非法返回 `1007`。
|
||||
`female`:1=ellipse,2=flower,3=heart,4=straight,5=wave;`male`:1=ellipse,2=inverse_arc,3=m,4=straight。
|
||||
- 可选 `use_mask` / `prompt`:同接口2 的生发控制参数。
|
||||
`female`:1=ellipse,2=flower,3=heart,4=straight,5=wave,6=bigflower,7=clasicalflower;
|
||||
`male`:1=ellipse,2=inverse_arc,3=m,4=straight,5=heart,6=Softpetal,7=wave。
|
||||
- 可选 `use_mask` / `prompt`:同接口2 的生发控制参数(仅 male 路径生效)。
|
||||
注:生发黑模板固定取 `hairline_texture_black/`(middle 档),即三档叠图分别用各自贴图、但生发目标固定 middle。
|
||||
- 可选 `generate_grow_image`(默认 `true`):是否生成生发效果图(ComfyUI 生发,全流程最耗时)。
|
||||
`false` 时跳过生发,各发型 `grown_image_*` 恒为 `null`,仅返回三档发际线叠图与中心点,大幅降低耗时。
|
||||
- **生发机制(同接口2,按性别分流)**:
|
||||
`female` 走「换发型 + Flux-2 整帧重绘」(依赖 change_hair:8801 与 ComfyUI:8188);
|
||||
`male` 走 ComfyUI `add_hair` 原生 inpaint。
|
||||
- 可选 `flux_model` / `redraw_max_side`:同接口2(仅 female 路径生效)。
|
||||
|
||||
**返回说明**:
|
||||
|
||||
@@ -1076,16 +1237,18 @@ async def hairline_generate(
|
||||
image_url: Optional[str] = Form(default=None, description="图片 URL"),
|
||||
image_base64: Optional[str] = Form(default=None, description="图片 base64(需带 data:image/...;base64, 前缀)"),
|
||||
gender: Optional[str] = Form(default=None, description="性别 male/female(必填)"),
|
||||
hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填,如 1,2,3)。female:1-5 male:1-4"),
|
||||
use_mask: bool = Form(default=True, description="生发是否启用 inpaint 遮罩(同接口2,测试对比用)"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜", description="ComfyUI 提示词(同接口2),会替换工作流节点60的文本"),
|
||||
generate_grow_image: bool = Form(default=True, description="是否生成生发效果图(ComfyUI 生发,最耗时)。默认 true 出图;false 时跳过生发,各发型 grown_image 恒为 null,仅返回三档发际线叠图与中心点"),
|
||||
hair_style: Optional[str] = Form(default=None, description="发型序号逗号分隔(必填,如 1,2,3)。female:1-7 male:1-7"),
|
||||
use_mask: bool = Form(default=True, description="生发是否启用 inpaint 遮罩(同接口2,仅 male 路径生效)"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,人物增加一点磨皮", description="ComfyUI 提示词(同接口2,仅 male 路径生效),会替换工作流节点60的文本"),
|
||||
generate_grow_image: bool = Form(default=True, description="是否生成生发效果图(最耗时)。默认 true 出图;false 时跳过生发,各发型 grown_image 恒为 null,仅返回三档发际线叠图与中心点"),
|
||||
flux_model: Optional[str] = Form(default=None, description="Flux 模型文件名(同接口2,切换模型用)。None=工作流默认"),
|
||||
redraw_max_side: Optional[int] = Form(default=None, description="重绘压图长边像素(同接口2,仅 female 路径生效)。None=默认896;0=不缩图(原图直送);其他如 768/640/1024"),
|
||||
):
|
||||
if gender not in ("male", "female"):
|
||||
return err(1004, "gender 必填且只能为 male / female")
|
||||
|
||||
# hair_style 必填(同接口2):解析逗号分隔,缺失/越界/非法 → 1007
|
||||
max_styles = {"female": 5, "male": 4}[gender]
|
||||
max_styles = {"female": 7, "male": 7}[gender]
|
||||
hair_styles = _parse_hair_styles(hair_style, max_styles)
|
||||
if hair_styles is None:
|
||||
return err(1007, f"hair_style 必填且为 1..{max_styles} 的整数(逗号分隔),收到 {hair_style!r}")
|
||||
@@ -1104,7 +1267,9 @@ async def hairline_generate(
|
||||
|
||||
res = await run_in_threadpool(
|
||||
generate_hairline_pngs, image, gender, hair_styles, use_mask, prompt,
|
||||
generate_grow_image=generate_grow_image)
|
||||
generate_grow_image=generate_grow_image,
|
||||
redraw_max_side=redraw_max_side, unet_name=flux_model,
|
||||
v2_defaults=_V2_FINAL_DEFAULTS)
|
||||
if res is None:
|
||||
return err(1001, "无法识别人像")
|
||||
|
||||
@@ -1316,6 +1481,70 @@ async def head_band(
|
||||
return err(1007, f"处理失败:{ex}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 接口 99:人脸特殊点检测(固定关键点 + 发际线特殊点)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.post(
|
||||
"/api/v1/face/special-points",
|
||||
summary="接口99 人脸特殊点检测",
|
||||
tags=["人脸分析"],
|
||||
description=f"""
|
||||
输入一张人脸照片,返回 MediaPipe Face Mesh 一组**固定编号特殊点**的像素坐标,
|
||||
以及 5 个**发际线特殊点**(射线与 BiSeNet 头发分割发际线的交点,见 hairline_grow 同款分割)。
|
||||
|
||||
**字段命名**:`<组英文名>_<点ID>`,如 `eyebrow_107`、`mouth_17`;发际线点用给定字段名
|
||||
(`hair_line_center` 等)。坐标为原图像素坐标(int),发际线点不可得(无头发/分割失败)时为 null。
|
||||
|
||||
| 组 | 字段前缀 | 点 ID |
|
||||
|----|----------|-------|
|
||||
| 眉毛 | eyebrow | 107 66 105 63 70 336 296 334 293 300 |
|
||||
| 眼睛 | eye | 189 222 224 113 226 413 442 444 342 446 |
|
||||
| 嘴 | mouth | 0 37 40 67 91 84 17 405 375 409 269 |
|
||||
| 中线鼻 | nose_midline | 9 168 197 5 4 194 278 48 437 217 |
|
||||
| 面颊 | cheek | 101 117 123 187 205 50 330 346 352 280 425 |
|
||||
| 边线 | face_edge | 162 234 58 136 149 152 378 365 288 401 366 389 251 |
|
||||
|
||||
**发际线点算法**:从关键点 a 沿 a→b 方向逐像素步进,首次进入头发 mask 处即交点;
|
||||
双射线的点取两交点中点(仅一条命中返回该点,均未命中为 null):
|
||||
- `hair_line_center`:151→10
|
||||
- `hair_line_right`:mid(108→109, 69→67)
|
||||
- `hair_line_right_right`:mid(104→103, 68→54)
|
||||
- `hair_line_left`:mid(337→338, 299→297)
|
||||
- `hair_line_left_left`:mid(333→332, 298→284)
|
||||
|
||||
{_image_fields_desc}
|
||||
""",
|
||||
)
|
||||
async def face_special_points(
|
||||
image_file: Optional[UploadFile] = File(default=None, description="上传图片文件(JPG/PNG)"),
|
||||
image_url: Optional[str] = Form(default=None, description="图片 URL"),
|
||||
image_base64: Optional[str] = Form(default=None, description="图片 base64(需带 data:image/...;base64, 前缀)"),
|
||||
):
|
||||
"""接口99:固定关键点 + 发际线特殊点,像素坐标 JSON 返回。"""
|
||||
raw, e = await resolve_image_bytes(image_file, image_url, image_base64)
|
||||
if e is not None:
|
||||
return e
|
||||
|
||||
image = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR)
|
||||
if image is None:
|
||||
return err(1008, "图片格式不支持(仅 JPG / PNG)")
|
||||
|
||||
try:
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from face_analysis.special_points import detect_special_points, NoFaceError, NonFrontalError
|
||||
try:
|
||||
data = await run_in_threadpool(detect_special_points, image)
|
||||
except NoFaceError:
|
||||
return err(1001, "无法识别人像")
|
||||
except NonFrontalError:
|
||||
return err(1003, "角度问题,请上传正面照")
|
||||
return ok(data)
|
||||
except Exception as ex: # noqa: BLE001
|
||||
logger.exception("接口99 处理异常")
|
||||
return err(1007, f"处理失败:{ex}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 接口 11:发际线生发(接口9 遮罩 + change_hair 换发型 + 按遮罩羽化贴回)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1472,7 +1701,7 @@ async def hairline_grow_v2(
|
||||
inpainting_fill: int = Form(default=1, description="change_hair服务端重绘填充:0=保留原图 | 1=噪声 | 2=纯色 | 3=潜变量。默认 1"),
|
||||
mask_blur: int = Form(default=11, description="change_hair服务端遮罩边缘模糊像素,默认 11"),
|
||||
mask_dilate_scale: float = Form(default=1.0, description="change_hair服务端遮罩膨胀缩放,默认 1.0"),
|
||||
comfyui_prompt: Optional[str] = Form(default=None, description="Flux-2 重绘提示词,None 用默认「填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜」"),
|
||||
comfyui_prompt: Optional[str] = Form(default=None, description="Flux-2 重绘提示词,None 用默认「填充遮罩区域的头发,人物增加一点磨皮」"),
|
||||
beauty_alpha: float = Form(default=0.6, description="redraw_band 版 band 外的全脸美颜融入强度(0=band外无美颜纯用final,1≈整帧版),默认 0.6"),
|
||||
band_lo_mult: float = Form(default=0.5, description="重绘带外推倍率下限(相对 hairline_push_cm,内轮廓=0×、原外推线=1.0×),默认 0.5"),
|
||||
band_hi_mult: float = Form(default=1.5, description="重绘带外推倍率上限(相对 hairline_push_cm),默认 1.5"),
|
||||
@@ -1638,7 +1867,7 @@ async def hairline_grow_v2_final_v2(
|
||||
async def api_redraw(
|
||||
image_file: UploadFile = File(..., description="人物图片(JPG/PNG)"),
|
||||
mask_file: UploadFile = File(..., description="遮罩图片(PNG,支持红/白/alpha 格式)"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜",
|
||||
prompt: str = Form(default="填充遮罩区域的头发,人物增加一点磨皮",
|
||||
description="ComfyUI 提示词"),
|
||||
):
|
||||
image_bytes = await image_file.read()
|
||||
@@ -1687,12 +1916,127 @@ async def download_hairline_log(rid: Optional[str] = None, tail: int = 500):
|
||||
# 健康检查
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_health_cfg() -> dict:
|
||||
"""深健康检查配置:环境变量优先,回退 worker_config.json 的 "health" 段。
|
||||
|
||||
min_free_gb=0 关闭磁盘检查;check_deps=false 关闭依赖探测(均退化为旧行为,
|
||||
即只看模型就绪标志)。
|
||||
"""
|
||||
cfg_path = os.path.join(os.path.dirname(__file__), "worker_config.json")
|
||||
file_cfg: dict = {}
|
||||
if os.path.isfile(cfg_path):
|
||||
try:
|
||||
with open(cfg_path, encoding="utf-8") as f:
|
||||
file_cfg = json.load(f).get("health") or {}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("读取 worker_config.json health 段失败:%s", e)
|
||||
|
||||
def _get(env_key, file_key, default):
|
||||
raw = os.getenv(env_key)
|
||||
return raw if raw not in (None, "") else file_cfg.get(file_key, default)
|
||||
|
||||
def _as_float(value, default):
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
return {
|
||||
"min_free_gb": _as_float(_get("HEALTH_MIN_FREE_GB", "min_free_gb", 5.0), 5.0),
|
||||
"check_deps": str(_get("HEALTH_CHECK_DEPS", "check_deps", True)).strip().lower()
|
||||
not in ("0", "false", "no", "off"),
|
||||
"dep_comfyui": str(_get("HEALTH_DEP_COMFYUI", "dep_comfyui", "127.0.0.1:8188")),
|
||||
"deps_cache_seconds": max(0.0, _as_float(
|
||||
_get("HEALTH_DEPS_CACHE_SECONDS", "deps_cache_seconds", 5.0), 5.0)),
|
||||
}
|
||||
|
||||
|
||||
_HEALTH_CFG = _load_health_cfg()
|
||||
|
||||
|
||||
def _disk_free_gb() -> float:
|
||||
"""worker 所在文件系统的剩余空间(GB)。"""
|
||||
st = shutil.disk_usage(os.path.dirname(os.path.abspath(__file__)))
|
||||
return st.free / (1 << 30)
|
||||
|
||||
|
||||
def _parse_host_port(addr: str, default_port: int):
|
||||
"""解析 "host:port"(仅支持 IPv4/主机名形式)。"""
|
||||
host, _, port = str(addr).partition(":")
|
||||
try:
|
||||
return host or "127.0.0.1", int(port) if port else default_port
|
||||
except ValueError:
|
||||
return host or "127.0.0.1", default_port
|
||||
|
||||
|
||||
def _change_hair_addr():
|
||||
"""从 _CHANGE_HAIR_BASE 解析 (host, port),失败返回 None。"""
|
||||
try:
|
||||
u = urlsplit(_CHANGE_HAIR_BASE)
|
||||
if u.hostname:
|
||||
return u.hostname, u.port or 80
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
async def _tcp_probe(host: str, port: int, timeout: float = 0.8) -> bool:
|
||||
"""TCP 连通性探测:只判下游进程死活,不过 HTTP 认证、不受业务繁忙影响。"""
|
||||
try:
|
||||
_, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout)
|
||||
writer.close()
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
_DEP_CACHE = {"ts": -1.0, "detail": None}
|
||||
|
||||
|
||||
async def _check_deps():
|
||||
"""并发探测下游依赖(ComfyUI、change_hair),结果缓存 deps_cache_seconds 秒。"""
|
||||
now = time.monotonic()
|
||||
detail = _DEP_CACHE["detail"]
|
||||
if detail is None or now - _DEP_CACHE["ts"] >= _HEALTH_CFG["deps_cache_seconds"]:
|
||||
probes = {"comfyui": _tcp_probe(*_parse_host_port(_HEALTH_CFG["dep_comfyui"], 8188))}
|
||||
ch = _change_hair_addr()
|
||||
if ch:
|
||||
probes["change_hair"] = _tcp_probe(*ch)
|
||||
names = list(probes)
|
||||
results = await asyncio.gather(*probes.values())
|
||||
detail = dict(zip(names, results))
|
||||
_DEP_CACHE["ts"], _DEP_CACHE["detail"] = now, detail
|
||||
return all(detail.values()), detail
|
||||
|
||||
|
||||
@app.get("/health", include_in_schema=False)
|
||||
async def health():
|
||||
# 模型就绪后才返回 200,供网关探测;未就绪返回 503。
|
||||
"""网关探测入口。
|
||||
|
||||
模型未就绪 → 503 starting;磁盘剩余低于阈值 / 下游依赖 TCP 不通 → 503 degraded;
|
||||
正常 → 200(附 disk_free_gb 与 deps 明细,供人工排查)。深检自身异常时按就绪返回
|
||||
(健康检查不能自己成为故障点)。
|
||||
"""
|
||||
if not _STATE["ready"]:
|
||||
return JSONResponse(status_code=503, content={"status": "starting"})
|
||||
return {"status": "ok"}
|
||||
try:
|
||||
free_gb = _disk_free_gb()
|
||||
body = {"status": "ok", "disk_free_gb": round(free_gb, 1)}
|
||||
min_free = _HEALTH_CFG["min_free_gb"]
|
||||
if min_free > 0 and free_gb < min_free:
|
||||
body.update(status="degraded", reason=f"disk_free_below_{min_free}g")
|
||||
return JSONResponse(status_code=503, content=body)
|
||||
if _HEALTH_CFG["check_deps"]:
|
||||
deps_ok, detail = await _check_deps()
|
||||
body["deps"] = detail
|
||||
if not deps_ok:
|
||||
down = ",".join(k for k, v in detail.items() if not v)
|
||||
body.update(status="degraded", reason=f"dep_down:{down}")
|
||||
return JSONResponse(status_code=503, content=body)
|
||||
return body
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("深健康检查异常,按就绪返回")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发型对比矩阵测试:3图×5发型=15行,每行10张图(4b@896×1 + 9b三模型×三分辨率×9)。
|
||||
按模型分组跑(减少模型切换次数、降低OOM风险),结果重组为15行存JSON+生成报告。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
API = "http://127.0.0.1:8187/api/v1/hair/grow"
|
||||
TOKEN = "dev-shared-secret-2026"
|
||||
OUT = Path("/home/ubuntu/hair/benchmark_out/hairstyle")
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
IMGS = [
|
||||
("asdf", "/home/ubuntu/hair/image/asdf.jpg"),
|
||||
("qwer", "/home/ubuntu/hair/image/qwer.jpg"),
|
||||
("girl5", "/home/ubuntu/hair/image/girl_img/girl5.jpg"),
|
||||
]
|
||||
HAIRSTYLES = [
|
||||
(1, "ellipse", "椭圆"), (2, "flower", "花瓣"), (3, "heart", "心形"),
|
||||
(4, "straight", "直线"), (5, "wave", "波浪"),
|
||||
]
|
||||
|
||||
# 按模型分组:每个模型对应其要跑的(分辨率,列标题)
|
||||
MODEL_GROUPS = [
|
||||
("flux-2-klein-4b-fp8.safetensors", [("896", "4B@896")]),
|
||||
("flux2.0/flux-2-klein-9b-fp8.safetensors",
|
||||
[("0", "9B-fp8@原图"), ("896", "9B-fp8@896"), ("640", "9B-fp8@640")]),
|
||||
("flux-2-klein-9b-Q5_K_M.gguf",
|
||||
[("0", "9B-Q5@原图"), ("896", "9B-Q5@896"), ("640", "9B-Q5@640")]),
|
||||
("flux-2-klein-9b-Q4_K_M.gguf",
|
||||
[("0", "9B-Q4@原图"), ("896", "9B-Q4@896"), ("640", "9B-Q4@640")]),
|
||||
]
|
||||
# 列顺序(4b在前,然后9b三模型)
|
||||
COLUMN_TITLES = ["4B@896", "9B-fp8@原图", "9B-fp8@896", "9B-fp8@640",
|
||||
"9B-Q5@原图", "9B-Q5@896", "9B-Q5@640",
|
||||
"9B-Q4@原图", "9B-Q4@896", "9B-Q4@640"]
|
||||
|
||||
|
||||
def gpu_used():
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"], timeout=10)
|
||||
return int(out.decode().strip())
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def call(img_path, hair_num, model_file, res_val):
|
||||
fd = {"gender": "female", "hair_style": str(hair_num), "use_mask": "true",
|
||||
"prompt": "填充遮罩区域的头发,人物增加一点磨皮"}
|
||||
if model_file:
|
||||
fd["flux_model"] = model_file
|
||||
if res_val != "":
|
||||
fd["redraw_max_side"] = res_val
|
||||
t0 = time.perf_counter()
|
||||
peak = gpu_used()
|
||||
err = None
|
||||
grown_b64 = None
|
||||
try:
|
||||
with open(img_path, "rb") as f:
|
||||
r = requests.post(API, headers={"X-Internal-Token": TOKEN},
|
||||
files={"image_file": (os.path.basename(img_path), f, "image/jpeg")},
|
||||
data=fd, timeout=300)
|
||||
elapsed = time.perf_counter() - t0
|
||||
peak = max(peak, gpu_used())
|
||||
j = r.json()
|
||||
if j.get("code") != 0:
|
||||
err = f"code={j.get('code')} {j.get('message', '')[:60]}"
|
||||
else:
|
||||
res = j.get("data", {}).get("results", [])
|
||||
if res and res[0].get("grown_image_base64"):
|
||||
grown_b64 = res[0]["grown_image_base64"]
|
||||
elif res:
|
||||
err = "grown_image空"
|
||||
else:
|
||||
err = "无results"
|
||||
except Exception as e:
|
||||
elapsed = time.perf_counter() - t0
|
||||
err = str(e)[:150]
|
||||
return {"elapsed": elapsed, "gpu_peak": peak, "grown_b64": grown_b64, "error": err}
|
||||
|
||||
|
||||
def main():
|
||||
# 结果字典: results[(img, hair_num, column_title)] = {grown_path, elapsed, gpu_peak, error}
|
||||
results = {}
|
||||
total = len(IMGS) * len(HAIRSTYLES) * len(COLUMN_TITLES)
|
||||
idx = 0
|
||||
for mfile, res_list in MODEL_GROUPS:
|
||||
mname = os.path.basename(mfile)
|
||||
print(f"\n===== 切换到模型: {mname} =====", flush=True)
|
||||
# 等模型切换稳定
|
||||
time.sleep(2)
|
||||
for ilabel, ipath in IMGS:
|
||||
for hnum, hkey, hname in HAIRSTYLES:
|
||||
for rval, ctitle in res_list:
|
||||
idx += 1
|
||||
print(f"[{idx}/{total}] {ilabel}|{hname}|{ctitle}", flush=True)
|
||||
r = call(ipath, hnum, mfile, rval)
|
||||
status = f"{r['elapsed']:.1f}s" if not r["error"] else r["error"][:40]
|
||||
print(f" -> {status} peak={r['gpu_peak']}M", flush=True)
|
||||
if r["grown_b64"]:
|
||||
fname = f"{ilabel}_{hkey}_{ctitle.replace('@','_').replace('-','')}.jpg"
|
||||
with open(OUT / fname, "wb") as gf:
|
||||
gf.write(base64.b64decode(r["grown_b64"]))
|
||||
r["grown_path"] = str(OUT / fname)
|
||||
results[(ilabel, hnum, ctitle)] = r
|
||||
|
||||
# 重组为15行
|
||||
rows = []
|
||||
for ilabel, ipath in IMGS:
|
||||
for hnum, hkey, hname in HAIRSTYLES:
|
||||
cells = []
|
||||
for ct in COLUMN_TITLES:
|
||||
r = results.get((ilabel, hnum, ct), {"error": "未跑"})
|
||||
cells.append({"title": ct, **{k: v for k, v in r.items() if k != "grown_b64"}})
|
||||
rows.append({"img": ilabel, "img_path": ipath,
|
||||
"hair_num": hnum, "hair_key": hkey, "hair_name": hname,
|
||||
"cells": cells})
|
||||
with open(OUT / "results.json", "w", encoding="utf-8") as f:
|
||||
json.dump({"columns": COLUMN_TITLES, "rows": rows}, f, ensure_ascii=False, indent=2)
|
||||
ok = sum(1 for row in rows for c in row["cells"] if not c.get("error"))
|
||||
print(f"\n✓ 完成: {ok}/{total} 成功 -> {OUT/'results.json'}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把发型对比测试结果生成 HTML 报告。
|
||||
15行(3图×5发型) × 10列(4b@896 + 9b三模型×三分辨率),每行首列=原图。
|
||||
图片 base64 内嵌,自包含单文件。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
OUT = Path("/home/ubuntu/hair/benchmark_out/hairstyle")
|
||||
RESULTS = OUT / "results.json"
|
||||
HTML = OUT / "report.html"
|
||||
|
||||
|
||||
def img_src(path):
|
||||
"""把绝对路径转成报告里的相对 URL(报告在 static/,图片在 static/bench/)。"""
|
||||
if not path:
|
||||
return None
|
||||
p = str(path)
|
||||
if "benchmark_out/hairstyle/" in p:
|
||||
return "bench/hairstyle/" + os.path.basename(p)
|
||||
if "benchmark_out/matrix/" in p:
|
||||
return "bench/matrix/" + os.path.basename(p)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
d = json.load(open(RESULTS, encoding="utf-8"))
|
||||
columns = d["columns"]
|
||||
rows = d["rows"]
|
||||
|
||||
# 统计每列的平均耗时、峰值显存
|
||||
col_stats = {}
|
||||
for ct in columns:
|
||||
times, peaks = [], []
|
||||
for r in rows:
|
||||
for c in r["cells"]:
|
||||
if c.get("title") == ct and not c.get("error"):
|
||||
times.append(c["elapsed"])
|
||||
peaks.append(c["gpu_peak"])
|
||||
col_stats[ct] = {
|
||||
"avg_t": sum(times) / len(times) if times else 0,
|
||||
"max_p": max(peaks) / 1024 if peaks else 0,
|
||||
}
|
||||
|
||||
# 表头:原图 + 10列
|
||||
headers = ['<th class="col-label">原图</th>']
|
||||
for ct in columns:
|
||||
s = col_stats[ct]
|
||||
headers.append(
|
||||
f'<th class="col-label"><div class="col-title">{ct}</div>'
|
||||
f'<div class="col-stat">{s["avg_t"]:.0f}s · {s["max_p"]:.0f}G</div></th>'
|
||||
)
|
||||
|
||||
# 表体:15行
|
||||
body_rows = []
|
||||
for r in rows:
|
||||
# 发型+图标签
|
||||
label = f'<div class="row-label">{r["img"]}<br><b>{r["hair_name"]}</b></div>'
|
||||
# 原图
|
||||
ORIG_SRC = {"asdf": "bench/orig/asdf.jpg", "qwer": "bench/orig/qwer.jpg", "girl5": "bench/orig/girl5.jpg"}
|
||||
orig = ORIG_SRC.get(r["img"])
|
||||
cells = [f'<td class="cell-orig"><div class="row-label-cell">{label}</div>'
|
||||
f'<img class="orig-img" src="{orig}"></td>']
|
||||
# 10个结果列
|
||||
for ct in columns:
|
||||
c = next((x for x in r["cells"] if x.get("title") == ct), {})
|
||||
src = img_src(c.get("grown_path")) if not c.get("error") else None
|
||||
if src:
|
||||
cells.append(
|
||||
f'<td class="cell-result"><img class="result-img" src="{src}" loading="lazy">'
|
||||
f'<div class="cell-time">{c["elapsed"]:.1f}s</div></td>')
|
||||
else:
|
||||
cells.append(f'<td class="cell-result"><div class="na">⚠</div></td>')
|
||||
body_rows.append(f'<tr>{"".join(cells)}</tr>')
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>发型对比测试报告 — 4模型×3分辨率</title>
|
||||
<style>
|
||||
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
|
||||
body {{ font-family: -apple-system, "Segoe UI", sans-serif; background: #f5f5f5; padding: 16px; }}
|
||||
h1 {{ font-size: 20px; margin-bottom: 4px; }}
|
||||
.subtitle {{ color: #888; font-size: 12px; margin-bottom: 12px; }}
|
||||
.legend {{ background: #fff; border-radius: 8px; padding: 10px 16px; margin-bottom: 12px; font-size: 12px; color: #555; }}
|
||||
.scroll-wrap {{ overflow-x: auto; }}
|
||||
table {{ border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,.06); }}
|
||||
th, td {{ border: 1px solid #eee; padding: 6px; vertical-align: top; text-align: center; }}
|
||||
th {{ background: #f9fafb; position: sticky; top: 0; }}
|
||||
.col-label {{ min-width: 110px; max-width: 130px; }}
|
||||
.col-title {{ font-size: 12px; font-weight: 700; color: #374151; }}
|
||||
.col-stat {{ font-size: 10px; color: #9ca3af; margin-top: 2px; }}
|
||||
.row-label {{ font-size: 11px; color: #6b7280; }}
|
||||
.row-label b {{ color: #1f2937; }}
|
||||
.row-label-cell {{ font-size: 11px; color: #6b7280; margin-bottom: 4px; }}
|
||||
.row-label-cell b {{ color: #1f2937; font-size: 13px; }}
|
||||
img {{ border-radius: 4px; max-width: 120px; max-height: 150px; object-fit: contain; background: #f3f4f6; }}
|
||||
.orig-img {{ border: 2px solid #d1d5db; max-height: 130px; }}
|
||||
.cell-time {{ font-size: 10px; color: #9ca3af; margin-top: 2px; }}
|
||||
.na {{ color: #d1d5db; font-size: 16px; padding: 40px; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>💇 发型对比测试报告</h1>
|
||||
<p class="subtitle">接口2女性 · 3图×5发型=15行 · 每行: 4B@896(1) + 9B(fp8/Q5/Q4)×(原图/896/640)(9) · 150/150成功 · RTX3090</p>
|
||||
<div class="legend">列标题下显示<b>平均耗时 · 峰值显存</b>。横向滚动查看更多列。原图列含图片名+发型名。</div>
|
||||
<div class="scroll-wrap">
|
||||
<table>
|
||||
<tr>{"".join(headers)}</tr>
|
||||
{"".join(body_rows)}
|
||||
</table>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
with open(HTML, "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
print(f"✓ 报告: {HTML} ({HTML.stat().st_size//1024} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""接口2女性 花瓣形 单发型 4模型×3分辨率×3图×3次 矩阵测试。
|
||||
|
||||
调用本机 hair-worker (:8187) 的 /api/v1/hair/grow,gender=female, hair_style=2(花瓣形)。
|
||||
每次记录:生发图、耗时、显存峰值。结果图存到 benchmark_out/matrix/,最后生成 HTML 报告。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
API = "http://127.0.0.1:8187/api/v1/hair/grow"
|
||||
TOKEN = "dev-shared-secret-2026"
|
||||
OUT = Path("/home/ubuntu/hair/benchmark_out/matrix")
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 4 模型 × 3 分辨率 × 3 图 × 3 次
|
||||
MODELS = [
|
||||
("4b-fp8", "flux-2-klein-4b-fp8.safetensors"),
|
||||
("9b-fp8", "flux2.0/flux-2-klein-9b-fp8.safetensors"),
|
||||
("9b-Q5", "flux-2-klein-9b-Q5_K_M.gguf"),
|
||||
("9b-Q4", "flux-2-klein-9b-Q4_K_M.gguf"),
|
||||
]
|
||||
RES = [("orig", "0"), ("640", "640"), ("896", "896")]
|
||||
IMGS = [
|
||||
("asdf", "/home/ubuntu/hair/image/asdf.jpg"),
|
||||
("qwer", "/home/ubuntu/hair/image/qwer.jpg"),
|
||||
("girl5", "/home/ubuntu/hair/image/girl_img/girl5.jpg"),
|
||||
]
|
||||
REPEAT = 3
|
||||
|
||||
|
||||
def gpu_used():
|
||||
"""返回当前显存已用 MiB。"""
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"],
|
||||
timeout=10,
|
||||
)
|
||||
return int(out.decode().strip())
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def call(img_path, model_file, res_val):
|
||||
"""调一次接口2。返回 dict: ok/elapsed/grown_path/gpu_peak/error。"""
|
||||
fd = {
|
||||
"gender": "female",
|
||||
"hair_style": "2", # 花瓣形
|
||||
"use_mask": "true",
|
||||
"prompt": "填充遮罩区域的头发,人物增加一点磨皮",
|
||||
}
|
||||
if model_file:
|
||||
fd["flux_model"] = model_file
|
||||
if res_val != "":
|
||||
fd["redraw_max_side"] = res_val
|
||||
t0 = time.perf_counter()
|
||||
peak = gpu_used()
|
||||
err = None
|
||||
grown_path = None
|
||||
try:
|
||||
with open(img_path, "rb") as f:
|
||||
r = requests.post(
|
||||
API, headers={"X-Internal-Token": TOKEN},
|
||||
files={"image_file": (os.path.basename(img_path), f, "image/jpeg")},
|
||||
data=fd, timeout=300,
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
# 采样峰值(推理刚结束)
|
||||
peak = max(peak, gpu_used())
|
||||
j = r.json()
|
||||
if j.get("code") != 0:
|
||||
err = f"code={j.get('code')} {j.get('message','')}"
|
||||
else:
|
||||
res = j.get("data", {}).get("results", [])
|
||||
if res and res[0].get("grown_image_base64"):
|
||||
grown_path = OUT / f"tmp_grown.jpg"
|
||||
with open(grown_path, "wb") as gf:
|
||||
gf.write(base64.b64decode(res[0]["grown_image_base64"]))
|
||||
elif res:
|
||||
err = "grown_image_base64 为空"
|
||||
else:
|
||||
err = "无 results"
|
||||
except Exception as e:
|
||||
elapsed = time.perf_counter() - t0
|
||||
err = str(e)[:200]
|
||||
return {"elapsed": elapsed, "gpu_peak": peak, "grown_path": str(grown_path) if grown_path else None, "error": err}
|
||||
|
||||
|
||||
def main():
|
||||
results = [] # 每元素一个组合
|
||||
total = len(MODELS) * len(RES) * len(IMGS) * REPEAT
|
||||
idx = 0
|
||||
for mlabel, mfile in MODELS:
|
||||
for rlabel, rval in RES:
|
||||
for ilabel, ipath in IMGS:
|
||||
# 一个组合:3 次
|
||||
runs = []
|
||||
for rep in range(REPEAT):
|
||||
idx += 1
|
||||
print(f"[{idx}/{total}] {mlabel} | res={rlabel} | {ilabel} | rep{rep+1}", flush=True)
|
||||
r = call(ipath, mfile, rval)
|
||||
print(f" -> {r['elapsed']:.1f}s peak={r['gpu_peak']}MiB err={r['error']}", flush=True)
|
||||
# 存每次的生发图
|
||||
if r["grown_path"]:
|
||||
save_to = OUT / f"{mlabel}_{rlabel}_{ilabel}_r{rep+1}.jpg"
|
||||
os.replace(r["grown_path"], save_to)
|
||||
r["grown_path"] = str(save_to)
|
||||
runs.append(r)
|
||||
results.append({
|
||||
"model": mlabel, "model_file": mfile,
|
||||
"res": rlabel, "res_val": rval,
|
||||
"img": ilabel, "img_path": ipath,
|
||||
"runs": runs,
|
||||
})
|
||||
# 存原始数据
|
||||
with open(OUT / "results.json", "w", encoding="utf-8") as f:
|
||||
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||
print(f"\n✓ 全部完成,原始数据 -> {OUT/'results.json'}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把 benchmark_out/matrix/results.json 生成 HTML 报告。
|
||||
每个组合一行:原图 + 3次生发图 + 耗时/显存。
|
||||
图片用 base64 内嵌(自包含单文件,便于部署)。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
OUT = Path("/home/ubuntu/hair/benchmark_out/matrix")
|
||||
RESULTS = OUT / "results.json"
|
||||
HTML = OUT / "report.html"
|
||||
|
||||
RES_LABEL = {"orig": "原图", "640": "640", "896": "896(默认)"}
|
||||
MODEL_LABEL = {
|
||||
"4b-fp8": "4B fp8 (3.8G)",
|
||||
"9b-fp8": "9B fp8 (8.8G)",
|
||||
"9b-Q5": "9B Q5_K_M (6.6G)",
|
||||
"9b-Q4": "9B Q4_K_M (5.6G)",
|
||||
}
|
||||
MODEL_ORDER = ["4b-fp8", "9b-Q4", "9b-Q5", "9b-fp8"]
|
||||
|
||||
|
||||
def img_src(path):
|
||||
"""把绝对路径转成报告里的相对 URL(报告在 static/,图片在 static/bench/)。"""
|
||||
if not path:
|
||||
return None
|
||||
p = str(path)
|
||||
# benchmark_out/matrix/xxx.jpg -> bench/matrix/xxx.jpg
|
||||
if "benchmark_out/matrix/" in p:
|
||||
return "bench/matrix/" + os.path.basename(p)
|
||||
if "benchmark_out/hairstyle/" in p:
|
||||
return "bench/hairstyle/" + os.path.basename(p)
|
||||
return None
|
||||
|
||||
|
||||
def thumb(src, alt="", cls=""):
|
||||
if not src:
|
||||
return f'<div class="na {cls}">⚠ 失败</div>'
|
||||
return f'<img class="{cls}" src="{src}" alt="{alt}" loading="lazy">'
|
||||
|
||||
|
||||
def main():
|
||||
data = json.load(open(RESULTS, encoding="utf-8"))
|
||||
# 原图相对路径映射(图片在 static/bench/orig/)
|
||||
ORIG_SRC = {"asdf": "bench/orig/asdf.jpg", "qwer": "bench/orig/qwer.jpg", "girl5": "bench/orig/girl5.jpg"}
|
||||
|
||||
# 统计:每个模型的平均耗时、平均峰值显存
|
||||
stats = {}
|
||||
for c in data:
|
||||
m = c["model"]
|
||||
stats.setdefault(m, {"times": [], "peaks": []})
|
||||
for r in c["runs"]:
|
||||
if not r["error"]:
|
||||
stats[m]["times"].append(r["elapsed"])
|
||||
stats[m]["peaks"].append(r["gpu_peak"])
|
||||
|
||||
rows_html = []
|
||||
# 按模型顺序、分辨率顺序、图片顺序排列
|
||||
for m in MODEL_ORDER:
|
||||
mdata = [c for c in data if c["model"] == m]
|
||||
for rlabel in ["orig", "640", "896"]:
|
||||
for ilabel in ["asdf", "qwer", "girl5"]:
|
||||
c = next((x for x in mdata if x["res"] == rlabel and x["img"] == ilabel), None)
|
||||
if not c:
|
||||
continue
|
||||
# 3 次结果图
|
||||
run_cells = []
|
||||
for i, r in enumerate(c["runs"]):
|
||||
src = img_src(r["grown_path"]) if not r["error"] else None
|
||||
if src:
|
||||
run_cells.append(
|
||||
f'<div class="run-cell"><div class="run-label">第{i+1}次 · {r["elapsed"]:.1f}s</div>'
|
||||
f'{thumb(src, f"r{i+1}", "result-img")}</div>'
|
||||
)
|
||||
else:
|
||||
run_cells.append(
|
||||
f'<div class="run-cell"><div class="run-label">第{i+1}次 · 失败</div>'
|
||||
f'<div class="na">⚠ {r["error"][:30] if r["error"] else ""}</div></div>'
|
||||
)
|
||||
|
||||
orig = ORIG_SRC.get(c["img"])
|
||||
rows_html.append(f'''
|
||||
<div class="combo-row">
|
||||
<div class="cell-model">{MODEL_LABEL.get(m, m)}<div class="cell-sub">res={RES_LABEL.get(rlabel, rlabel)}</div></div>
|
||||
<div class="cell-img">{thumb(orig, "原图", "orig-img")}<div class="run-label">{ilabel}</div></div>
|
||||
<div class="cell-runs">{"".join(run_cells)}</div>
|
||||
</div>''')
|
||||
|
||||
# 模型对比汇总
|
||||
summary_rows = []
|
||||
for m in MODEL_ORDER:
|
||||
s = stats.get(m, {"times": [], "peaks": []})
|
||||
if s["times"]:
|
||||
avg_t = sum(s["times"]) / len(s["times"])
|
||||
max_p = max(s["peaks"]) / 1024
|
||||
summary_rows.append(
|
||||
f"<tr><td>{MODEL_LABEL.get(m,m)}</td><td>{avg_t:.1f}s</td>"
|
||||
f"<td>{max_p:.1f} GB</td><td>{len(s['times'])} 成功</td></tr>"
|
||||
)
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Flux 模型矩阵测试报告 — 接口2女性花瓣形</title>
|
||||
<style>
|
||||
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
|
||||
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f5f5f5; color: #333; padding: 20px; }}
|
||||
h1 {{ font-size: 22px; margin-bottom: 4px; }}
|
||||
.subtitle {{ color: #888; font-size: 13px; margin-bottom: 16px; }}
|
||||
.summary {{ background: #fff; border-radius: 10px; padding: 16px 20px; margin-bottom: 20px; box-shadow: 0 1px 4px rgba(0,0,0,.06); }}
|
||||
.summary h2 {{ font-size: 16px; margin-bottom: 10px; }}
|
||||
.summary table {{ border-collapse: collapse; width: 100%; font-size: 14px; }}
|
||||
.summary th, .summary td {{ border: 1px solid #e5e7eb; padding: 8px 12px; text-align: left; }}
|
||||
.summary th {{ background: #f9fafb; font-weight: 600; }}
|
||||
.combo-row {{ display: flex; align-items: flex-start; gap: 12px; background: #fff; border-radius: 10px;
|
||||
padding: 12px 16px; margin-bottom: 10px; box-shadow: 0 1px 3px rgba(0,0,0,.05); }}
|
||||
.cell-model {{ min-width: 130px; font-weight: 700; font-size: 14px; padding-top: 6px; }}
|
||||
.cell-sub {{ font-weight: 400; font-size: 12px; color: #6b7280; margin-top: 2px; }}
|
||||
.cell-img {{ min-width: 160px; text-align: center; }}
|
||||
.cell-runs {{ display: flex; gap: 10px; flex: 1; }}
|
||||
.run-cell {{ text-align: center; }}
|
||||
.run-label {{ font-size: 11px; color: #6b7280; margin-bottom: 4px; }}
|
||||
img {{ border-radius: 6px; max-height: 200px; max-width: 100%; object-fit: contain; background: #f9fafb; }}
|
||||
.orig-img {{ max-height: 180px; border: 2px solid #e5e7eb; }}
|
||||
.result-img {{ max-height: 200px; }}
|
||||
.na {{ color: #d1d5db; font-size: 12px; padding: 40px 20px; background: #f9fafb; border-radius: 6px; width: 150px; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>💇 Flux 模型矩阵测试报告</h1>
|
||||
<p class="subtitle">接口2女性 · 花瓣形发型 · 4模型 × 3分辨率 × 3图 × 3次 = 108 次 · RTX 3090 24GB</p>
|
||||
|
||||
<div class="summary">
|
||||
<h2>📊 模型对比汇总</h2>
|
||||
<table>
|
||||
<tr><th>模型</th><th>平均耗时</th><th>峰值显存</th><th>成功次数</th></tr>
|
||||
{"".join(summary_rows)}
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h2 style="font-size:16px;margin:24px 0 12px">🖼️ 各组合对比(每行:原图 + 3次生发结果)</h2>
|
||||
{"".join(rows_html)}
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
with open(HTML, "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
print(f"✓ 报告已生成: {HTML} ({HTML.stat().st_size//1024} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -16,7 +16,7 @@
|
||||
Handler 签名新增:
|
||||
|
||||
```python
|
||||
prompt: str = Form(default="补充遮罩区域的头发", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,人物增加一点磨皮", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
```
|
||||
|
||||
透传链路:
|
||||
@@ -31,7 +31,7 @@ handler → generate_grow_results(image, gender, use_mask, prompt)
|
||||
Handler 签名新增:
|
||||
|
||||
```python
|
||||
prompt: str = Form(default="补充遮罩区域的头发", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
prompt: str = Form(default="填充遮罩区域的头发,人物增加一点磨皮", description="ComfyUI 提示词,会替换工作流节点60的文本"),
|
||||
```
|
||||
|
||||
透传链路:
|
||||
@@ -80,17 +80,17 @@ if prompt is not None:
|
||||
| 2 | `image_base64` | string | — | 同上 |
|
||||
| 2 | `gender` | string | `female` | `male` / `female` |
|
||||
| 2 | `use_mask` | bool | `true` | inpaint 遮罩开关 |
|
||||
| 2 | `prompt` | string | `补充遮罩区域的头发` | ComfyUI 提示词 |
|
||||
| 2 | `prompt` | string | `填充遮罩区域的头发,人物增加一点磨皮` | ComfyUI 提示词 |
|
||||
| 3 | `marked_image_file` | file | — | 划线图(三选一) |
|
||||
| 3 | `marked_image_url` | string | — | 同上 |
|
||||
| 3 | `marked_image_base64` | string | — | 同上 |
|
||||
| 3 | `use_mask` | bool | `true` | 画发际线开关 |
|
||||
| 3 | `prompt` | string | `补充遮罩区域的头发` | ComfyUI 提示词 |
|
||||
| 3 | `prompt` | string | `填充遮罩区域的头发,人物增加一点磨皮` | ComfyUI 提示词 |
|
||||
|
||||
## 3. 当前工作流提示词节点
|
||||
|
||||
`add_hair.json` 中节点 **60**(`JjkText`)为提示词节点,当前硬编码文本:
|
||||
|
||||
> 补充遮罩区补充遮罩区域内的头发,头发填满遮罩区域。发际线往下挡住额头
|
||||
> 填充遮罩区域的头发,人物增加一点磨皮
|
||||
|
||||
`comfyui.run()` 收到 `prompt` 参数后将替换此文本。
|
||||
|
||||
@@ -12,15 +12,18 @@
|
||||
|
||||
```
|
||||
客户端 ──HTTPS──> 外网网关(gateway/) ──HTTP(X-Internal-Token)──> worker(GPU 机, app.py)
|
||||
│ 薄代理 + 落盘改URL │ 跑算法(本地模型/ComfyUI)
|
||||
└ 接口4 本机直接调豆包(不转发) └ 接口1/2/3/5/6/7
|
||||
│ 薄代理 + 落盘改URL │ 跑算法(本地模型/ComfyUI/change_hair)
|
||||
└ 接口4(豆包)/99(特殊点) 本机实现(不转发) └ 接口1/2/3/5/6/7/9/10/11/12 + 工具路由
|
||||
```
|
||||
|
||||
- **worker**(`app.py` + `face_analysis/` + `hairline/`):跑真正的算法,**纯本地、无外网依赖**。
|
||||
对 `/api/*` 校验 `X-Internal-Token`(密码在 `worker_config.json` 的 `accept_passwords`);
|
||||
`/health` 模型就绪才返回 200。监听 **8187**(`./start.sh` 控制开关,`./run_worker.sh` 热重载)。
|
||||
- **worker**(`app.py` + `face_analysis/` + `hairline/`):跑真正的算法,除 ComfyUI/change_hair 走本机
|
||||
回环外无外网依赖。对 `/api/*` 校验 `X-Internal-Token`(密码在 `worker_config.json` 的 `accept_passwords`);
|
||||
`/health` 模型就绪才返回 200。监听 **8187**(systemd `hair-worker.service`,也可 `./run_worker.sh` 手动起)。
|
||||
另有 worker 本机的工具路由:`/api/swapHair/v1`、`/hairColor/v2`(CORS 代理转发 change_hair:8801)、
|
||||
`/api/v1/redraw`(直接 ComfyUI 重绘)、`/api/v1/debug/*`(免鉴权调试)。
|
||||
- **网关**(`gateway/`):薄反向代理,健康检查/派发/鉴权/把 worker 的 `*_base64` 落盘改成 `*_url`。
|
||||
唯一例外是**接口4 在网关本机直接实现**(调外网豆包,不转发 worker)。
|
||||
网关本机实现的接口(不转发 worker):**接口4**(调外网豆包)与**接口99**(纯 CPU 特殊点检测,
|
||||
直接 import 同仓库 `face_analysis/special_points`,`_if99_lock` 单路排队)。
|
||||
- **图片三选一**:所有接口图片入参 `image_file`/`image_url`/`image_base64` 严格三选一(接口3 是 `marked_image_*`)。
|
||||
- **响应信封**:`{code, message, request_id, data}`;业务错误用 `code`(HTTP 一律 200)。
|
||||
|
||||
@@ -33,7 +36,10 @@
|
||||
| 2 | `results[].image_base64` / `results[].grown_image_base64`(可空) | `results[].image_url` / `results[].grown_image_url` |
|
||||
| 3 | `hair_growth_image_base64`(可空) | `hair_growth_image_url` |
|
||||
| 5 | `hairline_images[].image_{middle,high,low}_base64` / `grown_image_base64`(可空) | `hairline_images[].image_{middle,high,low}_url` / `grown_image_url` |
|
||||
| 7 | `results[].image_base64` / `results[].grown_image_base64`(可空) | `results[].image_url` / `results[].grown_image_url` |
|
||||
| 9 | `steps_common.*_base64`、`bisenet|segformer.{hair,closed_region,final_overlay,mask}_mask_base64` 等 | 同名 `*_url` |
|
||||
| 10 | `steps_common.*_base64`、`bisenet|segformer.{base_mask,contour,band_overlay,mask}_base64` 等 | 同名 `*_url` |
|
||||
| 11 | `steps.{input,baseline,hair_mask,mask_overlay,mask,swap_raw,alpha,final}_base64` | `steps.*_url` |
|
||||
| 12 | `steps.{input,final,redraw_band_overlay,redraw_full,redraw_band,redraw_c}_base64` | `steps.*_url` |
|
||||
| 4 | (网关本机产出,无图片字段,`features` 为 JSON 字符串) | — |
|
||||
|
||||
> 实现建议:递归遍历 data,凡 key 以 `_base64` 结尾就落盘改 `_url`,自动覆盖嵌套/新增字段。
|
||||
@@ -47,7 +53,7 @@
|
||||
|
||||
---
|
||||
|
||||
## 2. 五个接口实现简述
|
||||
## 2. 各接口实现简述
|
||||
|
||||
### 接口1 四庭七眼测量 `/api/v1/face/measure`(worker)
|
||||
- **做什么**:正面照 → 四庭(顶/上/中/下庭) + 七眼(眼宽/脸宽/间距) 的 cm 与占比、5 个关键点坐标、一张透明底标注 PNG。
|
||||
@@ -65,10 +71,10 @@
|
||||
### 接口2 C端生发 `/api/v1/hair/grow`(worker)—— 预览 + 生发图
|
||||
- **做什么**:正面照 + `gender`(必填) + `hair_style`(必填,逗号分隔多选,如 `1,2,3`) → 指定发际线类型 **N 组**:**预览图**(发际线叠在照片上) + **生发后图**(植发3个月效果)。
|
||||
- **怎么实现**(`hairline/`):移植 head3d——MediaPipe(Tasks) + SegFormer 分割 + 17 锚点射线检测 → 502 点 mesh,
|
||||
按 `face_ext.obj` 的 UV 把发际线贴图渲染到额头(预览)。生发:黑贴图渲染遮罩 → 调本机 **ComfyUI 8182** 的
|
||||
按 `face_ext.obj` 的 UV 把发际线贴图渲染到额头(预览)。原生生发:黑贴图渲染遮罩 → 调本机 **ComfyUI 8188** 的
|
||||
`add_hair.json`(Flux-2) 出图。**关键坑**:obj 是重排序,需 `INDEX_MAP_468` 把 MP 序→OBJ 序。
|
||||
返回 `results[].image_base64` + `grown_image_base64`。
|
||||
- `hair_style` 映射:female 1=ellipse 2=flower 3=heart 4=straight 5=wave;male 1=ellipse 2=inverse_arc 3=m 4=straight。
|
||||
- `hair_style` 映射:female 1=ellipse 2=flower 3=heart 4=straight 5=wave 6=bigflower 7=clasicalflower;male 1=ellipse 2=inverse_arc 3=m 4=straight 5=heart 6=Softpetal 7=wave。female 1..5 走「换发型(change_hair)」+Flux-2 重绘管线(`generate_grow_results_swap`,复用接口12 final 的 `_V2_FINAL_DEFAULTS`,长边默认压到 `REDRAW_MAX_SIDE`=1024 再放大回原尺寸);female 6/7 与 male 全部走原生发(ComfyUI add_hair)管线。可选参数 `flux_model`(切换 Flux unet,.gguf 自动配 UnetLoaderGGUF + 配套 qwen CLIP)、`redraw_max_side`(0=不缩图)。
|
||||
|
||||
### 接口7 C端生发 v2 `/api/v1/hair/grow-v2`(worker)—— 接口2同款,add_hair2 工作流
|
||||
- **做什么**:与接口 2 完全一致(正面照 + `gender` + `hair_style` 逗号分隔多选 → N 组预览+生发图)。
|
||||
@@ -92,20 +98,50 @@
|
||||
- **做什么**:入参同接口2(`gender` + 多选 `hair_style` 必填)。对每个选中发型 → `middle`/`high`/`low` 三档发际线叠图 + 生发图 + 首个选中发型的面部中间点坐标。
|
||||
- **怎么实现**:复用接口2 的 502 点渲染管线,三档分别用 `hairline_texture[/_high|/_low]` 同名贴图渲染叠图;生发同接口2(ComfyUI inpaint),**黑模板固定取 `hairline_texture_black/`(middle)**,每发型 1 张生发图。`best_hairline_center_point`=眉心 x × 首个选中发型 middle 档发际线 y。
|
||||
|
||||
### 接口9 头发遮罩 `/api/v1/head/mask`(worker)
|
||||
- **做什么**:人像照 → 头发遮罩 + 全流程分步可视化。
|
||||
- **怎么实现**(`face_analysis/head_mask.py`):MediaPipe 底部分割线(21/68/104/69/108/151/337/299/333/298/251 连线,21/251 水平延伸)→ 线以上为上半区 → BiSeNet 与 SegFormer 双路头发分割、逐列向下填充到分割线得闭合区域(头发+额头)→ 外缘朝 151 内缩 `erode_cm`(默认1.2cm,虹膜标定) → 最终遮罩。返回 `steps_common` + `bisenet`/`segformer` 两组各四张图。
|
||||
|
||||
### 接口10 头部外缘膨胀带 `/api/v1/head/band`(worker)
|
||||
- **做什么**:在接口9 基准遮罩基础上,沿头部外缘生成一条膨胀带遮罩。
|
||||
- **怎么实现**(`face_analysis/head_band.py`):取基准遮罩外轮廓、去掉贴底分割线段 → 膨胀成总宽 `dilate_cm`(默认2cm) 的带子 → 裁到分割线以上。返回 `base_mask`/`contour`/`band_overlay`/`mask` 分步图。
|
||||
|
||||
### 接口11 发际线生发 `/api/v1/hairline/grow`(worker)—— 不含重绘
|
||||
- **做什么**:发际线偏高/头发稀少正脸图 + `hairline_id`(= change_hair `hair_id`,如 `chang_tuoyuan`)→ 压低发际线图 + 全步骤可视化。
|
||||
- **怎么实现**(`face_analysis/hairline_grow.py`,算法见 `发际线增强算法.md`):① 接口9 遮罩(`seg_model` 选 bisenet/segformer)→ ② 调 change_hair 生成该发际线类型图(`swap_mode=ext_mask` 把遮罩传给 webui 精确重绘 / `as_is` 用其内部遮罩;`gen_backend` 可换 hairgrow 区域生发 inpaint)→ ③ 严格按遮罩贴回 → ④ 接缝融合 `blend_method`(multiband 默认 / seamless / two_stage / feather / alpha_gradient,可选 Reinhard `color_match`)。返回 `steps.{input,baseline,hair_mask,mask_overlay,mask,swap_raw,alpha,final}`。
|
||||
|
||||
### 接口12 发际线带重绘 `/api/v1/hairline/grow_v2[_final[_v2]]`(worker)
|
||||
- **做什么**:接口11 的下游重绘阶段——先跑接口11 拿 ④final,再取发际线重绘带(外推 `band_lo_mult×push`~`band_hi_mult×push`,默认 0.5×~1.5×)作遮罩,用 **Flux-2(ComfyUI,`0716add-hair-api.json`,reference-latent 保色)** 重绘,产出两版:`redraw_full`(整帧美颜+整帧重绘)与 `redraw_band`(band 内加发、band 外 final 结构 + `beauty_alpha` 融入全脸美颜)。
|
||||
- **三个变体**:`grow_v2` 全参数暴露(接口11 参数 + `comfyui_prompt`/`beauty_alpha`/`band_lo_mult`/`band_hi_mult`);`grow_v2_final` / `grow_v2_final_v2` 精简生产版——仅图片 + `hairline_id`,其余固化 `_V2_FINAL_DEFAULTS`(push=0.8cm / two_stage / color_match=关 / beauty_alpha=0.6 等),两者后端计算完全一致(同一次输出含 A/B 两版),差异只是测试页展示哪版。接口2 女性 1..5 的生发图即复用此管线。
|
||||
- ⚠️ 依赖 ComfyUI(:8188);重绘失败在 `data.redraw.c_error` 报告。
|
||||
|
||||
### 接口99 人脸特殊点 `/api/v1/face/special-points`(**网关本机**,worker 保留同路径备份)
|
||||
- **做什么**:人脸照 → 60 个固定编号 MediaPipe 关键点(6 组:eyebrow/eye/mouth/nose_midline/cheek/face_edge)+ 5 个发际线特殊点,原图像素坐标 JSON(字段 `<组名>_<点ID>`,如 `eyebrow_107`)。
|
||||
- **怎么实现**(`face_analysis/special_points.py`):MediaPipe 单例取关键点;发际线点=接口1 方案B 的 BiSeNet 头发 mask 上沿指定关键点方向(如 151→10)射线步进取首个头发像素,双射线的(right/right_right/left/left_left)取中点。**纯 CPU 可跑**(BiSeNet 单核 <1s),网关直接 import 本机实现(`_if99_lock` 单路排队);worker 侧保留同路径接口供测试页直连。部署依赖清单见 `网关待改动.md` §9。
|
||||
- 测试页:`static/test_interface99.html`(canvas 可视化 + JSON,worker 本机直连)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 部署 / 环境要点
|
||||
|
||||
**worker(GPU 机)**
|
||||
- Python **3.12**(系统 3.13 无 mediapipe/torch wheel);venv 在 `./venv`,依赖 `requirements.txt`。
|
||||
- `numpy<2`(1.26.4),`scikit-image==0.24.0`(**别升 0.25+,会顶 numpy≥2 顶崩 mediapipe**)。
|
||||
- ⚠️ 本机 **RTX 5090(sm_120)**,pinned `torch 2.2.2(cu121)` 只到 sm_90 → GPU 算子报 "no kernel image",
|
||||
代码已自动**回退 CPU**(BiSeNet/SegFormer CPU 推理可用)。要用 5090 GPU 需换 torch cu128(≥2.7)。
|
||||
**worker(GPU 机,本机 = gpu_worker 角色)**
|
||||
- Python **3.10.12**(本机 venv 在 `./venv`);`numpy<2`(1.26.4),`scikit-image==0.24.0`
|
||||
(**别升 0.25+,会顶 numpy≥2 顶崩 mediapipe**)。
|
||||
- 本机 **RTX 4090**:venv 实装 `torch 2.7.1+cu128`,CUDA 可用(BiSeNet/SegFormer GPU 推理)。
|
||||
`requirements.txt` 里 pinned 的 `torch 2.2.2(cu121)` 及 5090 注释是旧机(sm_120 无 cu121 kernel、
|
||||
自动回退 CPU)的记录,本机以 venv 实际版本为准。
|
||||
- 模型权重/字体见 [`../OFFLINE_ASSETS.md`](../OFFLINE_ASSETS.md);BiSeNet/SegFormer/face_landmarker.task 本地。
|
||||
- 生发接口依赖本机 **ComfyUI(8188)**(Flux-2,它自带支持 5090 的 torch);worker 只调其 HTTP API,不跑 Flux。
|
||||
ComfyUI 开了 **HTTP Basic Auth**(user `admin` + 密码);密码放 `password.txt`(不入 git) /
|
||||
`worker_config.json.comfyui_password` / 环境变量 `COMFYUI_PASSWORD`,URL 用 `COMFYUI_URL`。
|
||||
- `worker_config.json`(不入 git):`accept_passwords`(鉴权) + 鉴权头 `X-Internal-Token`。
|
||||
- 生发接口依赖本机 **ComfyUI(8188)**(Flux-2,systemd `comfyui.service`,`--cache-classic --fast`);
|
||||
worker 只调其 HTTP API,不跑 Flux。ComfyUI 开了 **HTTP Basic Auth**(user `admin` + 密码);
|
||||
密码放 `password.txt`(不入 git) / `worker_config.json.comfyui_password` / 环境变量 `COMFYUI_PASSWORD`,
|
||||
URL 用 `COMFYUI_URL`。默认模型 flux-2-klein-9b Q4_K_M GGUF(接口2 `flux_model` 参数可切)。
|
||||
- 换发型依赖本机 **change_hair**(`/home/ubuntu/change_hair`,三进程 webui:57860(sdwebui) →
|
||||
photo_service:32678(py310/kohya) → hair_service_sd:8801(my_hair),`start_all.sh start|stop|status`,
|
||||
也有 systemd `change_hair-{webui,photo,hair}.service`)。不跑时接口2女1..5、接口11/12、
|
||||
swapHair/hairColor 代理不可用。
|
||||
- `worker_config.json`(不入 git):`accept_passwords`(鉴权) + `comfyui_password`;鉴权头 `X-Internal-Token`。
|
||||
- systemd 单元:`hair-worker.service`(8187) / `comfyui.service`(8188),仓库根有副本;手动启停用
|
||||
`./run_worker.sh` / `./stop_worker.sh`。
|
||||
|
||||
**网关机**
|
||||
- 很轻:FastAPI/uvicorn/httpx + **接口4 的 `volcengine-python-sdk[ark]`**(或直接 httpx 调,OpenAI 兼容)。
|
||||
|
||||
@@ -265,10 +265,12 @@
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| gender | string | **是** | 性别:`male` / `female`。决定使用的发际线贴图集合 |
|
||||
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数。female:1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave;male:1=ellipse, 2=inverse_arc, 3=m, 4=straight。越界/非法返回 `1007` |
|
||||
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),最多不超过该性别的预设数。female:1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave, 6=bigflower, 7=clasicalflower;male:1=ellipse, 2=inverse_arc, 3=m, 4=straight, 5=heart, 6=Softpetal, 7=wave。越界/非法返回 `1007` |
|
||||
| beauty_enabled | bool | 否 | 生发图是否带美颜效果,默认 false(当前阶段不生效) |
|
||||
| use_mask | bool | 否 | 是否启用 inpaint 遮罩,默认 `true`。`false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比 |
|
||||
| prompt | string | 否 | ComfyUI 提示词,默认「补充遮罩区域的头发,加一点美颜」,会替换工作流节点 60 的文本 |
|
||||
| use_mask | bool | 否 | 是否启用 inpaint 遮罩,默认 `true`。`false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比。仅对原生发(male / female 6/7)管线生效 |
|
||||
| prompt | string | 否 | ComfyUI 提示词,默认「填充遮罩区域的头发,人物增加一点磨皮」,会替换工作流节点 60 的文本。所有分支生效(male / female 6/7 原生生发,female 1..5 换发型后的发际线带重绘;不进 change_hair)。注:非默认提示词会使 ComfyUI 的 CLIP 条件缓存失效,换词后首次请求明显变慢(实测 45s vs 命中缓存 8s),相同提示词的后续请求恢复正常 |
|
||||
| flux_model | string | 否 | Flux 模型文件名(如 `flux-2-klein-9b-Q5_K_M.gguf`)。缺省用工作流默认(9B-Q4_K_M);`.gguf` 自动切 UnetLoaderGGUF 并同步配套 qwen CLIP |
|
||||
| redraw_max_side | int | 否 | female 1..5 重绘管线送模型前的长边上限像素。缺省=服务端默认(`REDRAW_MAX_SIDE`,当前 1024);`0`=不缩图(原图直送,更慢) |
|
||||
|
||||
### 输出(data)
|
||||
|
||||
@@ -278,10 +280,11 @@
|
||||
|------|------|------|
|
||||
| image_url | string | 发际线曲线**透明 PNG** URL(仅白色发际线曲线,透明底,**不含人物**,需前端叠加原图显示) |
|
||||
| grown_image_url | string | **生发后图片** URL(ComfyUI/Flux「植发 3 个月」效果图,完整人像照片) |
|
||||
| hairline_type | string | 发际线类型 key:`ellipse`/`flower`/`heart`/`straight`/`wave`(female),`ellipse`/`m`/`straight`/`inverse_arc`(male) |
|
||||
| hairline_type | string | 发际线类型 key:`ellipse`/`flower`/`heart`/`straight`/`wave`/`bigflower`/`clasicalflower`(female),`ellipse`/`m`/`straight`/`inverse_arc`/`heart`/`Softpetal`/`wave`(male) |
|
||||
| order | int | 排序序号(当前阶段固定 `1..N`,按贴图顺序,暂不计算合适度) |
|
||||
|
||||
> ⚠️ 生发图由本机 ComfyUI(Flux-2,端口 8182)生成,**一次请求生成指定发型的 1 张、同步返回**。
|
||||
> ⚠️ 生发图由本机 ComfyUI(Flux-2,端口 8188)生成,**一次请求生成指定发型的 1 张、同步返回**;
|
||||
> female 1..5 的生发图另依赖 change_hair 换发型服务(:8801)。
|
||||
> worker 侧返回 `image_base64` / `grown_image_base64`,
|
||||
> 网关落盘后改写为上表的 `image_url` / `grown_image_url`。
|
||||
>
|
||||
@@ -405,8 +408,8 @@
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| gender | string | **是** | 性别:`male` / `female`。决定发型集合(female 5 / male 4)。缺失/非法返回 `1004` |
|
||||
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),决定返回哪些发际线类型。female:1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave;male:1=ellipse, 2=inverse_arc, 3=m, 4=straight。缺失/越界/非法返回 `1007` |
|
||||
| gender | string | **是** | 性别:`male` / `female`。决定发型集合(female 7 / male 7)。缺失/非法返回 `1004` |
|
||||
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`),决定返回哪些发际线类型。female:1=ellipse, 2=flower, 3=heart, 4=straight, 5=wave, 6=bigflower, 7=clasicalflower;male:1=ellipse, 2=inverse_arc, 3=m, 4=straight, 5=heart, 6=Softpetal, 7=wave。缺失/越界/非法返回 `1007` |
|
||||
| use_mask | bool | 否 | 生发是否启用 inpaint 遮罩,默认 `true`。`false` 时用干净原图生成(空遮罩、不烧模板黑线),供测试对比 |
|
||||
| prompt | string | 否 | ComfyUI 提示词,默认「补充遮罩区域的头发,加一点美颜」,会替换工作流节点 60 的文本 |
|
||||
| generate_grow_image | bool | 否 | 是否生成生发效果图(ComfyUI 生发,全流程最耗时),默认 `true`。传 `false` 时跳过生发,各发型 `grown_image_*` 恒为 `null`,仅返回三档发际线叠图与中心点,可大幅降低耗时 |
|
||||
@@ -427,7 +430,7 @@
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| hairline_type | string | 发际线类型 key:`ellipse`/`flower`/`heart`/`straight`/`wave`(female),`ellipse`/`m`/`straight`/`inverse_arc`(male) |
|
||||
| hairline_type | string | 发际线类型 key:`ellipse`/`flower`/`heart`/`straight`/`wave`/`bigflower`/`clasicalflower`(female),`ellipse`/`m`/`straight`/`inverse_arc`/`heart`/`Softpetal`/`wave`(male) |
|
||||
| image_middle_url | string | middle 档发际线曲线**透明 PNG** URL(仅曲线,透明底,**不含人物**,需叠加原图显示) |
|
||||
| image_high_url | string | high 档发际线曲线**透明 PNG** URL(同上,high 档曲线) |
|
||||
| image_low_url | string | low 档发际线曲线**透明 PNG** URL(同上,low 档曲线) |
|
||||
@@ -446,7 +449,7 @@
|
||||
| four_courts | object | 四庭数据(顶/上/中/下庭 cm + 占比 ratios),结构同接口1 |
|
||||
| seven_eyes | object | 七眼数据(眼宽/脸宽/两眼间距 cm + 占比 ratios + eye1~eye7 从左到右 7 段宽度),结构同接口1 |
|
||||
| landmarks | object | 5 个纵向关键点像素坐标(hair_top/hairline/brow_center/nose_bottom/chin_tip),结构同接口1 |
|
||||
| hairline_source | string | 发际线来源:`segmentation`(真实分割)/ `estimated`(比例估算) |
|
||||
| hairline_source | string | 发际线来源:`segmentation`(真实分割)/ `estimated`(比例估算)/ `corrected`(发际线贴近头顶、分割不可靠,已按 0.95×中庭反推修正) |
|
||||
| head_pose | object | 头部姿态角度(yaw/pitch/roll,单位:度) |
|
||||
| left_position | object | MediaPipe 21 号关键点坐标(左脸定位点),原图像素:`{ "x": int, "y": int }` |
|
||||
| right_position | object | MediaPipe 251 号关键点坐标(右脸定位点,与 21 号镜像),原图像素:`{ "x": int, "y": int }` |
|
||||
@@ -515,16 +518,197 @@
|
||||
|
||||
---
|
||||
|
||||
## 接口 9:头发遮罩生成接口
|
||||
|
||||
**说明**:输入一张含人头的照片,生成头发遮罩,并返回**每一步的可视化图**(供对比调试)。
|
||||
|
||||
**请求**:`POST /api/v1/head/mask`
|
||||
|
||||
### 输入
|
||||
|
||||
图片参数见「通用约定 → 图片传参字段」。专属参数:
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| erode_cm | float | 否 | 外缘朝中心(鼻梁 151 点)内缩的距离(厘米),默认 1.2 |
|
||||
|
||||
### 处理流程
|
||||
|
||||
1. MediaPipe 关键点 → 底部分割线(关键点 21,68,104,69,108,151,337,299,333,298,251 的连线,21 水平延伸到最左、251 延伸到最右)。
|
||||
2. 分割线以上为「上半区」。
|
||||
3. 头发分割(**BiSeNet** 与 **SegFormer** 两套);从每列最顶端头发向下填充到分割线,得到**含额头**的闭合区域(头发+额头,不割断)。
|
||||
4. 外缘朝中心点 151 内缩 `erode_cm`(虹膜标定换算像素)、底线不动 → 最终遮罩。
|
||||
|
||||
### 输出(data)
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| px_per_cm | float | 虹膜标定出的像素/厘米 |
|
||||
| erode_cm / erode_px | float / int | 内缩距离(厘米 / 像素) |
|
||||
| image_size | object | `{width, height}` 原图尺寸 |
|
||||
| steps_common | object | `landmarks_baseline_*`(关键点/分割线)、`upper_region_*`(上半区) |
|
||||
| bisenet / segformer | object | 两套分割模型各自的结果:`hair_mask_*`(原始头发分割)、`closed_region_*`(含额头闭合区域)、`final_overlay_*`(最终遮罩叠加可视化)、`mask_*`(最终遮罩 PNG)及 `hair_pixels`/`closed_pixels`/`mask_pixels` 像素计数 |
|
||||
|
||||
> worker 返回 `*_base64`(data URI),经网关改写为 `*_url`。
|
||||
|
||||
---
|
||||
|
||||
## 接口 10:头部外缘膨胀带遮罩接口
|
||||
|
||||
**说明**:先和接口9 一样得到内缩后的基准遮罩,再沿头部外缘生成一条膨胀带遮罩。
|
||||
|
||||
**请求**:`POST /api/v1/head/band`
|
||||
|
||||
### 输入
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| erode_cm | float | 否 | 基准遮罩外缘朝 151 内缩距离(厘米,同接口9),默认 1.2 |
|
||||
| dilate_cm | float | 否 | 外轮廓线膨胀后带子总宽(厘米),默认 2.0 |
|
||||
|
||||
### 处理流程
|
||||
|
||||
1. 取基准遮罩的**外轮廓线**,去掉贴着底部分割线的那一段(只留头发/头部外缘弧线)。
|
||||
2. 把外轮廓线膨胀成带子(总宽 `dilate_cm`;半径=总宽/2,虹膜标定换算像素)。
|
||||
3. 裁到分割线以上(不越过底线)。
|
||||
|
||||
### 输出(data)
|
||||
|
||||
结构同接口9,但每组结果为 `base_mask_*`(基准遮罩)/ `contour_*`(外轮廓线)/ `band_overlay_*`(带子叠加可视化)/ `mask_*`(最终带状遮罩)及 `base_pixels`/`band_pixels` 计数,另有 `dilate_cm`/`dilate_radius_px`。
|
||||
|
||||
---
|
||||
|
||||
## 接口 11:发际线生发接口(不含重绘)
|
||||
|
||||
**说明**:输入一张**发际线较高 / 头发稀少**的正脸图 + 发际线类型 ID,输出同一个人、同一发型、按该类型压低发际线后的图片,并返回**每一步可视化**。重绘版见接口12。
|
||||
|
||||
**请求**:`POST /api/v1/hairline/grow`
|
||||
|
||||
### 输入
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| hairline_id | string | **是** | 发际线类型 ID(= change_hair `hair_id`):`chang_tuoyuan` / `chang_huaban` / `chang_xinxing` / `chang_zhixian` / `chang_bolang` |
|
||||
| gen_backend | string | 否 | 生成后端:`swaphair`(换发型 LoRA,默认)|`hairgrow`(区域生发 inpaint) |
|
||||
| hairgrow_strength | float | 否 | 区域生发强度(仅 hairgrow 后端),默认 0.75 |
|
||||
| is_hr | bool | 否 | 高清模式(换发型输出 1152×1536,否则 576×768),默认 false |
|
||||
| seg_model | string | 否 | 头发分割模型:`bisenet` | `segformer`(默认) |
|
||||
| erode_cm | float | 否 | baseline 参考内缩距离(厘米),默认 0.6 |
|
||||
| hairline_push_cm | float | 否 | 发际线外推距离(厘米,往头发方向推进),默认 1.0 |
|
||||
| hairline_edge | string | 否 | 发际线提取方式:`column`(默认)|`contour` |
|
||||
| swap_mode | string | 否 | 换发型取图模式:`ext_mask`(默认,把接口9 遮罩传给 webui 精确重绘)|`as_is`(用内部遮罩,贴回时再裁) |
|
||||
| edge_erode_px | int | 否 | 贴图前遮罩内缩像素(防边缘露皮/光晕),默认 3 |
|
||||
| denoising_strength | float | 否 | 换发型 webui 重绘强度(越大生发越激进),默认 0.6 |
|
||||
| mb_levels | int | 否 | 多频段金字塔层数(2~6),默认 5 |
|
||||
| blend_method | string | 否 | 接缝融合:`multiband`(默认)|`seamless`(泊松)|`two_stage`(泊松→多频段)|`feather`(高斯羽化)|`alpha_gradient`(距离渐变) |
|
||||
| color_match | bool | 否 | 融合前 Reinhard 颜色迁移消除整体色差,默认 true |
|
||||
| color_match_strength | float | 否 | 颜色迁移强度(0~1),默认 1.0 |
|
||||
| mb_feather_px | int | 否 | 多频段最细层掩码轻羽化像素,默认 1 |
|
||||
| transition_band_px | int | 否 | keep-region 过渡带边距(-1=自动按层数 2^n),默认 -1 |
|
||||
| inpainting_fill | int | 否 | change_hair 服务端重绘填充:0=保留原图 | 1=噪声(默认)| 2=纯色 | 3=潜变量噪声 |
|
||||
| mask_blur | int | 否 | change_hair 服务端遮罩边缘模糊像素,默认 11 |
|
||||
| mask_dilate_scale | float | 否 | change_hair 服务端遮罩膨胀缩放(<1 收缩防越界),默认 1.0 |
|
||||
|
||||
### 输出(data)
|
||||
|
||||
`steps`:`input`(原图)/ `baseline`(底部分割线)/ `hair_mask`(头发分割)/ `mask_overlay`(遮罩叠加)/ `mask`(遮罩)/ `swap_raw`(换发型原始输出)/ `alpha`(融合权重)/ `final`(最终结果)各步图(`*_base64`,经网关改写为 `*_url`),另有 `timings_ms` 分步耗时。
|
||||
|
||||
> ⚠️ `swaphair` 后端依赖 change_hair(:8801)在跑;`hairgrow` 后端依赖 ComfyUI(:8188)。
|
||||
|
||||
---
|
||||
|
||||
## 接口 12:发际线带重绘接口
|
||||
|
||||
**说明**:接口11 的**下游重绘阶段**——内部先跑接口11 核心管线拿 ④ 接缝融合最终图(final),再取发际线重绘带(外推 `band_lo_mult×push` ~ `band_hi_mult×push` 之间、经 baseline 截断只留上部的带状区域)作遮罩,用 **Flux-2(ComfyUI,reference-latent 保色重绘)** 重绘。
|
||||
|
||||
**同时产出两版结果**:
|
||||
|
||||
- `redraw_full`:ComfyUI 整帧输出(全脸美颜 + 全脸重绘)。
|
||||
- `redraw_band`:加发只在发际线带内、band 外保留 final 结构并按 `beauty_alpha` 融入全脸美颜。
|
||||
|
||||
**请求**:`POST /api/v1/hairline/grow_v2`
|
||||
|
||||
### 输入
|
||||
|
||||
接口11 的全部参数(见上表)再叠加:
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| comfyui_prompt | string | 否 | Flux-2 重绘提示词,缺省「填充遮罩区域的头发,人物增加一点磨皮」 |
|
||||
| beauty_alpha | float | 否 | redraw_band 版 band 外的全脸美颜融入强度(0=band 外纯用 final,1≈整帧版),默认 0.6 |
|
||||
| band_lo_mult | float | 否 | 重绘带外推倍率下限(相对 hairline_push_cm),默认 0.5 |
|
||||
| band_hi_mult | float | 否 | 重绘带外推倍率上限(相对 hairline_push_cm),默认 1.5 |
|
||||
|
||||
### 输出(data)
|
||||
|
||||
`steps`:`input` / `final`(重绘输入基底)/ `redraw_band_overlay`(重绘带可视化)/ `redraw_full`(A 整帧)/ `redraw_band`(B 局部+美颜)/ `redraw_c`(兼容旧字段,=redraw_full);重绘异常在 `redraw.c_error` 报告。
|
||||
|
||||
### 精简变体(生产推荐)
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `POST /api/v1/hairline/grow_v2_final` | 仅需图片 + `hairline_id`,其余参数固化为调优默认值(push=0.8cm / two_stage / color_match=关 等),**最终取整帧重绘 `redraw_full`** |
|
||||
| `POST /api/v1/hairline/grow_v2_final_v2` | 参数同上,**最终取 B 局部加发+全脸美颜 `redraw_band`** |
|
||||
|
||||
> ⚠️ 依赖 ComfyUI(:8188)与 change_hair(:8801)均在跑。接口2 女性 1..5 的生发图即复用 `grow_v2_final` 管线。
|
||||
|
||||
---
|
||||
|
||||
## 接口 99:人脸特殊点检测接口
|
||||
|
||||
**说明**:输入一张人脸照片,返回一组**固定编号 MediaPipe Face Mesh 关键点**的像素坐标,外加 5 个**发际线特殊点**(射线与头发分割发际线的交点)。**生产路径:网关本机实现(纯 CPU,不转发 worker,同接口4 模式)**;worker 侧保留同路径接口供测试页直连。
|
||||
|
||||
**请求**:`POST /api/v1/face/special-points`
|
||||
|
||||
### 输入
|
||||
|
||||
图片参数见「通用约定 → 图片传参字段」,无专属参数。要求单人正面照(非正面返回 `1003`)。
|
||||
|
||||
### 输出(data)
|
||||
|
||||
`points`:字段名 = `<组英文名>_<点ID>`,值为原图像素坐标 `{x, y}`(int);发际线点不可得(秃顶/分割失败)时为 null。
|
||||
|
||||
| 组 | 字段前缀 | 点 ID |
|
||||
|----|----------|-------|
|
||||
| 眉毛 | `eyebrow` | 107 66 105 63 70 336 296 334 293 300 |
|
||||
| 眼睛 | `eye` | 189 222 224 113 226 413 442 444 342 446 |
|
||||
| 嘴 | `mouth` | 0 37 40 67 91 84 17 405 375 409 269 |
|
||||
| 中线鼻 | `nose_midline` | 9 168 197 5 4 194 278 48 437 217 |
|
||||
| 面颊 | `cheek` | 101 117 123 187 205 50 330 346 352 280 425 |
|
||||
| 边线 | `face_edge` | 162 234 58 136 149 152 378 365 288 401 366 389 251 |
|
||||
|
||||
**发际线特殊点**(沿关键点 a→b 方向射线步进,首次进入 BiSeNet 头发 mask 处为交点;双射线取中点,仅一条命中返回该点):
|
||||
|
||||
| 字段 | 计算 |
|
||||
|------|------|
|
||||
| `hair_line_center` | 151→10 方向交点 |
|
||||
| `hair_line_right` | mid(108→109 交点A, 69→67 交点B) |
|
||||
| `hair_line_right_right` | mid(104→103 交点A, 68→54 交点B) |
|
||||
| `hair_line_left` | mid(337→338 交点A, 299→297 交点B) |
|
||||
| `hair_line_left_left` | mid(333→332 交点A, 298→284 交点B) |
|
||||
|
||||
另有 `image_size`(宽高)与 `hairline_source`(`segmentation`=发际线点已算出 / `unavailable`=分割不可用,发际线点为 null)。
|
||||
|
||||
---
|
||||
|
||||
## 汇总:输入输出一览
|
||||
|
||||
| 接口 | 输入 | 主要输出 |
|
||||
|------|------|----------|
|
||||
| 1 四庭七眼测量 | 用户照片 | 标注 PNG(无人物)+ 四庭/七眼厘米数值与坐标 |
|
||||
| 6 四庭七眼测量 v2 | 用户照片 | 同接口1,复刻实现 |
|
||||
| 2 C 端生发 | 用户照片 | 生发后图片 + 指定发际线预览(单/多张) |
|
||||
| 3 B 端生发 | 划线图片 | 最合适发际线图片 + 生发后图片 |
|
||||
| 4 用户特征 | 用户照片 | 6 个用户特征字段(脸形/眉形/年龄/动静/性别/基因风格) |
|
||||
| 5 发际线 PNG | 用户照片 + gender + hair_style(多选) | 每个选中发型 middle/high/low 三档发际线叠图 + 生发图 + 最合适发际线面部中间点坐标 |
|
||||
| 接口 | 路径 | 输入 | 主要输出 |
|
||||
|------|------|------|----------|
|
||||
| 1 四庭七眼测量 | `/api/v1/face/measure` | 用户照片 | 标注 PNG(无人物)+ 四庭/七眼厘米数值与坐标 |
|
||||
| 6 四庭七眼测量 v2 | `/api/v1/face/measure-v2` | 用户照片 | 同接口1,去顶庭变体 |
|
||||
| 2 C 端生发 | `/api/v1/hair/grow` | 用户照片 + gender + hair_style(多选) | 每发型预览 PNG + 生发图(female 1..5=换发型+重绘,其余=原生生发) |
|
||||
| 7 C 端生发 v2 | `/api/v1/hair/grow-v2` | 同接口2 | 同接口2(add_hair2 工作流,已弃用隐藏) |
|
||||
| 3 B 端生发 | `/api/v1/hair/grow-b` | 划线图片 | 检测到的发际线 + 生发后图片 |
|
||||
| 4 用户特征 | `/api/v1/face/features` | 用户照片 | 6 个用户特征字段(脸形/眉形/年龄/动静/性别/基因风格),网关本机实现 |
|
||||
| 5 发际线 PNG | `/api/v1/hairline/generate` | 用户照片 + gender + hair_style(多选) | 每个选中发型 middle/high/low 三档发际线叠图 + 生发图 + 最合适发际线面部中间点坐标 |
|
||||
| 9 头发遮罩 | `/api/v1/head/mask` | 用户照片 | 头发遮罩 + 分步可视化(BiSeNet/SegFormer 双路) |
|
||||
| 10 外缘膨胀带 | `/api/v1/head/band` | 用户照片 | 头部外缘带状遮罩 + 分步可视化 |
|
||||
| 11 发际线生发 | `/api/v1/hairline/grow` | 用户照片 + hairline_id | 压低发际线图 + 全步骤可视化(不含重绘) |
|
||||
| 12 发际线带重绘 | `/api/v1/hairline/grow_v2` | 同接口11 + 重绘带参数 | final 基底 + Flux-2 保色重绘(整帧/局部两版);精简版 `grow_v2_final[_v2]` 仅需图片+hairline_id |
|
||||
| 99 人脸特殊点 | `/api/v1/face/special-points` | 用户照片 | 60 个固定编号关键点 + 5 个发际线特殊点像素坐标 JSON(**网关本机实现**,同接口4) |
|
||||
|
||||
> 另有 worker 本机工具路由(不在对外契约内):`/api/swapHair/v1`、`/hairColor/v2`(CORS 代理 change_hair)、`/api/v1/redraw`(直接 ComfyUI 重绘)、`/api/v1/debug/*`。
|
||||
|
||||
---
|
||||
|
||||
@@ -534,7 +718,7 @@
|
||||
- 默认单人;检测到 2~3 人报错提示客户端;单文件 **≤ 1 MB**;格式仅 **JPG / PNG**。
|
||||
- 所有坐标基准:**原图像素**。
|
||||
- 接口 2:提供「美颜」开关 `beauty_enabled`。
|
||||
- 接口 3:需同时上传原图,需返回发际线类型。
|
||||
- 接口 3:仅传**划线图**(`marked_image_*` 三选一),需返回发际线类型(`custom`)。
|
||||
- 接口 4:`data` 返回**一个 JSON 字符串**,字段不固定,可随时调整。
|
||||
- 接口 5:发际线 PNG 数量 **N 不固定**,需按合适度**排序**。
|
||||
- 英文字段命名由本文档约定(见各接口表格)。
|
||||
|
||||
@@ -70,7 +70,7 @@ async def hair_grow_v2(request: Request):
|
||||
|------|------|------|------|
|
||||
| image_file / image_url / image_base64 | — | **三选一** | 用户正面照 |
|
||||
| gender | string | **是** | `male` / `female` |
|
||||
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`)。female: 1–5,male: 1–4 |
|
||||
| hair_style | string | **是** | 发型序号,**逗号分隔多选**(如 `1,2,3`)。female / male 均为 1–7 |
|
||||
| beauty_enabled | bool | 否 | 美颜开关(本期不生效) |
|
||||
| use_mask | bool | 否 | 默认 `true`,`false` 跳过遮罩 |
|
||||
| prompt | string | 否 | ComfyUI 提示词 |
|
||||
@@ -135,6 +135,104 @@ async def face_measure_v2(request: Request):
|
||||
|
||||
---
|
||||
|
||||
## 7. ✅【已完成】接口9/10 头部遮罩(`/api/v1/head/mask`、`/api/v1/head/band`)
|
||||
|
||||
`gateway/app.py` 已新增两条盲转发路由(同接口6 的写法):
|
||||
|
||||
```python
|
||||
@app.post("/api/v1/head/mask", tags=["人脸分析"])
|
||||
@app.post("/api/v1/head/band", tags=["人脸分析"])
|
||||
```
|
||||
|
||||
- 入参:图片三选一 + `erode_cm`(接口10 另有 `dilate_cm`)。
|
||||
- 出参:`steps_common.*_base64` 与 `bisenet`/`segformer` 组内的 `*_base64` 字段——现有递归
|
||||
`rewrite_base64_to_url` 已覆盖(嵌套 dict/数组),无需额外改动。
|
||||
- 两个接口响应较慢(双分割模型跑两遍),注意 `request_timeout_seconds`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 🔲【新增】接口11/12 发际线生发/带重绘(`/api/v1/hairline/grow*`)
|
||||
|
||||
worker 侧已上线 4 条路由,**网关尚无对应转发路由**(当前仅测试页直连 worker)。如需对外提供,参考接口9 加法:
|
||||
|
||||
```python
|
||||
@app.post("/api/v1/hairline/grow", tags=["生发"]) # 接口11
|
||||
@app.post("/api/v1/hairline/grow_v2", tags=["生发"]) # 接口12 全参数
|
||||
@app.post("/api/v1/hairline/grow_v2_final", tags=["生发"]) # 接口12 final 精简版
|
||||
@app.post("/api/v1/hairline/grow_v2_final_v2", tags=["生发"])
|
||||
```
|
||||
|
||||
- 入参:图片三选一 + `hairline_id`(接口12 final 两变体仅需这两个)。接口11/12 全参数版还有
|
||||
20+ 个调优 Form 参数,网关盲转发即可,无需逐个声明。
|
||||
- 出参:`data.steps.*_base64`(input/final/redraw_full/redraw_band 等各步图)→ 现有递归改写覆盖。
|
||||
- ⚠️ 依赖 worker 机的 change_hair(:8801) 与 ComfyUI(:8188) 都在跑;单请求 10s+,超时建议 ≥120s。
|
||||
- 契约细节见 [`接口文档.md`](接口文档.md) 接口11/12 章节。
|
||||
|
||||
---
|
||||
|
||||
## 9. ✅【新增】接口99 人脸特殊点(`/api/v1/face/special-points`)— **网关本机实现,不转发 worker**
|
||||
|
||||
**背景**:接口99(固定编号 MediaPipe 关键点 6 组 60 点 + 5 个发际线特殊点,返回像素坐标 JSON)
|
||||
**纯 CPU 可跑**(MediaPipe 本就 CPU;BiSeNet 分割单核实测 <1s)且调用频率低。
|
||||
按约定:**不用 GPU、低频的接口默认网关本机实现**,不占 worker 队列
|
||||
(worker 池 `per_worker_concurrency=1`,转发会排在生发任务后面等)。
|
||||
|
||||
**网关代码已在本仓库 `gateway/app.py` 改好**——与接口4 同款本机实现(显式 Form 参数 +
|
||||
惰性导入 + `run_in_threadpool` + `gw-` request_id),直接 import 同仓库的
|
||||
`face_analysis/special_points.detect_special_points`。**单路排队**:`_if99_lock` 全局互斥,
|
||||
同一时刻只跑一路推理(限制 CPU 峰值 + 规避 MediaPipe 单例线程安全问题),请求 FIFO 排队。
|
||||
|
||||
### 网关机部署前检查
|
||||
|
||||
1. **Python 3.10~3.12**(mediapipe 0.10.14 无 3.13 wheel)。
|
||||
2. **系统库**(无 GUI 服务器跑 opencv/mediapipe 必需,已装可跳过):
|
||||
|
||||
```bash
|
||||
sudo apt install -y libgl1 libglib2.0-0 libegl1
|
||||
```
|
||||
|
||||
3. **安装依赖**(网关 venv,国内镜像):
|
||||
|
||||
```bash
|
||||
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple \
|
||||
mediapipe==0.10.14 opencv-python==4.10.0.84 numpy==1.26.4
|
||||
|
||||
# 可选:BiSeNet 头发分割(发际线 5 点需要)。CPU 版 torch 仅 ~200MB:
|
||||
pip install torch==2.2.2 torchvision==0.17.2 --index-url https://download.pytorch.org/whl/cpu
|
||||
# 不装 torch 也能跑:60 个关键点正常返回,发际线 5 点为 null(hairline_source="unavailable")
|
||||
# ⚠️ 网关无 GPU——务必用上面的 CPU 专用源装 torch;装默认 PyPI 版会带 2.5G 的 CUDA 包,浪费但也能跑(自动回退 CPU)
|
||||
```
|
||||
|
||||
4. **权重已入 git**,`git clone/pull` 自动到位:`face_analysis/weights/79999_iter.pth`(51MB)。
|
||||
无需手动下载任何模型文件。
|
||||
5. **无 GPU 已实测**:`CUDA_VISIBLE_DEVICES=""` 模拟验证通过(70/70 点,与 GPU 结果一致);
|
||||
CPU 推理 16 核 0.18s/次,网关机核少时约 0.5~2s/次,低频可接受。
|
||||
|
||||
### 部署与冒烟
|
||||
|
||||
```bash
|
||||
cd /path/to/hair && git pull
|
||||
sudo systemctl restart hair-gateway # 或网关实际服务名(uvicorn gateway.app:app)
|
||||
|
||||
# 冒烟(multipart 传图;经网关无需 X-Internal-Token)
|
||||
curl -s -X POST http://127.0.0.1:8080/api/v1/face/special-points \
|
||||
-F "image_file=@/tmp/face.jpg" | python3 -m json.tool | head -30
|
||||
# 期望 code=0;data.points 含 eyebrow_107 等 60 个关键点 + hair_line_* 5 点
|
||||
# 缺依赖时返回 code=1007 且 message 提示"网关依赖未安装"
|
||||
```
|
||||
|
||||
### 注意
|
||||
|
||||
- **超时无需调大**:单路 CPU 推理 <1s;即使排队,低频下积压可忽略。排队本身无超时,
|
||||
调用方按需自带客户端超时。
|
||||
- **错误码透传契约**:1001(无人脸)/ 1003(非正面)/ 1007(参数/处理失败/缺依赖)/
|
||||
1008(图片格式/下载失败),HTTP 一律 200。
|
||||
- **worker 侧同路径接口保留**(`app.py`),供测试页 `static/test_interface99.html`
|
||||
直连调试(需 token);生产路径是网关本机实现。
|
||||
- 契约详见 [`接口文档.md`](接口文档.md) 接口99 章节。
|
||||
|
||||
---
|
||||
|
||||
## 已经做好、无需再动的
|
||||
|
||||
- **接口4 在网关本机实现**(调豆包,不转发 worker)——已完成;config 里配 `ark`。
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
# 网关摘除隔离期实施方案(方案 B)
|
||||
|
||||
> 目标读者:网关机器的部署/维护者。本文档给出基于 **main 分支** `gateway/` 代码的
|
||||
> 完整改动说明,可直接照做。**不需要改 worker 侧任何代码。**
|
||||
|
||||
## 1. 背景与事故复盘
|
||||
|
||||
2026-09-19 晚,GPU worker 机器(ubuntu3090_debug_4090 所在主机)磁盘写满,业务接口
|
||||
全部失败,但网关**持续把请求打到该机器近 16 个小时**(21:30 故障发生 → 次日 13:36
|
||||
人工重启),没有切换到其他 worker。复盘结论是三层防线同时失效:
|
||||
|
||||
| 层 | 问题 | 后果 |
|
||||
|---|---|---|
|
||||
| 1. worker `/health` 太浅 | 只返回内存里的"模型就绪"标志,磁盘满/下游 ComfyUI 挂掉不影响它 | 探测一直 200 |
|
||||
| 2. 业务错误不触发摘除 | 下游出错经包装后以 HTTP 200/400 + 错误码返回,`forward.py` 只对 连接异常/超时/≥500/401 摘除 | 请求失败但 worker 被视为健康 |
|
||||
| 3. 摘除后 8 秒即复活(**本方案要修的**) | `mark_worker_unhealthy()` 下线后,下一轮探测(8s 后)`/health` 返回 200,`healthy_threshold=1` 使其**一次成功立即重新上线** | 即使被摘除也会反复横跳,流量持续打入 |
|
||||
|
||||
worker 侧的第 1 层已经修复(方案 A:`/health` 深检磁盘水位 + 下游依赖 TCP 探测,
|
||||
异常返回 503,代码在分支 `ubuntu3090_debug_4090`,提交 `14562d4`)。本方案修复
|
||||
第 3 层:**被动摘除后进入隔离期,隔离期内即使探测成功也不复活**。两层配合后:
|
||||
worker 磁盘满 → `/health` 503 → 网关 2 次探测失败摘除 → 隔离期内不再接流量。
|
||||
|
||||
> 第 2 层(错误码语义化,涉及调用方兼容)暂不处理,单独立项。
|
||||
|
||||
## 2. 现状代码行为(main 分支 gateway/pool.py)
|
||||
|
||||
- `mark_worker_unhealthy(w)`:被 `forward.py` 在转发失败(连接异常/超时/5xx/401)时
|
||||
调用,置 `w.online = False`。**没有任何冷却机制**。
|
||||
- `_health_check_loop(cfg)`:每 `interval_seconds`(默认 8s)探测所有 worker 的
|
||||
`/health`;返回 200 时 `consecutive_successes += 1`,达到 `healthy_threshold`
|
||||
(默认 **1**)且当前 offline → 立即 `online = True`。
|
||||
- 因此被动摘除最多 8 秒后就被一次探测成功拉回——如果 worker 是"浅健康"或故障
|
||||
间歇性表现,就会陷入 摘除→复活→失败→摘除 的横跳。
|
||||
- 另外 58-96 行有一段**从未被调用的死代码** `_check_worker_health()` /
|
||||
`_mark_failure()`(写了一半的旧实现),本次顺带删除,避免后人改错地方。
|
||||
|
||||
## 3. 代码改动(共 2 个文件 + 1 个配置)
|
||||
|
||||
### 3.1 `gateway/pool.py`
|
||||
|
||||
**(1) `WorkerState` 增加一个字段:**
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkerState:
|
||||
"""单个 worker 的运行时状态。"""
|
||||
url: str
|
||||
online: bool = False # 初始 offline,等健康检查通过后上线
|
||||
busy: bool = False
|
||||
consecutive_failures: int = 0
|
||||
consecutive_successes: int = 0
|
||||
offline_until: float = 0.0 # 被动摘除后的隔离截止时刻(time.monotonic() 基准)
|
||||
```
|
||||
|
||||
**(2) 模块顶部(`logger = ...` 之后)加一个配置读取 helper:**
|
||||
|
||||
```python
|
||||
def _cooldown_seconds() -> float:
|
||||
"""被动摘除后的隔离期时长(秒),配置 health_check.cooldown_seconds,默认 60。"""
|
||||
try:
|
||||
from gateway.config import get_config
|
||||
return float(get_config()["health_check"].get("cooldown_seconds", 60))
|
||||
except Exception: # noqa: BLE001
|
||||
return 60.0
|
||||
```
|
||||
|
||||
(函数内 import 是为了不引入模块级循环依赖;`gateway/config.py` 不依赖 pool,顶层
|
||||
import 也可以。)
|
||||
|
||||
**(3) `mark_worker_unhealthy()` 摘除时同时设置隔离期:**
|
||||
|
||||
```python
|
||||
async def mark_worker_unhealthy(w: WorkerState) -> None:
|
||||
"""被动标记:转发失败时立即将该 worker 下线,并进入隔离期。
|
||||
|
||||
隔离期内即使 /health 探测成功也不复活(由 _health_check_loop 守卫),
|
||||
避免"摘除→8 秒复活→再失败"的横跳。
|
||||
"""
|
||||
async with _pool_condition:
|
||||
if w.online:
|
||||
w.online = False
|
||||
w.consecutive_failures += 1
|
||||
w.offline_until = time.monotonic() + _cooldown_seconds()
|
||||
logger.warning("⚠ Worker 被动下线: %s(转发失败,隔离 %.0fs)",
|
||||
w.url, _cooldown_seconds())
|
||||
```
|
||||
|
||||
**(4) `_health_check_loop()` 的探测成功分支加隔离期守卫。** 找到这段:
|
||||
|
||||
```python
|
||||
if resp.status_code == 200:
|
||||
w.consecutive_failures = 0
|
||||
w.consecutive_successes += 1
|
||||
if w.consecutive_successes >= healthy_threshold and not w.online:
|
||||
w.online = True
|
||||
logger.info("✅ Worker 上线: %s", w.url)
|
||||
```
|
||||
|
||||
改为:
|
||||
|
||||
```python
|
||||
if resp.status_code == 200:
|
||||
w.consecutive_failures = 0
|
||||
w.consecutive_successes += 1
|
||||
if w.consecutive_successes >= healthy_threshold and not w.online:
|
||||
if time.monotonic() < w.offline_until:
|
||||
logger.debug("Worker %s 探测成功但处于隔离期,暂不复活", w.url)
|
||||
else:
|
||||
w.online = True
|
||||
logger.info("✅ Worker 上线: %s", w.url)
|
||||
```
|
||||
|
||||
注意:`except`(连接异常)分支只累计失败、不涉及复活,无需改动;
|
||||
`init_pool()` 启动时的首轮探测同理无需改动(进程刚启动时 `offline_until` 为 0,
|
||||
不构成隔离)。
|
||||
|
||||
**(5) 删除死代码**:`_check_worker_health()` 与
|
||||
`_mark_failure()` 两个函数整体删除(约 58-96 行,以函数名为准,别删到
|
||||
`_health_check_loop`)。删除前可确认无调用方:
|
||||
`grep -rn "_check_worker_health\|_mark_failure" .` 应只剩定义处。
|
||||
|
||||
### 3.2 `gateway/config.py`
|
||||
|
||||
`DEFAULTS["health_check"]` 增加一个 key:
|
||||
|
||||
```python
|
||||
"health_check": {
|
||||
"path": "/health",
|
||||
"interval_seconds": 8,
|
||||
"timeout_seconds": 3,
|
||||
"unhealthy_threshold": 2,
|
||||
"healthy_threshold": 1,
|
||||
"cooldown_seconds": 60, # ← 新增:被动摘除后的隔离期(秒)
|
||||
},
|
||||
```
|
||||
|
||||
`config.example.json` 同步加这个 key。网关机器的实际 `config.json` **不加也不会报错**
|
||||
(代码里有 60 的默认兜底),但建议显式加上,便于运维感知。
|
||||
|
||||
### 3.3 建议单测:`tests/test_gateway_pool.py`(新文件)
|
||||
|
||||
gateway 子包目前没有任何测试。隔离期是纯逻辑,建议至少覆盖以下三个用例
|
||||
(不依赖真实网络):
|
||||
|
||||
```python
|
||||
"""gateway/pool.py 隔离期逻辑单测。"""
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import patch
|
||||
|
||||
from gateway import pool
|
||||
from gateway.pool import WorkerState
|
||||
|
||||
|
||||
def _drain(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
def test_passive_ejection_sets_cooldown():
|
||||
w = WorkerState(url="http://127.0.0.1:9000", online=True)
|
||||
async def run():
|
||||
pool._pool_condition = asyncio.Condition()
|
||||
with patch.object(pool, "_cooldown_seconds", return_value=60.0):
|
||||
await pool.mark_worker_unhealthy(w)
|
||||
_drain(run())
|
||||
assert w.online is False
|
||||
assert w.offline_until > time.monotonic()
|
||||
|
||||
|
||||
def test_probe_success_revives_after_cooldown():
|
||||
w = WorkerState(url="http://127.0.0.1:9000") # offline
|
||||
w.offline_until = time.monotonic() - 1 # 隔离期已过
|
||||
# 直接验证状态迁移逻辑(若按 3.1(4) 内联实现,可复制该分支逻辑做断言,
|
||||
# 或将判断抽成 _try_revive(w, healthy_threshold) 小函数后单测)
|
||||
...
|
||||
|
||||
|
||||
def test_probe_success_blocked_during_cooldown():
|
||||
w = WorkerState(url="http://127.0.0.1:9000")
|
||||
w.offline_until = time.monotonic() + 60
|
||||
... # 断言保持 offline
|
||||
```
|
||||
|
||||
> 提示:如果按 3.1(4) 原样内联修改,后两个用例不好直接驱动,可以把"是否允许复活"
|
||||
> 抽成一个 6 行的纯函数 `_try_revive(w, healthy_threshold) -> bool` 再测,主循环
|
||||
> 调用它即可——实现方式自定,覆盖语义即可。
|
||||
|
||||
## 4. 部署步骤(网关机器)
|
||||
|
||||
1. `git pull` main 分支(含本方案代码改动)。
|
||||
2. (可选但建议)`config.json` 的 `health_check` 段加 `"cooldown_seconds": 60`。
|
||||
3. 重启网关服务(`hair-gateway.service` 或等价的 uvicorn 进程)。重启期间网关
|
||||
本身短暂不可用,选低峰执行。
|
||||
4. 观察启动日志:`健康检查循环启动 | 间隔=8s | 下线阈值=2 | 上线阈值=1 | workers=N`
|
||||
正常出现。
|
||||
|
||||
## 5. 验证
|
||||
|
||||
**功能验证(低峰演练):**
|
||||
|
||||
1. 人工把主 worker 摘除一次最直接的方法:临时在 worker 机器
|
||||
`systemctl stop hair-worker`(或临时设 `HEALTH_MIN_FREE_GB=999` 重启)。
|
||||
2. 观察网关日志:
|
||||
- 连续 2 次探测失败 → `⚠ Worker 下线`(原有行为);
|
||||
- **转发失败触发的** `⚠ Worker 被动下线: ...(转发失败,隔离 60s)`(新日志);
|
||||
- 恢复 worker 后,若刚被被动摘除过,即使 `/health` 恢复 200,也应看到 60 秒内
|
||||
**不出现** `✅ Worker 上线`,隔离期满后下一次探测成功才上线。
|
||||
3. `GET /gateway-health` 观察 `workers_healthy` 的变化节奏。
|
||||
|
||||
**回归确认:** 正常场景 worker 上下线不受影响(隔离期只对"被动摘除"生效;
|
||||
探测失败导致的下线,恢复后仍按 `healthy_threshold` 立即上线)。
|
||||
|
||||
## 6. 回滚
|
||||
|
||||
- 代码回滚:`git revert` 对应提交即可,无数据/配置迁移。
|
||||
- 紧急关闭隔离期:网关机器 `config.json` 设 `"cooldown_seconds": 0`
|
||||
(等价于旧行为——摘除后下一次探测成功即复活),无需回代码。
|
||||
|
||||
## 7. 附:worker 侧方案 A 的行为(已上线,供联调参考)
|
||||
|
||||
worker(分支 `ubuntu3090_debug_4090`,提交 `14562d4`)的 `/health` 现在会在以下
|
||||
情况返回 **503**(网关 2 次探测失败即摘除):
|
||||
|
||||
- 模型加载中:`503 {"status":"starting"}`(原有行为不变)
|
||||
- 磁盘剩余低于阈值:`503 {"status":"degraded","reason":"disk_free_below_5.0g","disk_free_gb":...}`
|
||||
- 下游依赖(ComfyUI 8188 / change_hair 8801)TCP 不通:
|
||||
`503 {"status":"degraded","reason":"dep_down:comfyui,...","deps":{...}}`
|
||||
|
||||
正常时返回 `200 {"status":"ok","disk_free_gb":24.6,"deps":{"comfyui":true,"change_hair":true}}`。
|
||||
|
||||
worker 侧配置(`worker_config.json` 的 `health` 段,环境变量可覆盖):
|
||||
`min_free_gb`(默认 5,0=关闭)、`check_deps`(默认 true)、`dep_comfyui`(默认
|
||||
127.0.0.1:8188)、`deps_cache_seconds`(默认 5)。**其他 worker 机器如果也想启用
|
||||
深检,cherry-pick 该提交并补一份 worker_config.json 的 health 段即可。**
|
||||
@@ -202,7 +202,7 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
|
||||
|
||||
# --- 自适应尺寸:字号/线宽/虚线/箭头按短边缩放 ---
|
||||
s = min(w, h)
|
||||
font_size = max(8, round(s * 0.017)) # 字体更小
|
||||
font_size = max(9, round(s * 0.020)) # 字号上调一档
|
||||
line_w = max(1, round(s * 0.0022))
|
||||
dash_len = max(4, round(s * 0.008))
|
||||
gap_len = max(2, round(dash_len * 0.7)) # 虚线更稠密(间隙<划线)
|
||||
@@ -212,6 +212,8 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
|
||||
|
||||
buf = np.zeros((h, w, 4), dtype=np.uint8)
|
||||
|
||||
# 横线:v1 = 头顶/发际线/眉心/鼻翼下缘/下巴尖;v6 = 发际线/眉心/鼻翼下缘/下巴尖。
|
||||
# (发际线贴近头顶时已在 MeasureResult 修正 vertical,此处始终正常画发际线。)
|
||||
if variant == "v6":
|
||||
order = ["hairline", "brow_center", "nose_bottom", "chin_tip"]
|
||||
else:
|
||||
@@ -239,7 +241,7 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
|
||||
face_cx = (fx0 + fx1) / 2
|
||||
over = max(6, round(s * 0.030)) # 线超出包围盒的长度(参考图风格)
|
||||
face_half = (fx1 - fx0) / 2 + over # 横线超出最外侧竖线一点
|
||||
# v6 竖线纵向范围 = 发际线→下巴尖(不超出);v1 = 头顶→下巴尖并两端超出一点
|
||||
# 竖线纵向范围:v6 = 发际线→下巴尖(不超出);v1 = 头顶→下巴尖并两端超出一点
|
||||
v_top = fy0 if variant == "v6" else fy0 - over
|
||||
v_bot = fy1 if variant == "v6" else fy1 + over
|
||||
|
||||
@@ -255,6 +257,18 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
font = _load_font(font_size)
|
||||
|
||||
# --- 2b. 每条横线在「中间线段」(两内眼角之间)中点画原点突出 ---
|
||||
# 注意:原点不在整条线的中点 face_cx,而在被竖线切出的中间段(左内眼角↔右内眼角)
|
||||
# 的正中,即脸的竖直中轴附近、两内眼角连线中点。
|
||||
li_x = pts["left_inner"][0]
|
||||
ri_x = pts["right_inner"][0]
|
||||
dot_cx = (li_x + ri_x) / 2
|
||||
dot_r = max(2, round(s * 0.0045)) # 原点半径,与 arrow_size 同档自适应
|
||||
for cy in ys:
|
||||
x0, y0 = dot_cx - dot_r, cy - dot_r
|
||||
x1, y1 = dot_cx + dot_r, cy + dot_r
|
||||
draw.ellipse((x0, y0, x1, y1), fill=LINE_COLOR)
|
||||
|
||||
# --- 3a. 横线右侧:线名(头顶/发际线/眉心/鼻翼下缘/下巴尖),文字纵向居中对齐到线 ---
|
||||
name_x = fx1 + over + pad # 移到横线右端外侧一点(往右)
|
||||
for i, name in enumerate(order):
|
||||
@@ -265,19 +279,22 @@ def create_annotated_image(image_bgr, measure_result, ear_mask=None, hair_mask=N
|
||||
draw.text((x, ys[i]), text, fill=LINE_COLOR, font=font, anchor="lm")
|
||||
|
||||
# --- 3b. 左侧四庭:名 + 数值两行(无 cm)+ 竖向虚线双箭头 ---
|
||||
# court_start:庭段在 order 里的起始索引。v6 为三庭(无顶庭),其余四庭。
|
||||
if variant == "v6":
|
||||
court_cm = [measure_result.upper_cm, measure_result.middle_cm, measure_result.lower_cm]
|
||||
court_name = ["上庭", "中庭", "下庭"]
|
||||
n_court = 3
|
||||
court_start = 0
|
||||
else:
|
||||
court_cm = [measure_result.top_cm, measure_result.upper_cm,
|
||||
measure_result.middle_cm, measure_result.lower_cm]
|
||||
court_name = ["顶庭", "上庭", "中庭", "下庭"]
|
||||
n_court = 4
|
||||
court_start = 0
|
||||
arrow_x = max(arrow_size + 1, fx0 - pad) # 竖箭头所在 x(脸左侧,贴近最左竖线)
|
||||
court_total = sum(court_cm) or 1.0 # 各庭占比分母 = 四庭(v6 三庭)之和
|
||||
for i in range(n_court):
|
||||
y_a, y_b = ys[i], ys[i + 1]
|
||||
y_a, y_b = ys[court_start + i], ys[court_start + i + 1]
|
||||
# 竖向虚线双箭头,覆盖该庭高度(略收一点避免压到横线)
|
||||
inset = min(arrow_size, (y_b - y_a) * 0.12)
|
||||
draw_dashed_line_with_arrows(
|
||||
|
||||
@@ -1107,7 +1107,7 @@ def generate_hairline_redraw(image_bgr, hairline_id, is_hr=False, seg_model="seg
|
||||
"hairline_id": hairline_id,
|
||||
"blend_method": blend_method,
|
||||
"hairline_push_cm": round(float(hairline_push_cm), 2),
|
||||
"comfyui_prompt": comfyui_prompt or "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜",
|
||||
"comfyui_prompt": comfyui_prompt or "填充遮罩区域的头发,人物增加一点磨皮",
|
||||
"beauty_alpha": beauty_alpha,
|
||||
"px_per_cm": round(float(px_per_cm), 4),
|
||||
"mask_pixels": mask_viz["mask_pixels"],
|
||||
|
||||
@@ -12,7 +12,7 @@ from face_analysis.calibration import (
|
||||
estimate_scale_factor, normalized_to_pixel, pixel_distance, _lm_list,
|
||||
)
|
||||
from face_analysis.face_mesh_landmarks import (
|
||||
GLABELLA_9, GLABELLA_151, NOSE_BOTTOM, CHIN_TIP,
|
||||
GLABELLA_9, NOSE_BOTTOM, CHIN_TIP,
|
||||
LEFT_EYE_OUTER, LEFT_EYE_INNER, RIGHT_EYE_INNER, RIGHT_EYE_OUTER,
|
||||
LEFT_CHEEK, RIGHT_CHEEK, LEFT_POSITION, RIGHT_POSITION,
|
||||
)
|
||||
@@ -24,10 +24,8 @@ _TOP_RATIO = 0.22 / 0.28 # 顶庭 ÷ 中庭(≈ 0.786)
|
||||
|
||||
|
||||
def _brow_center(lm, w, h):
|
||||
"""眉心 = 索引 9 / 151 中点。"""
|
||||
g9 = normalized_to_pixel(lm[GLABELLA_9], w, h)
|
||||
g151 = normalized_to_pixel(lm[GLABELLA_151], w, h)
|
||||
return (g9[0] + g151[0]) / 2, (g9[1] + g151[1]) / 2
|
||||
"""眉心 = 索引 9(眉间上点)。"""
|
||||
return normalized_to_pixel(lm[GLABELLA_9], w, h)
|
||||
|
||||
|
||||
def estimate_vertical_landmarks(landmarks, image_width, image_height):
|
||||
@@ -144,9 +142,24 @@ def measure_seven_eyes(landmarks, image_width, image_height):
|
||||
}
|
||||
|
||||
|
||||
def pt_or_none(vertical, name):
|
||||
"""vertical dict 的点 → {"x","y"},值为 None 时返回 None。"""
|
||||
v = vertical.get(name)
|
||||
if v is None:
|
||||
return None
|
||||
return {"x": int(round(v[0])), "y": int(round(v[1]))}
|
||||
|
||||
|
||||
class MeasureResult:
|
||||
"""测量结果,提供 to_response() 输出与接口文档同构的 data 字段。"""
|
||||
|
||||
# 发际线修正阈值/固定值:发际线离头顶(顶庭)< 此值时判定分割不可靠,需修正发际线。
|
||||
# hairline 与 hair_top 几乎重合(如稀疏头发中轴漏检只剩一小撮)→ 上庭改取
|
||||
# 0.95×中庭反推发际线;若反推后越过头顶,则顶庭固定为 0.7cm(发际线钉在头顶下方
|
||||
# 0.7cm),上庭取眉心→发际线剩余距离。修正后始终返回完整四庭,不再置 null。
|
||||
HAIRLINE_CORRECT_TOP_CM = 0.7
|
||||
UPPER_TO_MIDDLE_RATIO = 0.95 # 贴近头顶时,上庭 = 中庭 × 此比例
|
||||
|
||||
def __init__(self, vertical, eyes, px_per_cm, hairline_source, head_pose,
|
||||
landmarks=None, image_width=None, image_height=None):
|
||||
self.vertical = vertical
|
||||
@@ -159,12 +172,32 @@ class MeasureResult:
|
||||
self.w = image_width
|
||||
self.h = image_height
|
||||
|
||||
# 各庭厘米
|
||||
# 发际线修正:顶庭(头顶→发际线)< 阈值视为发际线贴近头顶、不可靠。
|
||||
# 改写:上庭 = 0.95×中庭 → 由眉心反推发际线 y;若发际线越过头顶
|
||||
# (hairline_y < hair_top_y),顶庭固定为 0.7cm(发际线钉在头顶下方 0.7cm)。
|
||||
# 回写 vertical,使 to_response/标注图/v6 复用全部拿到修正后的发际线。
|
||||
self.detected_top_cm = vertical["top_court_px"] / px_per_cm
|
||||
self.hairline_corrected = self.detected_top_cm < self.HAIRLINE_CORRECT_TOP_CM
|
||||
if self.hairline_corrected:
|
||||
brow_x, brow_y = vertical["brow_center"]
|
||||
hair_top_y = vertical["hair_top"][1]
|
||||
new_upper_px = vertical["middle_court_px"] * self.UPPER_TO_MIDDLE_RATIO
|
||||
hairline_y = brow_y - new_upper_px
|
||||
if hairline_y < hair_top_y: # 反推发际线越过头顶 → 顶庭固定 0.7cm
|
||||
hairline_y = hair_top_y + self.HAIRLINE_CORRECT_TOP_CM * px_per_cm
|
||||
new_upper_px = brow_y - hairline_y
|
||||
vertical["hairline"] = (brow_x, float(hairline_y))
|
||||
vertical["upper_court_px"] = new_upper_px
|
||||
vertical["top_court_px"] = hairline_y - hair_top_y
|
||||
self.hairline_source = "corrected"
|
||||
|
||||
# 各庭厘米(修正后)
|
||||
self.top_cm = vertical["top_court_px"] / px_per_cm
|
||||
self.upper_cm = vertical["upper_court_px"] / px_per_cm
|
||||
self.middle_cm = vertical["middle_court_px"] / px_per_cm
|
||||
self.lower_cm = vertical["lower_court_px"] / px_per_cm
|
||||
self.face_total_cm = self.top_cm + self.upper_cm + self.middle_cm + self.lower_cm
|
||||
self.face_total_cm = (self.top_cm + self.upper_cm
|
||||
+ self.middle_cm + self.lower_cm)
|
||||
|
||||
# 七眼厘米
|
||||
self.eye_width_cm = eyes["eye_width_px"] / px_per_cm
|
||||
@@ -172,14 +205,9 @@ class MeasureResult:
|
||||
self.inter_eye_cm = eyes["inter_eye_distance_px"] / px_per_cm
|
||||
|
||||
def to_response(self):
|
||||
# 四庭完整输出(发际线贴近头顶时已在 __init__ 修正 vertical,无 null 分支)。
|
||||
total_px = (self.vertical["top_court_px"] + self.vertical["upper_court_px"]
|
||||
+ self.vertical["middle_court_px"] + self.vertical["lower_court_px"])
|
||||
fw_px = self.eyes["face_width_px"]
|
||||
|
||||
def pt(name):
|
||||
x, y = self.vertical[name]
|
||||
return {"x": int(round(x)), "y": int(round(y))}
|
||||
|
||||
data = {
|
||||
"face_total_height_cm": round(self.face_total_cm, 2),
|
||||
"four_courts": {
|
||||
@@ -199,16 +227,16 @@ class MeasureResult:
|
||||
"face_width_cm": round(self.face_width_cm, 2),
|
||||
"inter_eye_distance_cm": round(self.inter_eye_cm, 2),
|
||||
"ratios": {
|
||||
"eye_width": round(self.eyes["eye_width_px"] / fw_px, 3),
|
||||
"inter_eye_distance": round(self.eyes["inter_eye_distance_px"] / fw_px, 3),
|
||||
"eye_width": round(self.eyes["eye_width_px"] / self.eyes["face_width_px"], 3),
|
||||
"inter_eye_distance": round(self.eyes["inter_eye_distance_px"] / self.eyes["face_width_px"], 3),
|
||||
},
|
||||
},
|
||||
"landmarks": {
|
||||
"hair_top": pt("hair_top"),
|
||||
"hairline": pt("hairline"),
|
||||
"brow_center": pt("brow_center"),
|
||||
"nose_bottom": pt("nose_bottom"),
|
||||
"chin_tip": pt("chin_tip"),
|
||||
"hair_top": pt_or_none(self.vertical, "hair_top"),
|
||||
"hairline": pt_or_none(self.vertical, "hairline"),
|
||||
"brow_center": pt_or_none(self.vertical, "brow_center"),
|
||||
"nose_bottom": pt_or_none(self.vertical, "nose_bottom"),
|
||||
"chin_tip": pt_or_none(self.vertical, "chin_tip"),
|
||||
},
|
||||
"hairline_source": self.hairline_source,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""接口99:人脸特殊点检测。
|
||||
|
||||
返回 MediaPipe Face Mesh 关键点中一组固定编号的像素坐标(英文组名_点ID 为字段名),
|
||||
外加 5 个发际线特殊点:从指定关键点沿指定方向射线步进,与 BiSeNet 头发分割 mask
|
||||
首次相交处即发际线点(参考接口1 方案B 的发际线定位方式,见 hair_segmenter.py)。
|
||||
|
||||
组与编号(需求方给定):
|
||||
- eyebrow 107 66 105 63 70 336 296 334 293 300
|
||||
- eye 189 222 224 113 226 413 442 444 342 446
|
||||
- mouth 0 37 40 67 91 84 17 405 375 409 269
|
||||
- nose_midline 9 168 197 5 4 194 278 48 437 217
|
||||
- cheek 101 117 123 187 205 50 330 346 352 280 425
|
||||
- face_edge 162 234 58 136 149 152 378 365 288 401 366 389 251
|
||||
|
||||
发际线点(字段名需求方给定;A/B 两射线时取中点,仅一条命中则返回该点,均未命中为 null):
|
||||
- hair_line_center 151 → 10 方向与发际线交点
|
||||
- hair_line_right mid(108→109 交点A, 69→67 交点B)
|
||||
- hair_line_right_right mid(104→103 交点A, 68→54 交点B)
|
||||
- hair_line_left mid(337→338 交点A, 299→297 交点B)
|
||||
- hair_line_left_left mid(333→332 交点A, 298→284 交点B) # 与 right_right 镜像对称
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
# 固定关键点组:组英文名 → MediaPipe 点 ID 列表(顺序即需求方给定顺序)
|
||||
GROUPS = {
|
||||
"eyebrow": [107, 66, 105, 63, 70, 336, 296, 334, 293, 300],
|
||||
"eye": [189, 222, 224, 113, 226, 413, 442, 444, 342, 446],
|
||||
"mouth": [0, 37, 40, 67, 91, 84, 17, 405, 375, 409, 269],
|
||||
"nose_midline": [9, 168, 197, 5, 4, 194, 278, 48, 437, 217],
|
||||
"cheek": [101, 117, 123, 187, 205, 50, 330, 346, 352, 280, 425],
|
||||
"face_edge": [162, 234, 58, 136, 149, 152, 378, 365, 288, 401, 366, 389, 251],
|
||||
}
|
||||
|
||||
# 发际线点定义:字段名 → 参与计算的 (起点ID, 方向点ID) 射线组;单射线直接取交点,
|
||||
# 双射线取两交点中点。
|
||||
HAIRLINE_RAYS = {
|
||||
"hair_line_center": [(151, 10)],
|
||||
"hair_line_right": [(108, 109), (69, 67)],
|
||||
"hair_line_right_right": [(104, 103), (68, 54)],
|
||||
"hair_line_left": [(337, 338), (299, 297)],
|
||||
"hair_line_left_left": [(333, 332), (298, 284)],
|
||||
}
|
||||
|
||||
|
||||
class NoFaceError(Exception):
|
||||
"""未检出人脸。"""
|
||||
|
||||
|
||||
class NonFrontalError(Exception):
|
||||
"""非正面照(复用接口1 姿态阈值)。"""
|
||||
|
||||
|
||||
def ray_hairline_intersection(p1, p2, hair_mask):
|
||||
"""从 p1 沿 p1→p2 方向逐像素步进,返回首次进入头发 mask 的整数像素坐标。
|
||||
|
||||
p1/p2: (x, y) 像素坐标(float)。起点本身已在头发内时直接返回起点(已到发际线)。
|
||||
步进直到出图或步数上限(3×图对角线,防极端死循环);未命中返回 None。
|
||||
"""
|
||||
mask = np.asarray(hair_mask).astype(bool)
|
||||
if mask.size == 0:
|
||||
return None
|
||||
h, w = mask.shape
|
||||
x0, y0 = float(p1[0]), float(p1[1])
|
||||
dx, dy = float(p2[0]) - x0, float(p2[1]) - y0
|
||||
length = math.hypot(dx, dy)
|
||||
if length < 1e-6:
|
||||
return None
|
||||
ux, uy = dx / length, dy / length
|
||||
max_steps = int(3 * math.hypot(h, w))
|
||||
|
||||
def _hit(x, y):
|
||||
xi, yi = int(round(x)), int(round(y))
|
||||
if 0 <= xi < w and 0 <= yi < h:
|
||||
return mask[yi, xi]
|
||||
return False
|
||||
|
||||
x, y = x0, y0
|
||||
for _ in range(max_steps):
|
||||
if _hit(x, y):
|
||||
return int(round(x)), int(round(y))
|
||||
x += ux
|
||||
y += uy
|
||||
if not (0 <= int(round(x)) < w and 0 <= int(round(y)) < h):
|
||||
return None # 已步出图像,方向上无头发
|
||||
return None
|
||||
|
||||
|
||||
def detect_special_points(image_bgr):
|
||||
"""主入口:图片 → {字段名: {"x","y"} 或 None} + 元信息。
|
||||
|
||||
Returns: {"points": {...}, "image_size": {"width","height"},
|
||||
"hairline_source": "segmentation"|"unavailable"}
|
||||
无人脸抛 NoFaceError;非正面抛 NonFrontalError。
|
||||
"""
|
||||
from face_analysis.detector import detector
|
||||
from face_analysis.calibration import normalized_to_pixel
|
||||
from face_analysis.pose import check_frontal_face
|
||||
|
||||
h, w = image_bgr.shape[:2]
|
||||
landmarks = detector.detect(image_bgr)
|
||||
if landmarks is None:
|
||||
raise NoFaceError("未检出人脸")
|
||||
if not check_frontal_face(landmarks, w, h):
|
||||
raise NonFrontalError("非正面照")
|
||||
|
||||
lm = landmarks.landmark
|
||||
px = {i: normalized_to_pixel(lm[i], w, h) for i in range(len(lm))}
|
||||
|
||||
points = {}
|
||||
for group, ids in GROUPS.items():
|
||||
for idx in ids:
|
||||
x, y = px[idx]
|
||||
points[f"{group}_{idx}"] = {"x": int(round(x)), "y": int(round(y))}
|
||||
|
||||
# 头发分割(与接口1 相同:按人脸框裁剪后再分割,脸外背景不干扰)
|
||||
hair_mask = None
|
||||
try:
|
||||
from face_analysis.hair_segmenter import get_segmenter
|
||||
face_box = (min(p[0] for p in px.values()), min(p[1] for p in px.values()),
|
||||
max(p[0] for p in px.values()), max(p[1] for p in px.values()))
|
||||
hair_mask, _ = get_segmenter().segment_hair_and_ears(
|
||||
image_bgr, face_box=face_box)
|
||||
except Exception: # noqa: BLE001 分割不可用 → 发际线点置 null,不阻塞关键点
|
||||
hair_mask = None
|
||||
|
||||
for name, rays in HAIRLINE_RAYS.items():
|
||||
hits = []
|
||||
if hair_mask is not None:
|
||||
for a, b in rays:
|
||||
hits.append(ray_hairline_intersection(px[a], px[b], hair_mask))
|
||||
found = [p for p in hits if p is not None]
|
||||
if not found:
|
||||
points[name] = None
|
||||
elif len(found) == 1:
|
||||
points[name] = {"x": found[0][0], "y": found[0][1]}
|
||||
else:
|
||||
points[name] = {
|
||||
"x": int(round(sum(p[0] for p in found) / len(found))),
|
||||
"y": int(round(sum(p[1] for p in found) / len(found))),
|
||||
}
|
||||
|
||||
return {
|
||||
"points": points,
|
||||
"image_size": {"width": w, "height": h},
|
||||
"hairline_source": "segmentation" if hair_mask is not None else "unavailable",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
import cv2
|
||||
import json
|
||||
|
||||
path = sys.argv[1] if len(sys.argv) > 1 else "tests/fixtures/frontal.jpg"
|
||||
img = cv2.imread(path)
|
||||
if img is None:
|
||||
print(f"无法读取图片: {path}")
|
||||
sys.exit(1)
|
||||
try:
|
||||
out = detect_special_points(img)
|
||||
except (NoFaceError, NonFrontalError) as e:
|
||||
print(f"检测失败: {e}")
|
||||
sys.exit(1)
|
||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
||||
@@ -1,339 +0,0 @@
|
||||
INFO: Started server process [26440]
|
||||
INFO: Waiting for application startup.
|
||||
2026-07-01 23:35:15 [INFO] gateway.config: 配置加载完成 | workers=['http://127.0.0.1:8187'] | public_base_url=http://127.0.0.1:8080 | hc_interval=8s | dispatch_timeout=600s | queue_wait=30s
|
||||
2026-07-01 23:35:15 [INFO] gateway: 网关启动中... workers=['http://127.0.0.1:8187']
|
||||
2026-07-01 23:35:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:35:16 [INFO] gateway.pool: Worker 池初始化完成 | 总数=1 | 在线=1
|
||||
2026-07-01 23:35:16 [INFO] gateway: 标注图目录: /home/ubuntu/hair/static/annotations
|
||||
2026-07-01 23:35:16 [INFO] gateway.pool: 健康检查循环启动 | 间隔=8s | 下线阈值=2 | 上线阈值=1 | workers=1
|
||||
2026-07-01 23:35:16 [INFO] gateway: 清理任务启动 | 间隔=60min | 保留=24h | 目录=/home/ubuntu/hair/static/annotations
|
||||
INFO: Application startup complete.
|
||||
INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
|
||||
2026-07-01 23:35:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 127.0.0.1:35872 - "GET /gateway-health HTTP/1.1" 200 OK
|
||||
2026-07-01 23:35:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:35:27 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/face/measure "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:35:27 [INFO] gateway.forward: base64→URL: annotated_image_base64 → http://127.0.0.1:8080/static/annotations/422b7786adc4486989d7f8770df40693.png (21864 bytes)
|
||||
INFO: 127.0.0.1:57220 - "POST /api/v1/face/measure HTTP/1.1" 200 OK
|
||||
2026-07-01 23:35:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 127.0.0.1:57232 - "GET /static/annotations/422b7786adc4486989d7f8770df40693.png HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:57240 - "GET /gateway-health HTTP/1.1" 200 OK
|
||||
2026-07-01 23:35:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:35:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:35:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:36:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:37:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:38:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:39:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:40:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:41:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:42:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:43:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:44:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:45:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:46:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:47:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:48:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:49:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:50:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:51:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:52:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 127.0.0.1:44470 - "GET /gateway-health HTTP/1.1" 200 OK
|
||||
2026-07-01 23:52:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:52:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:52:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:52:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:52:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:52:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:53:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 111.192.98.24:6017 - "GET / HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:6017 - "GET /favicon.ico HTTP/1.1" 404 Not Found
|
||||
2026-07-01 23:53:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:54:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 127.0.0.1:39090 - "GET /docs HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:39092 - "GET / HTTP/1.1" 200 OK
|
||||
2026-07-01 23:55:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:55:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 127.0.0.1:56172 - "GET /static/test_interface1.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56174 - "GET /static/test_interface1.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56184 - "GET /static/test_interface2.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56196 - "GET /static/test_interface2.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56202 - "GET /static/test_interface3.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56206 - "GET /static/test_interface3.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56212 - "GET /static/test_interface4.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56214 - "GET /static/test_interface4.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56218 - "GET /static/test_interface5.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56230 - "GET /static/test_interface5.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56242 - "GET /static/test_interface6.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56256 - "GET /static/test_interface6.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56272 - "GET /static/test_interface7.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56278 - "GET /static/test_interface7.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56282 - "GET /static/integration.html HTTP/1.1" 200 OK
|
||||
INFO: 127.0.0.1:56284 - "GET /static/integration.html HTTP/1.1" 200 OK
|
||||
2026-07-01 23:55:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:55:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:55:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:55:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:55:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:55:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 111.192.98.24:6434 - "GET /static/test_interface1.html HTTP/1.1" 200 OK
|
||||
2026-07-01 23:56:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:08 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/face/measure "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:08 [INFO] gateway.forward: base64→URL: annotated_image_base64 → http://127.0.0.1:8080/static/annotations/8a70c12c19ef4868af555ef84eaeafae.png (35965 bytes)
|
||||
INFO: 111.192.98.24:6435 - "POST /api/v1/face/measure HTTP/1.1" 200 OK
|
||||
2026-07-01 23:56:12 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:20 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:28 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:36 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:44 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:56:52 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:00 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:08 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:16 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:24 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:32 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:40 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:48 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:57:56 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:04 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: Shutting down
|
||||
INFO: Waiting for application shutdown.
|
||||
2026-07-01 23:58:08 [INFO] gateway: 网关关闭中...
|
||||
2026-07-01 23:58:08 [INFO] gateway: 清理任务已停止
|
||||
2026-07-01 23:58:08 [INFO] gateway.pool: 健康检查循环已停止
|
||||
2026-07-01 23:58:08 [INFO] gateway.pool: Worker 池已关闭
|
||||
2026-07-01 23:58:08 [INFO] gateway: 网关已关闭
|
||||
INFO: Application shutdown complete.
|
||||
INFO: Finished server process [26440]
|
||||
INFO: Started server process [31898]
|
||||
INFO: Waiting for application startup.
|
||||
2026-07-01 23:58:10 [INFO] gateway.config: 配置加载完成 | workers=['http://127.0.0.1:8187'] | public_base_url=http://117.50.213.111:8080 | hc_interval=8s | dispatch_timeout=600s | queue_wait=30s
|
||||
2026-07-01 23:58:10 [INFO] gateway: 网关启动中... workers=['http://127.0.0.1:8187']
|
||||
2026-07-01 23:58:10 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:10 [INFO] gateway.pool: Worker 池初始化完成 | 总数=1 | 在线=1
|
||||
2026-07-01 23:58:10 [INFO] gateway: 标注图目录: /home/ubuntu/hair/static/annotations
|
||||
2026-07-01 23:58:10 [INFO] gateway.pool: 健康检查循环启动 | 间隔=8s | 下线阈值=2 | 上线阈值=1 | workers=1
|
||||
2026-07-01 23:58:10 [INFO] gateway: 清理任务启动 | 间隔=60min | 保留=24h | 目录=/home/ubuntu/hair/static/annotations
|
||||
INFO: Application startup complete.
|
||||
INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
|
||||
2026-07-01 23:58:10 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 127.0.0.1:33732 - "GET /gateway-health HTTP/1.1" 200 OK
|
||||
2026-07-01 23:58:18 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:26 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:28 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/face/measure "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:28 [INFO] gateway.forward: base64→URL: annotated_image_base64 → http://117.50.213.111:8080/static/annotations/478efab4566a46c3af0065ad0ffafb67.png (21864 bytes)
|
||||
INFO: 127.0.0.1:32982 - "POST /api/v1/face/measure HTTP/1.1" 200 OK
|
||||
INFO: 117.50.213.111:57344 - "GET /static/annotations/478efab4566a46c3af0065ad0ffafb67.png HTTP/1.1" 200 OK
|
||||
2026-07-01 23:58:34 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:42 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:50 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:54 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/face/measure "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:58:54 [INFO] gateway.forward: base64→URL: annotated_image_base64 → http://117.50.213.111:8080/static/annotations/88d5eec74def44fdad5dd6f7b22e7be4.png (35965 bytes)
|
||||
INFO: 111.192.98.24:7030 - "POST /api/v1/face/measure HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:7030 - "GET /static/annotations/88d5eec74def44fdad5dd6f7b22e7be4.png HTTP/1.1" 200 OK
|
||||
2026-07-01 23:58:58 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 111.192.98.24:7031 - "GET /static/test_interface2.html HTTP/1.1" 200 OK
|
||||
2026-07-01 23:59:06 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:14 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:22 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:27 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/hair/grow "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:27 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/8f770fef8bc14827b419698c90ebd6fa.jpg (105970 bytes)
|
||||
2026-07-01 23:59:27 [INFO] gateway.forward: base64→URL: grown_image_base64 → http://117.50.213.111:8080/static/annotations/6f592882d9c84c1b916ac327f4e0b2af.jpg (113320 bytes)
|
||||
INFO: 111.192.98.24:7062 - "POST /api/v1/hair/grow HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:7062 - "GET /static/annotations/8f770fef8bc14827b419698c90ebd6fa.jpg HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:7166 - "GET /static/annotations/6f592882d9c84c1b916ac327f4e0b2af.jpg HTTP/1.1" 200 OK
|
||||
2026-07-01 23:59:30 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:38 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:46 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:48 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/hair/grow "HTTP/1.1 200 OK"
|
||||
2026-07-01 23:59:48 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/ed790d4888f742caa6625b3cf4704a77.jpg (105641 bytes)
|
||||
2026-07-01 23:59:48 [INFO] gateway.forward: base64→URL: grown_image_base64 → http://117.50.213.111:8080/static/annotations/e4aed9d67e864d31909b30a58e08c16e.jpg (111495 bytes)
|
||||
INFO: 111.192.98.24:5164 - "POST /api/v1/hair/grow HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5164 - "GET /static/annotations/ed790d4888f742caa6625b3cf4704a77.jpg HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5188 - "GET /static/annotations/e4aed9d67e864d31909b30a58e08c16e.jpg HTTP/1.1" 200 OK
|
||||
2026-07-01 23:59:54 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 111.192.98.24:5213 - "GET /static/test_interface3.html HTTP/1.1" 200 OK
|
||||
2026-07-02 00:00:02 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:00:10 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:00:16 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/hair/grow-b "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:00:16 [INFO] gateway.forward: base64→URL: hair_growth_image_base64 → http://117.50.213.111:8080/static/annotations/0891a4b9375e4f58814502e893b12bf6.jpg (152092 bytes)
|
||||
INFO: 111.192.98.24:5212 - "POST /api/v1/hair/grow-b HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5212 - "GET /static/annotations/0891a4b9375e4f58814502e893b12bf6.jpg HTTP/1.1" 200 OK
|
||||
2026-07-02 00:00:18 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 111.192.98.24:5332 - "GET /static/test_interface4.html HTTP/1.1" 200 OK
|
||||
2026-07-02 00:00:26 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:00:34 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:00:39 [ERROR] gateway: 接口4 豆包调用失败
|
||||
Traceback (most recent call last):
|
||||
File "/home/ubuntu/hair/gateway/app.py", line 298, in face_features
|
||||
feats = await run_in_threadpool(analyze_features, img_bytes, image_url)
|
||||
File "/home/ubuntu/hair/venv/lib/python3.10/site-packages/starlette/concurrency.py", line 37, in run_in_threadpool
|
||||
return await anyio.to_thread.run_sync(func)
|
||||
File "/home/ubuntu/hair/venv/lib/python3.10/site-packages/anyio/to_thread.py", line 63, in run_sync
|
||||
return await get_async_backend().run_sync_in_worker_thread(
|
||||
File "/home/ubuntu/hair/venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 2596, in run_sync_in_worker_thread
|
||||
return await future
|
||||
File "/home/ubuntu/hair/venv/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 1029, in run
|
||||
result = context.run(func, *args)
|
||||
File "/home/ubuntu/hair/face_features.py", line 98, in analyze_features
|
||||
resp = get_client().chat.completions.create(
|
||||
File "/home/ubuntu/hair/face_features.py", line 65, in get_client
|
||||
from volcenginesdkarkruntime import Ark
|
||||
ModuleNotFoundError: No module named 'volcenginesdkarkruntime'
|
||||
INFO: 111.192.98.24:5331 - "POST /api/v1/face/features HTTP/1.1" 200 OK
|
||||
2026-07-02 00:00:42 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: 111.192.98.24:5436 - "GET /static/test_interface5.html HTTP/1.1" 200 OK
|
||||
2026-07-02 00:00:50 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:00:58 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:00 [INFO] httpx: HTTP Request: POST http://127.0.0.1:8187/api/v1/hairline/generate "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:00 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/4516a9491a1c41f4af048020f6709870.jpg (105674 bytes)
|
||||
2026-07-02 00:01:00 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/ad51e082bb5540ea843259cdc1e76e6b.jpg (105970 bytes)
|
||||
2026-07-02 00:01:00 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/12a6f7745c9c461ca963f4d49c5267ef.jpg (105735 bytes)
|
||||
2026-07-02 00:01:00 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/316d8352062848e4b28337ef233d820e.jpg (105641 bytes)
|
||||
2026-07-02 00:01:00 [INFO] gateway.forward: base64→URL: image_base64 → http://117.50.213.111:8080/static/annotations/2ae45e3579b0419ab8bff5e3129ab26e.jpg (105705 bytes)
|
||||
INFO: 111.192.98.24:5435 - "POST /api/v1/hairline/generate HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5435 - "GET /static/annotations/4516a9491a1c41f4af048020f6709870.jpg HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5466 - "GET /static/annotations/ad51e082bb5540ea843259cdc1e76e6b.jpg HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5467 - "GET /static/annotations/12a6f7745c9c461ca963f4d49c5267ef.jpg HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5469 - "GET /static/annotations/316d8352062848e4b28337ef233d820e.jpg HTTP/1.1" 200 OK
|
||||
INFO: 111.192.98.24:5471 - "GET /static/annotations/2ae45e3579b0419ab8bff5e3129ab26e.jpg HTTP/1.1" 200 OK
|
||||
2026-07-02 00:01:06 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:14 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:22 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:30 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:38 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:46 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:01:54 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:02 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:10 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:18 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:26 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:34 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:42 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:50 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
2026-07-02 00:02:58 [INFO] httpx: HTTP Request: GET http://127.0.0.1:8187/health "HTTP/1.1 200 OK"
|
||||
INFO: Shutting down
|
||||
INFO: Waiting for application shutdown.
|
||||
2026-07-02 00:02:59 [INFO] gateway: 网关关闭中...
|
||||
2026-07-02 00:02:59 [INFO] gateway: 清理任务已停止
|
||||
2026-07-02 00:02:59 [INFO] gateway.pool: 健康检查循环已停止
|
||||
2026-07-02 00:02:59 [INFO] gateway.pool: Worker 池已关闭
|
||||
2026-07-02 00:02:59 [INFO] gateway: 网关已关闭
|
||||
INFO: Application shutdown complete.
|
||||
INFO: Finished server process [31898]
|
||||
@@ -607,3 +607,79 @@ async def head_mask(request: Request):
|
||||
async def head_band(request: Request):
|
||||
"""接口10:头部外缘膨胀带遮罩 + 分步可视化"""
|
||||
return await _proxy(request, "/api/v1/head/band")
|
||||
|
||||
|
||||
# 接口99 单路排队:网关机推理全局互斥。调用频率低,无需并发——串行既限制 CPU 峰值
|
||||
# (MediaPipe + BiSeNet 全 CPU 推理),也规避检测器单例的线程安全风险。排队无超时,
|
||||
# 请求方按需自带客户端超时。
|
||||
_if99_lock = asyncio.Lock()
|
||||
|
||||
|
||||
@app.post("/api/v1/face/special-points", tags=["人脸分析"])
|
||||
async def face_special_points(
|
||||
image_file: Optional[UploadFile] = File(default=None, description="上传图片文件(JPG/PNG)"),
|
||||
image_url: Optional[str] = Form(default=None, description="图片 URL"),
|
||||
image_base64: Optional[str] = Form(default=None, description="图片 base64(需带前缀)"),
|
||||
):
|
||||
"""接口99:人脸特殊点检测 — 网关本机实现(纯 CPU:MediaPipe + BiSeNet CPU),不经过 worker。
|
||||
|
||||
与 worker 同仓库,直接 import face_analysis.special_points;权重已入 git,clone 即用。
|
||||
依赖惰性导入:网关缺依赖时仅本接口报 1007,不影响其他路由。
|
||||
"""
|
||||
import uuid as _uuid
|
||||
rid = f"gw-{_uuid.uuid4().hex[:8]}"
|
||||
|
||||
def _err(code, message):
|
||||
return JSONResponse(status_code=200, content={
|
||||
"code": code, "message": message, "request_id": rid, "data": None})
|
||||
|
||||
# 三选一校验
|
||||
provided = [x for x in (image_file, image_url, image_base64) if x]
|
||||
if len(provided) != 1:
|
||||
return _err(1007, "图片参数错误:必须且只能传 image_file / image_url / image_base64 其中一个")
|
||||
|
||||
img_bytes = None
|
||||
if image_file:
|
||||
img_bytes = await image_file.read()
|
||||
elif image_base64:
|
||||
b64 = image_base64.split(",", 1)[1] if "," in image_base64 else image_base64
|
||||
try:
|
||||
img_bytes = base64.b64decode(b64)
|
||||
except Exception:
|
||||
return _err(1008, "图片格式不支持(base64 解码失败)")
|
||||
else:
|
||||
try:
|
||||
import httpx
|
||||
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as cli:
|
||||
r = await cli.get(image_url)
|
||||
r.raise_for_status()
|
||||
img_bytes = r.content
|
||||
except Exception:
|
||||
return _err(1008, "图片下载失败(URL 不可达)")
|
||||
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np # noqa: F401 (detect_special_points 依赖)
|
||||
from face_analysis.special_points import (
|
||||
detect_special_points, NoFaceError, NonFrontalError)
|
||||
except ImportError as ex:
|
||||
return _err(1007, f"网关依赖未安装(安装清单见 docs/网关待改动.md §9):{ex}")
|
||||
|
||||
image = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
if image is None:
|
||||
return _err(1008, "图片格式不支持(仅 JPG / PNG)")
|
||||
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
try:
|
||||
async with _if99_lock: # 单路排队:同一时刻只跑一路推理
|
||||
data = await run_in_threadpool(detect_special_points, image)
|
||||
except NoFaceError:
|
||||
return _err(1001, "无法识别人像")
|
||||
except NonFrontalError:
|
||||
return _err(1003, "角度问题,请上传正面照")
|
||||
except Exception as ex: # noqa: BLE001
|
||||
logger.exception("接口99 处理异常")
|
||||
return _err(1007, f"处理失败:{ex}")
|
||||
|
||||
return JSONResponse(status_code=200, content={
|
||||
"code": 0, "message": "success", "request_id": rid, "data": data})
|
||||
|
||||
@@ -170,10 +170,10 @@
|
||||
},
|
||||
"16": {
|
||||
"inputs": {
|
||||
"unet_name": "flux2.0/flux-2-klein-9b-fp8.safetensors",
|
||||
"unet_name": "flux-2-klein-9b-Q4_K_M.gguf",
|
||||
"weight_dtype": "fp8_e4m3fn"
|
||||
},
|
||||
"class_type": "UNETLoader",
|
||||
"class_type": "UnetLoaderGGUF",
|
||||
"_meta": {
|
||||
"title": "UNet加载器"
|
||||
}
|
||||
@@ -410,7 +410,7 @@
|
||||
},
|
||||
"60": {
|
||||
"inputs": {
|
||||
"text": "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜"
|
||||
"text": "填充遮罩区域的头发,人物增加一点磨皮"
|
||||
},
|
||||
"class_type": "JjkText",
|
||||
"_meta": {
|
||||
|
||||
@@ -30,6 +30,19 @@ _REPO = os.path.dirname(os.path.dirname(__file__))
|
||||
_INPUT_NODE = "26" # LoadImage:外部输入图(含 alpha 遮罩)
|
||||
_SEED_NODE = "6" # RandomNoise
|
||||
_PROMPT_NODE = "60" # JjkText:提示词
|
||||
_UNET_NODE = "16" # UNETLoader / UnetLoaderGGUF:Flux 模型加载
|
||||
_CLIP_NODE = "61" # CLIPLoader:qwen 文本编码器
|
||||
|
||||
# Flux 模型 → 配套文本编码器映射。切换 unet 时自动同步编码器,避免维度不匹配。
|
||||
# 规则:4b 系列配 qwen_3_4b,9b 系列(fp8/GGUF)配 qwen_3_8b_fp8mixed。
|
||||
def _clip_for_unet(unet_name: str) -> str | None:
|
||||
"""根据 unet 文件名推断配套的文本编码器文件名;无法推断返回 None。"""
|
||||
low = unet_name.lower()
|
||||
if "4b" in low and "9b" not in low:
|
||||
return "qwen_3_4b.safetensors"
|
||||
if "9b" in low:
|
||||
return "qwen_3_8b_fp8mixed.safetensors"
|
||||
return None
|
||||
|
||||
_wf_cache: dict[str, dict] = {} # path → workflow JSON
|
||||
_wf_output_node: dict[str, str] = {} # path → SaveImage 节点 ID
|
||||
@@ -86,13 +99,18 @@ def _get_output_node(workflow_path: str | None = None) -> str:
|
||||
|
||||
|
||||
def run(rgba_png_bytes: bytes, timeout: float = COMFY_TIMEOUT, prompt: str = None,
|
||||
workflow_path: str | None = None, front: bool = False) -> bytes:
|
||||
workflow_path: str | None = None, front: bool = False,
|
||||
unet_name: str | None = None) -> bytes:
|
||||
"""提交一次生发任务,返回输出 PNG 字节。失败抛异常。
|
||||
|
||||
prompt:非 None 时替换工作流节点60(JjkText)的文本;None 时用工作流内置默认提示词。
|
||||
workflow_path:工作流 JSON 路径,None 则用默认 add_hair.json。
|
||||
front:True 时任务插到 ComfyUI 队列最前(server 端 "front" 字段,队列号取负)。
|
||||
接口2 对时延敏感用 True,避免排在接口3/5 的批量任务后面;其余接口保持 False。
|
||||
unet_name:非 None 时改写工作流里的模型加载节点(节点16),动态切换 Flux 模型。
|
||||
.safetensors → 保持 UNETLoader 节点类型不变,只替换 unet_name;
|
||||
.gguf → 自动把节点类型改成 UnetLoaderGGUF(需装 ComfyUI-GGUF 插件)。
|
||||
None 时用工作流内置默认模型。
|
||||
"""
|
||||
path = workflow_path or _WORKFLOW_DEFAULT
|
||||
output_node = _get_output_node(path)
|
||||
@@ -120,6 +138,21 @@ def run(rgba_png_bytes: bytes, timeout: float = COMFY_TIMEOUT, prompt: str = Non
|
||||
wf[_SEED_NODE]["inputs"]["noise_seed"] = random.randint(0, 2**63 - 1)
|
||||
if prompt is not None:
|
||||
wf[_PROMPT_NODE]["inputs"]["text"] = prompt
|
||||
if unet_name is not None:
|
||||
node = wf.get(_UNET_NODE)
|
||||
if node is not None:
|
||||
# .gguf 需切换到 ComfyUI-GGUF 插件的 UnetLoaderGGUF 节点;
|
||||
# .safetensors/.ckpt 保持原 UNETLoader 节点类型不变
|
||||
if unet_name.lower().endswith(".gguf"):
|
||||
node["class_type"] = "UnetLoaderGGUF"
|
||||
else:
|
||||
node["class_type"] = "UNETLoader"
|
||||
node["inputs"]["unet_name"] = unet_name
|
||||
# 同步切换配套文本编码器(4b→qwen_3_4b, 9b→qwen_3_8b),避免维度不匹配
|
||||
clip_node = wf.get(_CLIP_NODE)
|
||||
clip_name = _clip_for_unet(unet_name)
|
||||
if clip_node is not None and clip_name is not None:
|
||||
clip_node["inputs"]["clip_name"] = clip_name
|
||||
|
||||
# 诊断:落盘实际提交的工作流 + 输入图,便于和手动 ComfyUI 跑的对比
|
||||
try:
|
||||
|
||||
@@ -16,7 +16,7 @@ from . import comfyui
|
||||
|
||||
logger = logging.getLogger("hair.worker")
|
||||
|
||||
_DEFAULT_PROMPT = "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜"
|
||||
_DEFAULT_PROMPT = "填充遮罩区域的头发,人物增加一点磨皮"
|
||||
_REPO = os.path.dirname(os.path.dirname(__file__))
|
||||
_REPAINT_WORKFLOW = os.path.join(_REPO, "0716add-hair-api.json")
|
||||
|
||||
@@ -56,15 +56,16 @@ def _process_mask_to_rgba(image_bytes: bytes, mask_bytes: bytes) -> bytes:
|
||||
|
||||
def run_redraw(image_bytes: bytes, mask_bytes: bytes,
|
||||
prompt: str | None = None, timeout: float = 300.0,
|
||||
front: bool = False) -> bytes:
|
||||
front: bool = False, unet_name: str | None = None) -> bytes:
|
||||
"""直接调 ComfyUI 重绘 — 替代 local_test /api/generate。
|
||||
|
||||
Args:
|
||||
image_bytes: 人物图片字节(JPG/PNG)
|
||||
mask_bytes: 遮罩图片字节(支持红/白/alpha 遮罩格式)
|
||||
prompt: 提示词,None 用默认 "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜"
|
||||
prompt: 提示词,None 用默认 "填充遮罩区域的头发,人物增加一点磨皮"
|
||||
timeout: ComfyUI 超时秒数
|
||||
front: True 时任务插到 ComfyUI 队列最前(接口2 时延敏感路径用)
|
||||
unet_name: 非 None 时切换 Flux 模型(如 flux-2-klein-9b-Q5_K_M.gguf),None 用工作流默认
|
||||
|
||||
Returns:
|
||||
重绘后的 PNG 图片字节
|
||||
@@ -75,4 +76,5 @@ def run_redraw(image_bytes: bytes, mask_bytes: bytes,
|
||||
"""
|
||||
rgba_png = _process_mask_to_rgba(image_bytes, mask_bytes)
|
||||
return comfyui.run(rgba_png, timeout=timeout, prompt=prompt,
|
||||
workflow_path=_REPAINT_WORKFLOW, front=front)
|
||||
workflow_path=_REPAINT_WORKFLOW, front=front,
|
||||
unet_name=unet_name)
|
||||
|
||||
@@ -29,7 +29,8 @@ import logging
|
||||
logger = logging.getLogger("hair.worker")
|
||||
|
||||
# 接口2 女性发型 key → change_hair hair_id(chang_*)映射:换发型+Flux-2 整帧重绘用。
|
||||
# 与接口12 final 的 5 型一一对应。
|
||||
# 与接口12 final 的 5 型一一对应。female 6/7(bigflower/clasicalflower)无对应 LoRA,
|
||||
# 走与男性一致的原生生发(ComfyUI add_hair)管线,故不在本表。
|
||||
_FEMALE_KEY_TO_CHANG = {
|
||||
"ellipse": "chang_tuoyuan", # 椭圆
|
||||
"flower": "chang_huaban", # 花瓣
|
||||
@@ -38,6 +39,17 @@ _FEMALE_KEY_TO_CHANG = {
|
||||
"wave": "chang_bolang", # 波浪
|
||||
}
|
||||
|
||||
# 发际线贴图显式顺序表:决定 hair_style 序号(1-indexed)。
|
||||
# 不再依赖文件名字母序——字母序会因新增/重命名文件而错位,破坏现有前端/客户端取值。
|
||||
# key 须与 _gender_key 派生结果一致(已去空格):如 "inverse_arc"(源 man_ inverse_arc.png)、
|
||||
# "Softpetal"(源 man_Soft petal.png,大写 S 保留)。表外未知 key 兜底排到末尾。
|
||||
_HAIRSTYLE_ORDER = {
|
||||
"female": ["ellipse", "flower", "heart", "straight", "wave",
|
||||
"bigflower", "clasicalflower"], # 1..7
|
||||
"male": ["ellipse", "inverse_arc", "m", "straight", "heart", "Softpetal",
|
||||
"wave"], # 1..7
|
||||
}
|
||||
|
||||
_REPO = os.path.dirname(os.path.dirname(__file__))
|
||||
_TEXTURE_DIR = os.path.join(_REPO, "hairline_texture")
|
||||
_BLACK_TEXTURE_DIR = os.path.join(_REPO, "hairline_texture_black")
|
||||
@@ -46,29 +58,36 @@ _BLACK_TEXTURE_DIR = os.path.join(_REPO, "hairline_texture_black")
|
||||
# 关键:ComfyUI 单卡显存装不下 Flux(7.7G)+qwen CLIP(3.9G) 同驻,靠缓存 CLIP 文本条件避免重载。
|
||||
# prompt 不同会使缓存失效 → 重载 CLIP 并挤出 Flux(每次 +4s)。三接口用同一字符串即可全程命中。
|
||||
# 与 app.py 接口2/接口3 的默认 prompt 保持一致;可用 REDRAW_PROMPT 覆盖。
|
||||
_REDRAW_PROMPT = os.getenv("REDRAW_PROMPT", "填充遮罩区域的头发,皮肤加一点磨皮,再加一点美颜")
|
||||
_REDRAW_PROMPT = os.getenv("REDRAW_PROMPT", "填充遮罩区域的头发,人物增加一点磨皮")
|
||||
|
||||
# 接口2 女重绘整条管线(swapHair + ComfyUI)送模型前限边。真实照片常达 1257x1495:
|
||||
# 全分辨率 ComfyUI 重绘要 13~21s 且激活显存把模型挤出。女性路径含 swapHair(SD WebUI ~5.3s
|
||||
# 固定地板) + ComfyUI 两段串行。1024 档画质更好但部分大图会踩 12s 线,
|
||||
# 默认压到 896 兜底(ComfyUI ~4s,女性总耗时 9~11s);追画质可设 REDRAW_MAX_SIDE=1024。
|
||||
_REDRAW_MAX_SIDE = int(os.getenv("REDRAW_MAX_SIDE", "896"))
|
||||
# 全分辨率 ComfyUI 重绘要 13~21s 且激活显存把模型挤出。
|
||||
# 策略:输入图长边 > REDRAW_MAX_SIDE 才等比缩到该长边;≤ 时原图分辨率直送(不放大)。
|
||||
# 默认 1024:大于 1024 的图压到 1024(画质/速度均衡),≤1024 的小图保持原分辨率重绘。
|
||||
# 可用 REDRAW_MAX_SIDE 覆盖;0=永不缩图(原图直送)。
|
||||
_REDRAW_MAX_SIDE = int(os.getenv("REDRAW_MAX_SIDE", "1024"))
|
||||
|
||||
def _call_local_redraw(image_png_bytes, mask_png_bytes, timeout=300.0):
|
||||
def _call_local_redraw(image_png_bytes, mask_png_bytes, timeout=300.0,
|
||||
max_side=None, unet_name=None, prompt=None):
|
||||
"""直接调 ComfyUI 重绘(替代原 local_test HTTP 服务)。
|
||||
|
||||
传 final 图 + 纯红遮罩 PNG,返回重绘后的 PNG bytes。
|
||||
失败抛异常(调用方负责 try/except 跳过)。
|
||||
|
||||
max_side:送 ComfyUI 前长边压到多少像素,None 用全局默认 _REDRAW_MAX_SIDE。
|
||||
unet_name:非 None 时切换 Flux 模型,None 用工作流内置默认。
|
||||
prompt:None 用默认 _REDRAW_PROMPT,否则用传入的提示词。
|
||||
"""
|
||||
from .redraw import run_redraw
|
||||
eff_side = _REDRAW_MAX_SIDE if max_side is None else max_side
|
||||
img = cv2.imdecode(np.frombuffer(image_png_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
scale = 1.0
|
||||
orig_w = orig_h = 0
|
||||
if img is not None:
|
||||
orig_h, orig_w = img.shape[:2]
|
||||
m = max(orig_h, orig_w)
|
||||
if _REDRAW_MAX_SIDE > 0 and m > _REDRAW_MAX_SIDE:
|
||||
scale = _REDRAW_MAX_SIDE / float(m)
|
||||
if eff_side > 0 and m > eff_side:
|
||||
scale = eff_side / float(m)
|
||||
nw, nh = max(1, round(orig_w * scale)), max(1, round(orig_h * scale))
|
||||
msk = cv2.imdecode(np.frombuffer(mask_png_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
img_s = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_AREA)
|
||||
@@ -76,10 +95,11 @@ def _call_local_redraw(image_png_bytes, mask_png_bytes, timeout=300.0):
|
||||
image_png_bytes = cv2.imencode(".png", img_s)[1].tobytes()
|
||||
mask_png_bytes = cv2.imencode(".png", msk_s)[1].tobytes()
|
||||
logger.info("接口2女 缩图送 Comfy: %dx%d → %dx%d (max_side=%d)",
|
||||
orig_w, orig_h, nw, nh, _REDRAW_MAX_SIDE)
|
||||
orig_w, orig_h, nw, nh, eff_side)
|
||||
# front=True:接口2 时延敏感,插到 ComfyUI 队列最前,避免排在接口3/5 的批量任务后面
|
||||
out = run_redraw(image_png_bytes, mask_png_bytes, timeout=timeout,
|
||||
prompt=_REDRAW_PROMPT, front=True)
|
||||
prompt=prompt if prompt is not None else _REDRAW_PROMPT,
|
||||
front=True, unet_name=unet_name)
|
||||
if scale < 1.0 and out:
|
||||
out = _upscale_png_to(out, orig_w, orig_h)
|
||||
return out
|
||||
@@ -123,10 +143,13 @@ def _gender_key(stem: str):
|
||||
|
||||
|
||||
def get_texture_map(level: str = "middle") -> dict:
|
||||
"""扫描指定档位贴图目录建 {gender: [(key, path)]},按 key 排序、按档位缓存。
|
||||
"""扫描指定档位贴图目录建 {gender: [(key, path)]},按显式顺序表排序、按档位缓存。
|
||||
|
||||
level:middle(默认) / high / low,分别对应 hairline_texture[/_high|/_low]。
|
||||
文件名规范化去空格(如 `man_ inverse_arc.png` → key `inverse_arc`)。
|
||||
|
||||
排序依据 _HAIRSTYLE_ORDER:表内 key 按表序、表外未知 key 兜底排到末尾(再按字母序),
|
||||
保证新增/重命名文件不会打乱现有 hair_style 序号。
|
||||
"""
|
||||
if level not in _TEXTURE_DIRS:
|
||||
raise ValueError(f"hairline_level 必须是 middle/high/low,收到 {level!r}")
|
||||
@@ -140,7 +163,9 @@ def get_texture_map(level: str = "middle") -> dict:
|
||||
if gender:
|
||||
mapping[gender].append((key, path))
|
||||
for g in mapping:
|
||||
mapping[g].sort(key=lambda kp: kp[0])
|
||||
order = _HAIRSTYLE_ORDER.get(g, [])
|
||||
idx = {k: i for i, k in enumerate(order)}
|
||||
mapping[g].sort(key=lambda kp: (idx.get(kp[0], len(idx)), kp[0]))
|
||||
_texture_maps[level] = mapping
|
||||
return mapping
|
||||
|
||||
@@ -200,10 +225,11 @@ def generate_previews(image_bgr: np.ndarray, gender: str):
|
||||
|
||||
def generate_grow_results(image_bgr: np.ndarray, gender: str, use_mask: bool = True,
|
||||
prompt: str = None, hair_styles: list[int] | None = None,
|
||||
workflow_path: str | None = None):
|
||||
workflow_path: str | None = None,
|
||||
unet_name: str | None = None):
|
||||
"""指定发际线类型:发际线透明叠图(白线 RGBA) + 生发图(ComfyUI)。
|
||||
|
||||
hair_styles(1-indexed 列表):指定生成哪几张发际线(按贴图排序)。female: 1..5,male: 1..4。
|
||||
hair_styles(1-indexed 列表):指定生成哪几张发际线(按贴图排序)。female: 1..7,male: 1..7。
|
||||
为 None 时生成全部(兼容旧调用)。
|
||||
use_mask(默认 True):是否启用 inpaint 遮罩,用于测试对比(同接口3)。
|
||||
False 时用**干净原图 + 空遮罩**送 ComfyUI(不烧黑色模板线)。
|
||||
@@ -236,7 +262,8 @@ def generate_grow_results(image_bgr: np.ndarray, gender: str, use_mask: bool = T
|
||||
compose_comfy_rgba(img_s, msk_s).save(buf, format="PNG", compress_level=1)
|
||||
# front=True:接口2 时延敏感,插到 ComfyUI 队列最前
|
||||
shared_grown = comfyui.run(buf.getvalue(), prompt=prompt,
|
||||
workflow_path=workflow_path, front=True)
|
||||
workflow_path=workflow_path, front=True,
|
||||
unet_name=unet_name)
|
||||
if gsc < 1.0 and shared_grown:
|
||||
shared_grown = _upscale_png_to(shared_grown, w, h)
|
||||
except Exception as e: # noqa: BLE001
|
||||
@@ -261,7 +288,8 @@ def generate_grow_results(image_bgr: np.ndarray, gender: str, use_mask: bool = T
|
||||
compose_comfy_rgba(m_s, msk_s).save(buf, format="PNG", compress_level=1)
|
||||
# front=True:接口2 时延敏感,插到 ComfyUI 队列最前
|
||||
grown_png = comfyui.run(buf.getvalue(), prompt=prompt,
|
||||
workflow_path=workflow_path, front=True)
|
||||
workflow_path=workflow_path, front=True,
|
||||
unet_name=unet_name)
|
||||
if gsc < 1.0 and grown_png:
|
||||
grown_png = _upscale_png_to(grown_png, w, h)
|
||||
except Exception as e: # noqa: BLE001 单张失败不拖垮整请求
|
||||
@@ -273,15 +301,25 @@ def generate_grow_results(image_bgr: np.ndarray, gender: str, use_mask: bool = T
|
||||
|
||||
|
||||
def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | None,
|
||||
redraw_defaults: dict):
|
||||
"""接口2 女性专用:发际线透明叠图(同 generate_grow_results)+ 换发型重绘图。
|
||||
redraw_defaults: dict,
|
||||
redraw_max_side: int | None = None,
|
||||
unet_name: str | None = None,
|
||||
prompt: str | None = None):
|
||||
"""接口2 女性专用:发际线透明叠图(同 generate_grow_results)+ 生发图。
|
||||
|
||||
grown 图来源(新流程):对每个选中发型把 female key 映射到 change_hair 的 chang_* hair_id,
|
||||
调 face_analysis.hairline_grow.generate_hairline_redraw(= 接口12 final 管线,参数用
|
||||
redraw_defaults)拿到 ④ final(接缝融合基底)+ ⑤-② 纯红遮罩 PNG,再**后端直接调
|
||||
ComfyUI**(0716add-hair-api.json 工作流)完成发际线带重绘,重绘结果作为生发图。
|
||||
生发图来源按发型分两路:
|
||||
- 换发型(chang_* 表内,1..5):female key → change_hair 的 chang_* hair_id,调
|
||||
face_analysis.hairline_grow.generate_hairline_redraw(= 接口12 final 管线,参数用
|
||||
redraw_defaults)拿到 ④ final(接缝融合基底)+ ⑤-② 纯红遮罩 PNG,再**后端直接调
|
||||
ComfyUI**(0716add-hair-api.json 工作流)完成发际线带重绘。
|
||||
- 原生生发(表外,6/7 bigflower/clasicalflower 等):无对应 change_hair LoRA,改走与男性
|
||||
一致的原生生发(ComfyUI add_hair),由 _grow_native_one 完成(黑模板 + inpaint 遮罩)。
|
||||
|
||||
overlay 仍是发际线曲线透明层(与 generate_grow_results 完全一致)。
|
||||
prompt 两条分支都生效:换发型分支传入 _call_local_redraw,原生生发分支传给
|
||||
_grow_native_one。None/默认「填充遮罩区域的头发,人物增加一点磨皮」时与全局 _REDRAW_PROMPT 一致,
|
||||
不破坏 CLIP 缓存命中的快路径;传不同提示词会使缓存失效并重载 CLIP/Flux
|
||||
(实测换词后首次请求重绘 45s vs 缓存命中 8s),后续相同提示词恢复快路径。
|
||||
Returns: list[dict] {"hairline_type","order","overlay","grown_png"(jpg bytes 或 None)};
|
||||
无人脸返回 None。单个发型换发型/重绘失败时 grown_png=None,不抛异常。
|
||||
"""
|
||||
@@ -307,16 +345,17 @@ def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | N
|
||||
|
||||
# 重绘管线(swapHair + ComfyUI)统一降分辨率:真实照片 swap(SD WebUI)~5s、blend、ComfyUI
|
||||
# 均随分辨率线性下降。overlay 预览仍用全分辨率;grown_png 最后放大回原尺寸。
|
||||
eff_side = _REDRAW_MAX_SIDE if redraw_max_side is None else redraw_max_side
|
||||
redraw_img = image_bgr
|
||||
hair_mask_redraw = hair_mask_reuse
|
||||
if _REDRAW_MAX_SIDE > 0 and max(h, w) > _REDRAW_MAX_SIDE:
|
||||
redraw_img, _rs = _downscale_max_side(image_bgr, _REDRAW_MAX_SIDE)
|
||||
if eff_side > 0 and max(h, w) > eff_side:
|
||||
redraw_img, _rs = _downscale_max_side(image_bgr, eff_side)
|
||||
_nh, _nw = redraw_img.shape[:2]
|
||||
if hair_mask_redraw is not None:
|
||||
hair_mask_redraw = cv2.resize(hair_mask_reuse.astype(np.uint8), (_nw, _nh),
|
||||
interpolation=cv2.INTER_NEAREST).astype(bool)
|
||||
logger.info("接口2女 管线降分辨率: %dx%d → %dx%d (max_side=%d)",
|
||||
w, h, _nw, _nh, _REDRAW_MAX_SIDE)
|
||||
w, h, _nw, _nh, eff_side)
|
||||
|
||||
for order, (key, white_path) in items:
|
||||
white = load_texture_rgba(white_path)
|
||||
@@ -325,7 +364,10 @@ def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | N
|
||||
grown_png = None
|
||||
chang_id = _FEMALE_KEY_TO_CHANG.get(key)
|
||||
if chang_id is None:
|
||||
logger.warning("接口2 换发型:female key=%s 无对应 chang_id,跳过生发图", key)
|
||||
# 无对应 change_hair LoRA(如 bigflower/clasicalflower)→ 走与男性一致的原生生发
|
||||
logger.info("接口2 女 key=%s 无 chang_id,走原生生发(ComfyUI add_hair)", key)
|
||||
grown_png = _grow_native_one(image_bgr, ctx, white_path,
|
||||
prompt=prompt, unet_name=unet_name)
|
||||
else:
|
||||
try:
|
||||
import time as _t
|
||||
@@ -349,7 +391,10 @@ def generate_grow_results_swap(image_bgr: np.ndarray, hair_styles: list[int] | N
|
||||
mask_bytes = base64.b64decode(mask_b64)
|
||||
# 后端直接调 ComfyUI 重绘,返回重绘后的 PNG
|
||||
_tr0 = _t.perf_counter()
|
||||
grown_png = _call_local_redraw(final_bytes, mask_bytes)
|
||||
grown_png = _call_local_redraw(final_bytes, mask_bytes,
|
||||
max_side=redraw_max_side,
|
||||
unet_name=unet_name,
|
||||
prompt=prompt)
|
||||
_tr1 = _t.perf_counter()
|
||||
_tm = data.get("timings_ms") or {}
|
||||
logger.info("接口2女 分段计时 type=%s: swapHair管线=%.2fs (mask=%dms swap=%dms blend=%dms), ComfyUI重绘=%.2fs",
|
||||
@@ -394,17 +439,51 @@ def _grow_from_texture(image_bgr: np.ndarray, ctx: dict, white_path: str | None,
|
||||
return None
|
||||
|
||||
|
||||
def _grow_native_one(image_bgr: np.ndarray, ctx: dict, white_path: str,
|
||||
prompt: str | None = None, unet_name: str | None = None):
|
||||
"""对单个发际线做原生生发(ComfyUI add_hair),与男性 generate_grow_results 一致。
|
||||
|
||||
接口2 女性新发型(bigflower/clasicalflower 等)无对应 change_hair LoRA,改走此路径:
|
||||
黑模板 → build_inpaint_mask → 限边(_prep_comfy_input)→ comfyui.run(front=True)。
|
||||
失败返回 None,不抛异常。结果按限边前原图尺寸放大回原尺寸(仅展示对齐)。
|
||||
"""
|
||||
try:
|
||||
h, w = image_bgr.shape[:2]
|
||||
black = load_texture_rgba(_black_texture_path(white_path))
|
||||
marked, mask = build_inpaint_mask(
|
||||
image_bgr, ctx["landmarks"], ctx["parse_map"], ctx["points"], black)
|
||||
m_s, msk_s, gsc = _prep_comfy_input(marked, mask)
|
||||
buf = io.BytesIO()
|
||||
compose_comfy_rgba(m_s, msk_s).save(buf, format="PNG", compress_level=1)
|
||||
# front=True:接口2 时延敏感,插到 ComfyUI 队列最前
|
||||
grown_png = comfyui.run(buf.getvalue(), prompt=prompt, front=True, unet_name=unet_name)
|
||||
if gsc < 1.0 and grown_png:
|
||||
grown_png = _upscale_png_to(grown_png, w, h)
|
||||
return grown_png
|
||||
except Exception as e: # noqa: BLE001 单张失败不拖垮整请求
|
||||
logger.warning("接口2 女原生生发图失败:%s", e)
|
||||
return None
|
||||
|
||||
|
||||
def generate_hairline_pngs(image_bgr: np.ndarray, gender: str,
|
||||
hair_styles: list[int], use_mask: bool = True,
|
||||
prompt: str | None = None,
|
||||
generate_grow_image: bool = True):
|
||||
generate_grow_image: bool = True,
|
||||
redraw_max_side: int | None = None,
|
||||
unet_name: str | None = None,
|
||||
v2_defaults: dict | None = None):
|
||||
"""接口5:对选中发型返回 middle/high/low 三档发际线透明叠图 + 生发图(同接口2)。
|
||||
|
||||
入参同接口2:先选 gender,再多选 hair_styles(必填,1-indexed 按贴图排序)。
|
||||
每个选中发型返回三档叠图(middle/high/low,RGBA 透明层只含发际线曲线)与一张生发图;
|
||||
三档贴图同名,生发黑模板固定取自 hairline_texture_black/(middle),故生发目标固定 middle 档。
|
||||
use_mask/prompt:同接口2 的生发参数。
|
||||
generate_grow_image(默认 True):是否生成生发图(ComfyUI,最耗时)。False 时跳过生发,
|
||||
|
||||
生发机制(同接口2,按性别分流):
|
||||
- female:generate_grow_results_swap(swapHair + Flux-2 整帧重绘)
|
||||
- male:generate_grow_results(ComfyUI add_hair inpaint)
|
||||
redraw_max_side / unet_name / v2_defaults:female 路径参数,同接口2。
|
||||
male 路径仅用 unet_name;redraw_max_side/v2_defaults 对 male 无意义(忽略)。
|
||||
use_mask/prompt:仅 male 路径生效(同接口2 male)。
|
||||
generate_grow_image(默认 True):是否生成生发图(最耗时)。False 时跳过生发,
|
||||
各发型 grown_png 恒为 None,可大幅降低耗时(仅留三档发际线叠图与中心点)。
|
||||
Returns: {"images":[{hairline_type,order,overlays:{middle,high,low}((H,W,4) RGBA 透明层),grown_png}],
|
||||
"best_centers":{"middle":(x,y),"high":(x,y),"low":(x,y)}};无人脸 None。
|
||||
@@ -426,11 +505,27 @@ def generate_hairline_pngs(image_bgr: np.ndarray, gender: str,
|
||||
# 三档贴图表(同性别、同 key 顺序,因三个文件夹同名)
|
||||
tex_by_level = {lv: get_texture_map(lv)[gender] for lv in _TEXTURE_DIRS}
|
||||
|
||||
# use_mask=False:干净原图+空遮罩与贴图无关,只跑一次 ComfyUI,选中项复用
|
||||
# generate_grow_image=False:完全跳过生发(最耗时),grown_png 恒为 None
|
||||
shared_grown = None
|
||||
if generate_grow_image and not use_mask:
|
||||
shared_grown = _grow_from_texture(image_bgr, ctx, None, use_mask=False, prompt=prompt)
|
||||
# 生发图(同接口2,按性别分流):一次性算出所有选中发型的生发图,按 order 对应回叠图。
|
||||
# female→generate_grow_results_swap(swapHair+Flux-2 整帧重绘);
|
||||
# male→generate_grow_results(ComfyUI add_hair inpaint)。
|
||||
# generate_grow_image=False 时跳过,grown_by_order 为空 dict(各发型 grown_png 恒 None)。
|
||||
grown_by_order: dict[int, bytes | None] = {}
|
||||
if generate_grow_image:
|
||||
try:
|
||||
if gender == "female":
|
||||
items = generate_grow_results_swap(
|
||||
image_bgr, hair_styles, v2_defaults or {},
|
||||
redraw_max_side=redraw_max_side, unet_name=unet_name)
|
||||
else:
|
||||
items = generate_grow_results(
|
||||
image_bgr, gender, use_mask, prompt, hair_styles,
|
||||
unet_name=unet_name)
|
||||
if items is None:
|
||||
return None # 无人脸(同接口2 的 None 语义)
|
||||
for it in items:
|
||||
grown_by_order[it["order"]] = it.get("grown_png")
|
||||
except Exception as e: # noqa: BLE001 整批生发失败不拖垮叠图主结果
|
||||
logger.warning("接口5 生发批量失败(gender=%s):%s", gender, e)
|
||||
|
||||
def _center_of(overlay):
|
||||
"""从某档发际线透明叠图取面部中轴处的发际线中点 (x,y),无像素返回 None。"""
|
||||
@@ -443,18 +538,13 @@ def generate_hairline_pngs(image_bgr: np.ndarray, gender: str,
|
||||
|
||||
images, best_centers = [], None
|
||||
for s in hair_styles: # s = 1-indexed 发型序号
|
||||
key, mid_path = tex_by_level["middle"][s - 1]
|
||||
key, _mid_path = tex_by_level["middle"][s - 1]
|
||||
overlays = {}
|
||||
for lv in _TEXTURE_DIRS:
|
||||
white = load_texture_rgba(tex_by_level[lv][s - 1][1])
|
||||
overlays[lv] = build_overlay_layer(h, w, ctx["points"], ext_faces, uv, white)
|
||||
# 生发:固定 middle 黑模板(generate_grow_image=False 时跳过,恒 None)
|
||||
if not generate_grow_image:
|
||||
grown_png = None
|
||||
elif not use_mask:
|
||||
grown_png = shared_grown
|
||||
else:
|
||||
grown_png = _grow_from_texture(image_bgr, ctx, mid_path, use_mask=True, prompt=prompt)
|
||||
# 生发图:从按性别算好的结果里按 order 取(generate_grow_image=False 时缺省 None)
|
||||
grown_png = grown_by_order.get(s)
|
||||
images.append({"hairline_type": key, "order": s,
|
||||
"overlays": overlays, "grown_png": grown_png})
|
||||
# best_centers:首个选中发型三档(middle/high/low)发际线中点
|
||||
|
||||
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 6.0 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 5.6 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 5.9 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 4.1 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 5.9 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 5.9 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 6.2 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 440 KiB |
@@ -0,0 +1,75 @@
|
||||
=== 接口2 female 批量对比测试 ===
|
||||
矩阵: 4图 × 5发型 × 2档 = 40 次
|
||||
已跳过 0 个已完成项
|
||||
|
||||
[1/40] ▶ girl2_ellipse_default896 (side=None)... ✅ 10.8s 出图 1082x1081 (204589B)
|
||||
[2/40] ▶ girl2_ellipse_origin0 (side=0)... ✅ 13.3s 出图 1088x1088 (232252B)
|
||||
[3/40] ▶ girl2_flower_default896 (side=None)... ✅ 11.0s 出图 1082x1081 (210875B)
|
||||
[4/40] ▶ girl2_flower_origin0 (side=0)... ✅ 12.5s 出图 1088x1088 (236073B)
|
||||
[5/40] ▶ girl2_heart_default896 (side=None)... ✅ 11.9s 出图 1082x1081 (198911B)
|
||||
[6/40] ▶ girl2_heart_origin0 (side=0)... ✅ 12.2s 出图 1088x1088 (249893B)
|
||||
[7/40] ▶ girl2_straight_default896 (side=None)... ✅ 12.1s 出图 1082x1081 (211803B)
|
||||
[8/40] ▶ girl2_straight_origin0 (side=0)... ✅ 12.3s 出图 1088x1088 (235377B)
|
||||
[9/40] ▶ girl2_wave_default896 (side=None)... ✅ 12.7s 出图 1082x1081 (207736B)
|
||||
[10/40] ▶ girl2_wave_origin0 (side=0)... ✅ 11.9s 出图 1088x1088 (238081B)
|
||||
[11/40] ▶ girl5_ellipse_default896 (side=None)... ✅ 9.6s 出图 768x752 (105867B)
|
||||
[12/40] ▶ girl5_ellipse_origin0 (side=0)... ✅ 7.3s 出图 768x752 (112963B)
|
||||
[13/40] ▶ girl5_flower_default896 (side=None)... ✅ 8.0s 出图 768x752 (114378B)
|
||||
[14/40] ▶ girl5_flower_origin0 (side=0)... ✅ 7.2s 出图 768x752 (108495B)
|
||||
[15/40] ▶ girl5_heart_default896 (side=None)... ✅ 8.1s 出图 768x752 (113874B)
|
||||
[16/40] ▶ girl5_heart_origin0 (side=0)... ✅ 7.6s 出图 768x752 (103160B)
|
||||
[17/40] ▶ girl5_straight_default896 (side=None)... ✅ 8.4s 出图 768x752 (104492B)
|
||||
[18/40] ▶ girl5_straight_origin0 (side=0)... ✅ 7.2s 出图 768x752 (100941B)
|
||||
[19/40] ▶ girl5_wave_default896 (side=None)... ✅ 8.4s 出图 768x752 (120122B)
|
||||
[20/40] ▶ girl5_wave_origin0 (side=0)... ✅ 7.7s 出图 768x752 (113282B)
|
||||
[21/40] ▶ qwer_ellipse_default896 (side=None)... ✅ 10.2s 出图 1288x1678 (261812B)
|
||||
[22/40] ▶ qwer_ellipse_origin0 (side=0)... ✅ 30.0s 出图 1280x1680 (331013B)
|
||||
[23/40] ▶ qwer_flower_default896 (side=None)... ✅ 10.2s 出图 1288x1678 (312834B)
|
||||
[24/40] ▶ qwer_flower_origin0 (side=0)... ✅ 25.0s 出图 1280x1680 (328605B)
|
||||
[25/40] ▶ qwer_heart_default896 (side=None)... ✅ 11.1s 出图 1288x1678 (331337B)
|
||||
[26/40] ▶ qwer_heart_origin0 (side=0)... ✅ 25.0s 出图 1280x1680 (355982B)
|
||||
[27/40] ▶ qwer_straight_default896 (side=None)... ✅ 10.7s 出图 1288x1678 (281665B)
|
||||
[28/40] ▶ qwer_straight_origin0 (side=0)... ✅ 23.4s 出图 1280x1680 (322183B)
|
||||
[29/40] ▶ qwer_wave_default896 (side=None)... ✅ 11.1s 出图 1288x1678 (289322B)
|
||||
[30/40] ▶ qwer_wave_origin0 (side=0)... ✅ 25.8s 出图 1280x1680 (351719B)
|
||||
[31/40] ▶ asdf_ellipse_default896 (side=None)... ✅ 11.2s 出图 1254x1666 (285362B)
|
||||
[32/40] ▶ asdf_ellipse_origin0 (side=0)... ✅ 25.7s 出图 1248x1664 (286768B)
|
||||
[33/40] ▶ asdf_flower_default896 (side=None)... ✅ 10.7s 出图 1254x1666 (266946B)
|
||||
[34/40] ▶ asdf_flower_origin0 (side=0)... ✅ 22.9s 出图 1248x1664 (353668B)
|
||||
[35/40] ▶ asdf_heart_default896 (side=None)... ✅ 10.4s 出图 1254x1666 (271975B)
|
||||
[36/40] ▶ asdf_heart_origin0 (side=0)... ✅ 22.9s 出图 1248x1664 (291983B)
|
||||
[37/40] ▶ asdf_straight_default896 (side=None)... ✅ 9.8s 出图 1254x1666 (258665B)
|
||||
[38/40] ▶ asdf_straight_origin0 (side=0)... ✅ 24.0s 出图 1248x1664 (279883B)
|
||||
[39/40] ▶ asdf_wave_default896 (side=None)... ✅ 11.9s 出图 1254x1666 (286515B)
|
||||
[40/40] ▶ asdf_wave_origin0 (side=0)... ✅ 24.3s 出图 1248x1664 (295694B)
|
||||
|
||||
======================================================================
|
||||
汇总报告
|
||||
======================================================================
|
||||
|
||||
--- 速度对比(秒,✓=成功 ✗=失败)---
|
||||
图 发型 默认896 原图0 差值
|
||||
girl2 ellipse 10.8✓ 13.3✓ +2.5
|
||||
girl2 flower 11.0✓ 12.5✓ +1.5
|
||||
girl2 heart 11.9✓ 12.2✓ +0.3
|
||||
girl2 straight 12.1✓ 12.3✓ +0.2
|
||||
girl2 wave 12.7✓ 11.9✓ -0.8
|
||||
girl5 ellipse 9.6✓ 7.3✓ -2.3
|
||||
girl5 flower 8.0✓ 7.2✓ -0.8
|
||||
girl5 heart 8.1✓ 7.6✓ -0.5
|
||||
girl5 straight 8.4✓ 7.2✓ -1.2
|
||||
girl5 wave 8.4✓ 7.7✓ -0.7
|
||||
qwer ellipse 10.2✓ 30.0✓ +19.8
|
||||
qwer flower 10.2✓ 25.0✓ +14.8
|
||||
qwer heart 11.1✓ 25.0✓ +13.9
|
||||
qwer straight 10.7✓ 23.4✓ +12.7
|
||||
qwer wave 11.1✓ 25.8✓ +14.7
|
||||
asdf ellipse 11.2✓ 25.7✓ +14.5
|
||||
asdf flower 10.7✓ 22.9✓ +12.2
|
||||
asdf heart 10.4✓ 22.9✓ +12.5
|
||||
asdf straight 9.8✓ 24.0✓ +14.2
|
||||
asdf wave 11.9✓ 24.3✓ +12.4
|
||||
|
||||
结果图: /home/ubuntu/hair/image/compare_test/out/
|
||||
CSV报告: /home/ubuntu/hair/image/compare_test/out/report.csv
|
||||
JSON明细: /home/ubuntu/hair/image/compare_test/out/report.json
|
||||
@@ -0,0 +1,41 @@
|
||||
img,style,side,ok,elapsed_s,out_w,out_h,err
|
||||
girl2,ellipse,default896,True,10.8,1082,1081,
|
||||
girl2,ellipse,origin0,True,13.3,1088,1088,
|
||||
girl2,flower,default896,True,11.0,1082,1081,
|
||||
girl2,flower,origin0,True,12.5,1088,1088,
|
||||
girl2,heart,default896,True,11.9,1082,1081,
|
||||
girl2,heart,origin0,True,12.2,1088,1088,
|
||||
girl2,straight,default896,True,12.1,1082,1081,
|
||||
girl2,straight,origin0,True,12.3,1088,1088,
|
||||
girl2,wave,default896,True,12.7,1082,1081,
|
||||
girl2,wave,origin0,True,11.9,1088,1088,
|
||||
girl5,ellipse,default896,True,9.6,768,752,
|
||||
girl5,ellipse,origin0,True,7.3,768,752,
|
||||
girl5,flower,default896,True,8.0,768,752,
|
||||
girl5,flower,origin0,True,7.2,768,752,
|
||||
girl5,heart,default896,True,8.1,768,752,
|
||||
girl5,heart,origin0,True,7.6,768,752,
|
||||
girl5,straight,default896,True,8.4,768,752,
|
||||
girl5,straight,origin0,True,7.2,768,752,
|
||||
girl5,wave,default896,True,8.4,768,752,
|
||||
girl5,wave,origin0,True,7.7,768,752,
|
||||
qwer,ellipse,default896,True,10.2,1288,1678,
|
||||
qwer,ellipse,origin0,True,30.0,1280,1680,
|
||||
qwer,flower,default896,True,10.2,1288,1678,
|
||||
qwer,flower,origin0,True,25.0,1280,1680,
|
||||
qwer,heart,default896,True,11.1,1288,1678,
|
||||
qwer,heart,origin0,True,25.0,1280,1680,
|
||||
qwer,straight,default896,True,10.7,1288,1678,
|
||||
qwer,straight,origin0,True,23.4,1280,1680,
|
||||
qwer,wave,default896,True,11.1,1288,1678,
|
||||
qwer,wave,origin0,True,25.8,1280,1680,
|
||||
asdf,ellipse,default896,True,11.2,1254,1666,
|
||||
asdf,ellipse,origin0,True,25.7,1248,1664,
|
||||
asdf,flower,default896,True,10.7,1254,1666,
|
||||
asdf,flower,origin0,True,22.9,1248,1664,
|
||||
asdf,heart,default896,True,10.4,1254,1666,
|
||||
asdf,heart,origin0,True,22.9,1248,1664,
|
||||
asdf,straight,default896,True,9.8,1254,1666,
|
||||
asdf,straight,origin0,True,24.0,1248,1664,
|
||||
asdf,wave,default896,True,11.9,1254,1666,
|
||||
asdf,wave,origin0,True,24.3,1248,1664,
|
||||
|
@@ -0,0 +1,562 @@
|
||||
[
|
||||
{
|
||||
"key": "girl2_ellipse_default896",
|
||||
"img": "girl2",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 10.8,
|
||||
"err": "",
|
||||
"out_w": 1082,
|
||||
"out_h": 1081,
|
||||
"bytes": 204589
|
||||
},
|
||||
{
|
||||
"key": "girl2_ellipse_origin0",
|
||||
"img": "girl2",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 13.3,
|
||||
"err": "",
|
||||
"out_w": 1088,
|
||||
"out_h": 1088,
|
||||
"bytes": 232252
|
||||
},
|
||||
{
|
||||
"key": "girl2_flower_default896",
|
||||
"img": "girl2",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 11.0,
|
||||
"err": "",
|
||||
"out_w": 1082,
|
||||
"out_h": 1081,
|
||||
"bytes": 210875
|
||||
},
|
||||
{
|
||||
"key": "girl2_flower_origin0",
|
||||
"img": "girl2",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 12.5,
|
||||
"err": "",
|
||||
"out_w": 1088,
|
||||
"out_h": 1088,
|
||||
"bytes": 236073
|
||||
},
|
||||
{
|
||||
"key": "girl2_heart_default896",
|
||||
"img": "girl2",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 11.9,
|
||||
"err": "",
|
||||
"out_w": 1082,
|
||||
"out_h": 1081,
|
||||
"bytes": 198911
|
||||
},
|
||||
{
|
||||
"key": "girl2_heart_origin0",
|
||||
"img": "girl2",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 12.2,
|
||||
"err": "",
|
||||
"out_w": 1088,
|
||||
"out_h": 1088,
|
||||
"bytes": 249893
|
||||
},
|
||||
{
|
||||
"key": "girl2_straight_default896",
|
||||
"img": "girl2",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 12.1,
|
||||
"err": "",
|
||||
"out_w": 1082,
|
||||
"out_h": 1081,
|
||||
"bytes": 211803
|
||||
},
|
||||
{
|
||||
"key": "girl2_straight_origin0",
|
||||
"img": "girl2",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 12.3,
|
||||
"err": "",
|
||||
"out_w": 1088,
|
||||
"out_h": 1088,
|
||||
"bytes": 235377
|
||||
},
|
||||
{
|
||||
"key": "girl2_wave_default896",
|
||||
"img": "girl2",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 12.7,
|
||||
"err": "",
|
||||
"out_w": 1082,
|
||||
"out_h": 1081,
|
||||
"bytes": 207736
|
||||
},
|
||||
{
|
||||
"key": "girl2_wave_origin0",
|
||||
"img": "girl2",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 11.9,
|
||||
"err": "",
|
||||
"out_w": 1088,
|
||||
"out_h": 1088,
|
||||
"bytes": 238081
|
||||
},
|
||||
{
|
||||
"key": "girl5_ellipse_default896",
|
||||
"img": "girl5",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 9.6,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 105867
|
||||
},
|
||||
{
|
||||
"key": "girl5_ellipse_origin0",
|
||||
"img": "girl5",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 7.3,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 112963
|
||||
},
|
||||
{
|
||||
"key": "girl5_flower_default896",
|
||||
"img": "girl5",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 8.0,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 114378
|
||||
},
|
||||
{
|
||||
"key": "girl5_flower_origin0",
|
||||
"img": "girl5",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 7.2,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 108495
|
||||
},
|
||||
{
|
||||
"key": "girl5_heart_default896",
|
||||
"img": "girl5",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 8.1,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 113874
|
||||
},
|
||||
{
|
||||
"key": "girl5_heart_origin0",
|
||||
"img": "girl5",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 7.6,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 103160
|
||||
},
|
||||
{
|
||||
"key": "girl5_straight_default896",
|
||||
"img": "girl5",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 8.4,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 104492
|
||||
},
|
||||
{
|
||||
"key": "girl5_straight_origin0",
|
||||
"img": "girl5",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 7.2,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 100941
|
||||
},
|
||||
{
|
||||
"key": "girl5_wave_default896",
|
||||
"img": "girl5",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 8.4,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 120122
|
||||
},
|
||||
{
|
||||
"key": "girl5_wave_origin0",
|
||||
"img": "girl5",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 7.7,
|
||||
"err": "",
|
||||
"out_w": 768,
|
||||
"out_h": 752,
|
||||
"bytes": 113282
|
||||
},
|
||||
{
|
||||
"key": "qwer_ellipse_default896",
|
||||
"img": "qwer",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 10.2,
|
||||
"err": "",
|
||||
"out_w": 1288,
|
||||
"out_h": 1678,
|
||||
"bytes": 261812
|
||||
},
|
||||
{
|
||||
"key": "qwer_ellipse_origin0",
|
||||
"img": "qwer",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 30.0,
|
||||
"err": "",
|
||||
"out_w": 1280,
|
||||
"out_h": 1680,
|
||||
"bytes": 331013
|
||||
},
|
||||
{
|
||||
"key": "qwer_flower_default896",
|
||||
"img": "qwer",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 10.2,
|
||||
"err": "",
|
||||
"out_w": 1288,
|
||||
"out_h": 1678,
|
||||
"bytes": 312834
|
||||
},
|
||||
{
|
||||
"key": "qwer_flower_origin0",
|
||||
"img": "qwer",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 25.0,
|
||||
"err": "",
|
||||
"out_w": 1280,
|
||||
"out_h": 1680,
|
||||
"bytes": 328605
|
||||
},
|
||||
{
|
||||
"key": "qwer_heart_default896",
|
||||
"img": "qwer",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 11.1,
|
||||
"err": "",
|
||||
"out_w": 1288,
|
||||
"out_h": 1678,
|
||||
"bytes": 331337
|
||||
},
|
||||
{
|
||||
"key": "qwer_heart_origin0",
|
||||
"img": "qwer",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 25.0,
|
||||
"err": "",
|
||||
"out_w": 1280,
|
||||
"out_h": 1680,
|
||||
"bytes": 355982
|
||||
},
|
||||
{
|
||||
"key": "qwer_straight_default896",
|
||||
"img": "qwer",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 10.7,
|
||||
"err": "",
|
||||
"out_w": 1288,
|
||||
"out_h": 1678,
|
||||
"bytes": 281665
|
||||
},
|
||||
{
|
||||
"key": "qwer_straight_origin0",
|
||||
"img": "qwer",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 23.4,
|
||||
"err": "",
|
||||
"out_w": 1280,
|
||||
"out_h": 1680,
|
||||
"bytes": 322183
|
||||
},
|
||||
{
|
||||
"key": "qwer_wave_default896",
|
||||
"img": "qwer",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 11.1,
|
||||
"err": "",
|
||||
"out_w": 1288,
|
||||
"out_h": 1678,
|
||||
"bytes": 289322
|
||||
},
|
||||
{
|
||||
"key": "qwer_wave_origin0",
|
||||
"img": "qwer",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 25.8,
|
||||
"err": "",
|
||||
"out_w": 1280,
|
||||
"out_h": 1680,
|
||||
"bytes": 351719
|
||||
},
|
||||
{
|
||||
"key": "asdf_ellipse_default896",
|
||||
"img": "asdf",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 11.2,
|
||||
"err": "",
|
||||
"out_w": 1254,
|
||||
"out_h": 1666,
|
||||
"bytes": 285362
|
||||
},
|
||||
{
|
||||
"key": "asdf_ellipse_origin0",
|
||||
"img": "asdf",
|
||||
"style": "ellipse",
|
||||
"style_idx": 1,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 25.7,
|
||||
"err": "",
|
||||
"out_w": 1248,
|
||||
"out_h": 1664,
|
||||
"bytes": 286768
|
||||
},
|
||||
{
|
||||
"key": "asdf_flower_default896",
|
||||
"img": "asdf",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 10.7,
|
||||
"err": "",
|
||||
"out_w": 1254,
|
||||
"out_h": 1666,
|
||||
"bytes": 266946
|
||||
},
|
||||
{
|
||||
"key": "asdf_flower_origin0",
|
||||
"img": "asdf",
|
||||
"style": "flower",
|
||||
"style_idx": 2,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 22.9,
|
||||
"err": "",
|
||||
"out_w": 1248,
|
||||
"out_h": 1664,
|
||||
"bytes": 353668
|
||||
},
|
||||
{
|
||||
"key": "asdf_heart_default896",
|
||||
"img": "asdf",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 10.4,
|
||||
"err": "",
|
||||
"out_w": 1254,
|
||||
"out_h": 1666,
|
||||
"bytes": 271975
|
||||
},
|
||||
{
|
||||
"key": "asdf_heart_origin0",
|
||||
"img": "asdf",
|
||||
"style": "heart",
|
||||
"style_idx": 3,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 22.9,
|
||||
"err": "",
|
||||
"out_w": 1248,
|
||||
"out_h": 1664,
|
||||
"bytes": 291983
|
||||
},
|
||||
{
|
||||
"key": "asdf_straight_default896",
|
||||
"img": "asdf",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 9.8,
|
||||
"err": "",
|
||||
"out_w": 1254,
|
||||
"out_h": 1666,
|
||||
"bytes": 258665
|
||||
},
|
||||
{
|
||||
"key": "asdf_straight_origin0",
|
||||
"img": "asdf",
|
||||
"style": "straight",
|
||||
"style_idx": 4,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 24.0,
|
||||
"err": "",
|
||||
"out_w": 1248,
|
||||
"out_h": 1664,
|
||||
"bytes": 279883
|
||||
},
|
||||
{
|
||||
"key": "asdf_wave_default896",
|
||||
"img": "asdf",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "default896",
|
||||
"side_val": null,
|
||||
"ok": true,
|
||||
"elapsed": 11.9,
|
||||
"err": "",
|
||||
"out_w": 1254,
|
||||
"out_h": 1666,
|
||||
"bytes": 286515
|
||||
},
|
||||
{
|
||||
"key": "asdf_wave_origin0",
|
||||
"img": "asdf",
|
||||
"style": "wave",
|
||||
"style_idx": 5,
|
||||
"side": "origin0",
|
||||
"side_val": 0,
|
||||
"ok": true,
|
||||
"elapsed": 24.3,
|
||||
"err": "",
|
||||
"out_w": 1248,
|
||||
"out_h": 1664,
|
||||
"bytes": 295694
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""接口2 female 批量对比测试:4图 × 5发型 × 3分辨率档位 = 60次请求。
|
||||
串行执行,记录耗时与成败,结果图按 图_发型_档位 命名保存。
|
||||
用法: python3 batch_test.py
|
||||
支持断点续跑(progress.json);新增档位时只会补跑未完成项。
|
||||
"""
|
||||
import base64, csv, json, os, sys, time, traceback
|
||||
import requests
|
||||
|
||||
API = "http://127.0.0.1:8187/api/v1/hair/grow"
|
||||
TOKEN = "dev-shared-secret-2026"
|
||||
TIMEOUT = 600
|
||||
OUT = "/home/ubuntu/hair/image/compare_test/out"
|
||||
PROGRESS = "/home/ubuntu/hair/image/compare_test/progress.json"
|
||||
|
||||
IMG_DIR = "/home/ubuntu/hair/image"
|
||||
IMAGES = [
|
||||
("girl2", f"{IMG_DIR}/girl_img/girl2.jpg"),
|
||||
("girl5", f"{IMG_DIR}/girl_img/girl5.jpg"),
|
||||
("qwer", f"{IMG_DIR}/qwer.jpg"),
|
||||
("asdf", f"{IMG_DIR}/asdf.jpg"),
|
||||
]
|
||||
# female: 1=ellipse 2=flower 3=heart 4=straight 5=wave
|
||||
STYLES = [
|
||||
(1, "ellipse"), (2, "flower"), (3, "heart"), (4, "straight"), (5, "wave"),
|
||||
]
|
||||
# 三档: 默认896 / 显式1024 / 原图直送0
|
||||
SIDES = [
|
||||
("default896", None), # 不传 → 后端默认896
|
||||
("side1024", 1024), # 长边压到 1024
|
||||
("origin0", 0), # 原图直送
|
||||
]
|
||||
SIDE_LABEL = {
|
||||
"default896": "默认896",
|
||||
"side1024": "1024",
|
||||
"origin0": "原图0",
|
||||
}
|
||||
|
||||
def load_progress():
|
||||
if os.path.exists(PROGRESS):
|
||||
try:
|
||||
return json.load(open(PROGRESS))
|
||||
except Exception:
|
||||
pass
|
||||
return {"done": [], "results": []}
|
||||
|
||||
def save_progress(prog):
|
||||
json.dump(prog, open(PROGRESS, "w"), ensure_ascii=False, indent=1)
|
||||
|
||||
def run_one(img_name, img_path, style_idx, style_key, side_name, side_val):
|
||||
"""跑单次请求,返回 dict 结果。"""
|
||||
key = f"{img_name}_{style_key}_{side_name}"
|
||||
with open(img_path, "rb") as f:
|
||||
img_b64 = base64.b64encode(f.read()).decode()
|
||||
data = {
|
||||
"image_base64": "data:image/jpeg;base64," + img_b64,
|
||||
"gender": "female",
|
||||
"hair_style": str(style_idx),
|
||||
}
|
||||
if side_val is not None:
|
||||
data["redraw_max_side"] = str(side_val)
|
||||
t0 = time.time()
|
||||
rec = {"key": key, "img": img_name, "style": style_key, "style_idx": style_idx,
|
||||
"side": side_name, "side_val": side_val, "ok": False,
|
||||
"elapsed": 0.0, "err": "", "out_w": 0, "out_h": 0}
|
||||
try:
|
||||
r = requests.post(API, data=data, headers={"X-Internal-Token": TOKEN}, timeout=TIMEOUT)
|
||||
rec["elapsed"] = round(time.time() - t0, 1)
|
||||
d = r.json()
|
||||
if d.get("code") != 0:
|
||||
rec["err"] = f"code={d.get('code')} {d.get('message','')}"[:200]
|
||||
return rec
|
||||
results = (d.get("data") or {}).get("results") or []
|
||||
if not results:
|
||||
rec["err"] = "空结果"
|
||||
return rec
|
||||
it = results[0]
|
||||
grown = it.get("grown_image_base64")
|
||||
if not grown:
|
||||
rec["err"] = "无生发图(grown_png=None, 重绘失败)"
|
||||
return rec
|
||||
raw = base64.b64decode(grown)
|
||||
from PIL import Image
|
||||
import io as _io
|
||||
im = Image.open(_io.BytesIO(raw))
|
||||
rec["out_w"], rec["out_h"] = im.size
|
||||
out_path = f"{OUT}/{key}.jpg"
|
||||
with open(out_path, "wb") as fo:
|
||||
fo.write(raw)
|
||||
rec["ok"] = True
|
||||
rec["bytes"] = len(raw)
|
||||
except requests.exceptions.Timeout:
|
||||
rec["elapsed"] = round(time.time() - t0, 1)
|
||||
rec["err"] = f"超时(>{TIMEOUT}s)"
|
||||
except Exception as e:
|
||||
rec["elapsed"] = round(time.time() - t0, 1)
|
||||
rec["err"] = f"{type(e).__name__}: {str(e)[:180]}"
|
||||
return rec
|
||||
|
||||
def main():
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
prog = load_progress()
|
||||
done_keys = set(prog["done"])
|
||||
total = len(IMAGES) * len(STYLES) * len(SIDES)
|
||||
print(f"=== 接口2 female 批量对比测试 ===")
|
||||
print(f"矩阵: {len(IMAGES)}图 × {len(STYLES)}发型 × {len(SIDES)}档 = {total} 次")
|
||||
print(f"已跳过 {len(done_keys)} 个已完成项\n")
|
||||
|
||||
idx = 0
|
||||
for img_name, img_path in IMAGES:
|
||||
for style_idx, style_key in STYLES:
|
||||
for side_name, side_val in SIDES:
|
||||
idx += 1
|
||||
key = f"{img_name}_{style_key}_{side_name}"
|
||||
if key in done_keys:
|
||||
print(f"[{idx}/{total}] ⏭ 跳过已完成 {key}")
|
||||
continue
|
||||
print(f"[{idx}/{total}] ▶ {key} (side={side_val})...", end=" ", flush=True)
|
||||
rec = run_one(img_name, img_path, style_idx, style_key, side_name, side_val)
|
||||
prog["results"].append(rec)
|
||||
prog["done"].append(key)
|
||||
save_progress(prog)
|
||||
if rec["ok"]:
|
||||
print(f"✅ {rec['elapsed']}s 出图 {rec['out_w']}x{rec['out_h']} ({rec['bytes']}B)")
|
||||
else:
|
||||
print(f"❌ {rec['elapsed']}s {rec['err']}")
|
||||
time.sleep(2) # 串行间隔,避免队列堆积
|
||||
|
||||
# 汇总
|
||||
print("\n" + "="*70)
|
||||
print("汇总报告")
|
||||
print("="*70)
|
||||
write_report(prog["results"])
|
||||
print(f"\n结果图: {OUT}/")
|
||||
print(f"CSV报告: {OUT}/report.csv")
|
||||
print(f"JSON明细: {OUT}/report.json")
|
||||
|
||||
def write_report(results):
|
||||
# CSV
|
||||
csv_path = f"{OUT}/report.csv"
|
||||
with open(csv_path, "w", newline="") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["img","style","side","ok","elapsed_s","out_w","out_h","err"])
|
||||
for r in results:
|
||||
w.writerow([r["img"],r["style"],r["side"],r["ok"],r["elapsed"],
|
||||
r["out_w"],r["out_h"],r["err"]])
|
||||
# JSON
|
||||
json.dump(results, open(f"{OUT}/report.json","w"), ensure_ascii=False, indent=1)
|
||||
# 控制台速度对比表
|
||||
print("\n--- 速度对比(秒,✓=成功 ✗=失败)---")
|
||||
headers = ["图", "发型"] + [SIDE_LABEL[s] for s, _ in SIDES]
|
||||
print(f"{headers[0]:<8}{headers[1]:<10}" + "".join(f"{h:>12}" for h in headers[2:]))
|
||||
for img_name, _ in IMAGES:
|
||||
for _, style_key in STYLES:
|
||||
cells = []
|
||||
for side_name, _ in SIDES:
|
||||
r = next((x for x in results if x["img"]==img_name and x["style"]==style_key and x["side"]==side_name), None)
|
||||
cells.append(f"{r['elapsed']}{'✓' if r['ok'] else '✗'}" if r else "-")
|
||||
print(f"{img_name:<8}{style_key:<10}" + "".join(f"{c:>12}" for c in cells))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把 report.json + 结果图生成为自包含 HTML 报告(支持 896 / 1024 / 原图0 三档)。"""
|
||||
import json, os, html
|
||||
|
||||
OUT = "/home/ubuntu/hair/image/compare_test/out"
|
||||
REPORT_HTML = os.path.join(OUT, "report.html")
|
||||
results = json.load(open(os.path.join(OUT, "report.json")))
|
||||
|
||||
IMAGES = ["girl2", "girl5", "qwer", "asdf"]
|
||||
STYLES = ["ellipse", "flower", "heart", "straight", "wave"]
|
||||
SIDES = [
|
||||
("default896", "默认 896", "#2563eb", "d"),
|
||||
("side1024", "1024", "#10b981", "m"),
|
||||
("origin0", "原图直送 0", "#f59e0b", "o"),
|
||||
]
|
||||
IMG_LONGSIDE = {"girl2": 1082, "girl5": 767, "qwer": 1678, "asdf": 1666}
|
||||
STYLE_CN = {"ellipse": "椭圆", "flower": "花瓣", "heart": "心形", "straight": "直线", "wave": "波浪"}
|
||||
|
||||
def get(img, style, side):
|
||||
for r in results:
|
||||
if r["img"] == img and r["style"] == style and r["side"] == side:
|
||||
return r
|
||||
return None
|
||||
|
||||
# 总览统计(>60s 视为冷启动/异常,不进均值)
|
||||
total = len(results)
|
||||
ok = sum(1 for r in results if r["ok"])
|
||||
COLD_S = 60.0
|
||||
|
||||
def avg(seq):
|
||||
seq = [x for x in seq if x is not None]
|
||||
return sum(seq) / len(seq) if seq else 0
|
||||
|
||||
def times(side, img=None):
|
||||
out = []
|
||||
for r in results:
|
||||
if not r["ok"] or r["side"] != side:
|
||||
continue
|
||||
if img is not None and r["img"] != img:
|
||||
continue
|
||||
if r["elapsed"] >= COLD_S:
|
||||
continue
|
||||
out.append(r["elapsed"])
|
||||
return out
|
||||
|
||||
cold_n = sum(1 for r in results if r["ok"] and r["elapsed"] >= COLD_S)
|
||||
side_avgs = {sid: avg(times(sid)) for sid, *_ in SIDES}
|
||||
all_times = [t for sid, *_ in SIDES for t in times(sid)]
|
||||
max_bar = max(all_times + [1])
|
||||
|
||||
# 构造速度对比图数据:每图 × 三档
|
||||
chart_rows = []
|
||||
for img in IMAGES:
|
||||
chart_rows.append((img, IMG_LONGSIDE[img], [avg(times(sid, img)) for sid, *_ in SIDES]))
|
||||
|
||||
def bar_svg():
|
||||
bar_h = 22
|
||||
gap = 12
|
||||
label_w = 78
|
||||
chart_w = 760
|
||||
n_bars = len(SIDES)
|
||||
rows = len(chart_rows)
|
||||
h = rows * (bar_h * n_bars + gap) + 40
|
||||
parts = [f'<svg viewBox="0 0 {label_w + chart_w + 80} {h}" class="chart">']
|
||||
y = 10
|
||||
for img, longside, avgs in chart_rows:
|
||||
base = avgs[0] if avgs and avgs[0] else 1
|
||||
for i, ((sid, label, color, _), a) in enumerate(zip(SIDES, avgs)):
|
||||
yi = y + i * bar_h
|
||||
w = int(a / max_bar * chart_w) if a else 0
|
||||
warn = "⚠" if (i > 0 and a > base * 1.8) else ""
|
||||
parts.append(f'<rect x="{label_w}" y="{yi}" width="{w}" height="{bar_h-4}" rx="3" fill="{color}"/>')
|
||||
parts.append(f'<text x="{label_w + w + 6}" y="{yi + bar_h - 10}" class="barlabel">{a:.1f}s {warn}</text>')
|
||||
parts.append(f'<text x="{label_w-8}" y="{yi + bar_h - 10}" class="rowlabel" text-anchor="end">{html.escape(label)}</text>')
|
||||
parts.append(f'<text x="0" y="{y + bar_h - 2}" class="imglabel">{img}<tspan class="imgside">长边{longside}</tspan></text>')
|
||||
y += bar_h * n_bars + gap
|
||||
parts.append("</svg>")
|
||||
return "".join(parts)
|
||||
|
||||
def img_cell(r, cls):
|
||||
if not r:
|
||||
return f'<td class="{cls} fail">缺失</td>'
|
||||
fname = r["key"] + ".jpg"
|
||||
status = "✅" if r["ok"] else "❌"
|
||||
t = f'{r["elapsed"]}s'
|
||||
dim = f'{r["out_w"]}×{r["out_h"]}'
|
||||
err = f'<div class="err">{html.escape(r["err"])}</div>' if r["err"] else ""
|
||||
img_tag = (f'<img loading="lazy" src="{fname}" onclick="openImg(this.src)" alt="{html.escape(r["key"])}">'
|
||||
if r["ok"] else '<div class="noimg">无图</div>')
|
||||
return (f'<td class="{cls}"><div class="thumb">{img_tag}</div>'
|
||||
f'<div class="meta">{status} {t} · {dim}</div>{err}</td>')
|
||||
|
||||
def compare_cards():
|
||||
out = []
|
||||
for img in IMAGES:
|
||||
out.append(f'<div class="card"><div class="card-h">📷 {html.escape(img)} <span class="tag">原图长边 {IMG_LONGSIDE[img]}px</span></div><div class="card-b">')
|
||||
heads = "".join(f'<th class="{cls}">{html.escape(label)}</th>' for _, label, _, cls in SIDES)
|
||||
out.append(f'<table class="cmp"><thead><tr><th>发型</th>{heads}</tr></thead><tbody>')
|
||||
for style in STYLES:
|
||||
sc = STYLE_CN[style]
|
||||
cells = "".join(img_cell(get(img, style, sid), cls) for sid, _, _, cls in SIDES)
|
||||
out.append(f'<tr><td class="sname">{html.escape(style)}<span>{sc}</span></td>{cells}</tr>')
|
||||
out.append("</tbody></table></div></div>")
|
||||
return "".join(out)
|
||||
|
||||
# 结论
|
||||
small = [img for img in IMAGES if IMG_LONGSIDE[img] <= 1100]
|
||||
large = [img for img in IMAGES if IMG_LONGSIDE[img] > 1100]
|
||||
def ratio_range(num_side, den_side="default896"):
|
||||
ratios = []
|
||||
for img in large:
|
||||
den = avg(times(den_side, img))
|
||||
num = avg(times(num_side, img))
|
||||
if den:
|
||||
ratios.append(num / den)
|
||||
if not ratios:
|
||||
return 0, 0
|
||||
return min(ratios), max(ratios)
|
||||
|
||||
r1024_lo, r1024_hi = ratio_range("side1024")
|
||||
r0_lo, r0_hi = ratio_range("origin0")
|
||||
cold_note = f"冷启动 {cold_n} 次(≥{COLD_S:.0f}s)已从均值剔除。" if cold_n else ""
|
||||
conclusion = (
|
||||
f"原图长边 ≤ 1100({'/'.join(small)})时三档耗时接近;"
|
||||
f"长边 > 1600({'/'.join(large)})时相对默认896:"
|
||||
f"<b>1024 约 {r1024_lo:.1f}~{r1024_hi:.1f}×</b>,"
|
||||
f"<b>原图直送约 {r0_lo:.1f}~{r0_hi:.1f}×</b>。"
|
||||
f"{cold_note}画质对比见下方三列并排,点击可放大。"
|
||||
)
|
||||
|
||||
avg896 = side_avgs.get("default896", 0)
|
||||
avg1024 = side_avgs.get("side1024", 0)
|
||||
avg0 = side_avgs.get("origin0", 0)
|
||||
ratio1024 = avg1024 / avg896 if avg896 else 0
|
||||
ratio0 = avg0 / avg896 if avg896 else 0
|
||||
|
||||
legend = "".join(
|
||||
f'<span><i style="background:{color}"></i>{html.escape(label)}</span>'
|
||||
for _, label, color, _ in SIDES
|
||||
)
|
||||
|
||||
html_doc = f"""<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>接口2 分辨率对比测试报告</title>
|
||||
<style>
|
||||
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
|
||||
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif; background: #f3f4f6; color: #1f2937; line-height: 1.5; padding: 20px; }}
|
||||
.wrap {{ max-width: 1400px; margin: 0 auto; }}
|
||||
h1 {{ font-size: 24px; margin-bottom: 4px; }}
|
||||
.sub {{ color: #6b7280; font-size: 13px; margin-bottom: 20px; }}
|
||||
.summary {{ display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; margin-bottom: 24px; }}
|
||||
.stat {{ background: #fff; border-radius: 10px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,.06); }}
|
||||
.stat .num {{ font-size: 26px; font-weight: 700; }}
|
||||
.stat .lbl {{ font-size: 12px; color: #6b7280; margin-top: 2px; }}
|
||||
.stat.d .num {{ color: #2563eb; }}
|
||||
.stat.m .num {{ color: #10b981; }}
|
||||
.stat.o .num {{ color: #f59e0b; }}
|
||||
.card {{ background: #fff; border-radius: 12px; box-shadow: 0 1px 4px rgba(0,0,0,.07); margin-bottom: 20px; overflow: hidden; }}
|
||||
.card-h {{ padding: 12px 18px; background: #fafafa; border-bottom: 1px solid #f0f0f0; font-weight: 700; font-size: 15px; display: flex; align-items: center; gap: 8px; }}
|
||||
.card-h .tag {{ font-size: 11px; font-weight: 500; color: #6b7280; background: #f3f4f6; padding: 2px 8px; border-radius: 10px; }}
|
||||
.card-b {{ padding: 16px; }}
|
||||
.chart {{ width: 100%; height: auto; max-width: 920px; }}
|
||||
.barlabel {{ font-size: 12px; fill: #374151; font-weight: 600; }}
|
||||
.rowlabel {{ font-size: 11px; fill: #6b7280; }}
|
||||
.imglabel {{ font-size: 14px; fill: #111; font-weight: 700; }}
|
||||
.imgside {{ font-size: 10px; fill: #9ca3af; font-weight: 400; }}
|
||||
table.cmp {{ width: 100%; border-collapse: collapse; table-layout: fixed; }}
|
||||
table.cmp th {{ font-size: 12px; color: #6b7280; font-weight: 600; padding: 8px; text-align: center; border-bottom: 2px solid #f0f0f0; }}
|
||||
table.cmp td {{ padding: 8px; border-bottom: 1px solid #f6f6f6; vertical-align: top; text-align: center; }}
|
||||
table.cmp th.d, table.cmp td.d {{ background: #eff6ff; }}
|
||||
table.cmp th.m, table.cmp td.m {{ background: #ecfdf5; }}
|
||||
table.cmp th.o, table.cmp td.o {{ background: #fffbeb; }}
|
||||
td.sname {{ font-weight: 600; text-align: left; width: 90px; }}
|
||||
td.sname span {{ display: block; font-size: 11px; color: #9ca3af; font-weight: 400; }}
|
||||
.thumb {{ background: #222; border-radius: 6px; overflow: hidden; margin-bottom: 4px; cursor: zoom-in; }}
|
||||
.thumb img {{ width: 100%; height: 200px; object-fit: contain; display: block; }}
|
||||
.noimg {{ color: #d1d5db; font-size: 12px; padding: 40px 0; }}
|
||||
.meta {{ font-size: 11px; color: #6b7280; }}
|
||||
.err {{ font-size: 10px; color: #dc2626; margin-top: 2px; }}
|
||||
.note {{ background: #fef3c7; border-left: 3px solid #f59e0b; padding: 12px 16px; border-radius: 6px; font-size: 13px; margin-bottom: 20px; }}
|
||||
.legend {{ display: flex; gap: 20px; font-size: 12px; color: #6b7280; margin-bottom: 12px; flex-wrap: wrap; }}
|
||||
.legend span {{ display: inline-flex; align-items: center; gap: 5px; }}
|
||||
.legend i {{ width: 12px; height: 12px; border-radius: 2px; display: inline-block; }}
|
||||
.overlay {{ display: none; position: fixed; inset: 0; background: rgba(0,0,0,.9); z-index: 999; justify-content: center; align-items: center; cursor: zoom-out; padding: 30px; }}
|
||||
.overlay.active {{ display: flex; }}
|
||||
.overlay img {{ max-width: 95%; max-height: 95%; object-fit: contain; border-radius: 4px; }}
|
||||
@media (max-width: 900px) {{
|
||||
.summary {{ grid-template-columns: repeat(2, 1fr); }}
|
||||
.thumb img {{ height: 160px; }}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<h1>接口2 生发 · 分辨率对比测试报告</h1>
|
||||
<p class="sub">POST /api/v1/hair/grow · female · 4 张图 × 5 发型 × 3 档分辨率 = {total} 次 · 串行</p>
|
||||
|
||||
<div class="summary">
|
||||
<div class="stat"><div class="num">{ok}/{total}</div><div class="lbl">成功 / 总数</div></div>
|
||||
<div class="stat d"><div class="num">{avg896:.1f}s</div><div class="lbl">默认896 平均</div></div>
|
||||
<div class="stat m"><div class="num">{avg1024:.1f}s</div><div class="lbl">1024 平均 · ×{ratio1024:.2f}</div></div>
|
||||
<div class="stat o"><div class="num">{avg0:.1f}s</div><div class="lbl">原图直送 平均 · ×{ratio0:.2f}</div></div>
|
||||
<div class="stat"><div class="num" style="color:{'#dc2626' if ratio0>1.3 else '#16a34a'}">×{ratio0:.2f}</div><div class="lbl">原图/默认 倍率</div></div>
|
||||
</div>
|
||||
|
||||
<div class="note">
|
||||
<b>结论:</b>{conclusion}
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-h">平均耗时对比(按图分组,单位:秒)</div>
|
||||
<div class="card-b">
|
||||
<div class="legend">{legend}</div>
|
||||
{bar_svg()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 style="font-size:18px;margin:8px 0 14px">画质对比(左→右:默认896 · 1024 · 原图直送)</h2>
|
||||
{compare_cards()}
|
||||
|
||||
</div>
|
||||
<div class="overlay" id="overlay" onclick="this.classList.remove('active')">
|
||||
<img id="overlayImg" src="">
|
||||
</div>
|
||||
<script>
|
||||
function openImg(src) {{
|
||||
document.getElementById('overlayImg').src = src;
|
||||
document.getElementById('overlay').classList.add('active');
|
||||
}}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
with open(REPORT_HTML, "w") as f:
|
||||
f.write(html_doc)
|
||||
# 同步首页
|
||||
with open(os.path.join(OUT, "index.html"), "w") as f:
|
||||
f.write(html_doc)
|
||||
print(f"已生成: {REPORT_HTML}")
|
||||
print(f"图片目录: {OUT}")
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=接口2 分辨率对比测试报告 HTTP 服务 (8848)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ubuntu
|
||||
WorkingDirectory=/home/ubuntu/hair/image/compare_test/out
|
||||
ExecStart=/home/ubuntu/miniconda3/envs/my_hair/bin/python -m http.server 8848 --bind 0.0.0.0
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
After Width: | Height: | Size: 243 KiB |
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 198 KiB |
|
After Width: | Height: | Size: 223 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 180 KiB |
|
After Width: | Height: | Size: 184 KiB |
|
After Width: | Height: | Size: 198 KiB |
|
After Width: | Height: | Size: 186 KiB |
|
After Width: | Height: | Size: 176 KiB |
|
After Width: | Height: | Size: 175 KiB |