#!/usr/bin/env bash
#
# 证件照换头 CLI - 调本地 InsightFace 服务
# 用法: ./headswap.sh <源图> <目标图> <输出图>
#   源图: 提供头的人;  目标图: 要换头的人
set -euo pipefail

SRC="${1:?用法: headswap.sh <源图> <目标图> [输出图]}"
DST="${2:?用法: headswap.sh <源图> <目标图> [输出图]}"
OUT="${3:-${DST%.*}_swapped.jpg}"

if [ ! -f "$SRC" ]; then echo "错误: 源图不存在 $SRC"; exit 1; fi
if [ ! -f "$DST" ]; then echo "错误: 目标图不存在 $DST"; exit 1; fi

python3 - "$SRC" "$DST" "$OUT" <<'PY'
import sys, base64, json, urllib.request, time

src, dst, out = sys.argv[1:4]

def b64(p):
    with open(p, 'rb') as f:
        return base64.b64encode(f.read()).decode()

req = urllib.request.Request(
    'http://127.0.0.1:7870/swap',
    data=json.dumps({'src_image': b64(src), 'dst_image': b64(dst)}).encode(),
    headers={'Content-Type': 'application/json'})
t0 = time.time()
resp = json.loads(urllib.request.urlopen(req, timeout=300).read())
if 'error' in resp:
    print('错误:', resp['error']); sys.exit(1)
with open(out, 'wb') as f:
    f.write(base64.b64decode(resp['image']))
print(f"完成: {out}  ({time.time()-t0:.1f}s)")
PY
