Commit
·
83f52c2
1
Parent(s):
7e328d3
feat(api): add FastAPI server with hair swap endpoints and auth; update requirements
Browse files- requirements.txt +4 -1
- server.py +144 -0
requirements.txt
CHANGED
|
@@ -18,4 +18,7 @@ einops
|
|
| 18 |
kornia
|
| 19 |
matplotlib
|
| 20 |
imageio
|
| 21 |
-
imageio-ffmpeg
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
kornia
|
| 19 |
matplotlib
|
| 20 |
imageio
|
| 21 |
+
imageio-ffmpeg
|
| 22 |
+
fastapi>=0.110.0
|
| 23 |
+
uvicorn[standard]>=0.23.0
|
| 24 |
+
python-multipart
|
server.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import uuid
|
| 4 |
+
import logging
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, Depends, Header
|
| 8 |
+
from fastapi.responses import FileResponse, JSONResponse
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
from PIL import Image
|
| 14 |
+
|
| 15 |
+
from infer_full import StableHair
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
LOGGER = logging.getLogger("hair_server")
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
|
| 20 |
+
|
| 21 |
+
EXPECTED_BEARER = "logicgo@123"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def verify_bearer(authorization: Optional[str] = Header(None)):
|
| 25 |
+
if not authorization:
|
| 26 |
+
raise HTTPException(status_code=401, detail="Missing Authorization header")
|
| 27 |
+
try:
|
| 28 |
+
scheme, token = authorization.split(" ", 1)
|
| 29 |
+
except ValueError:
|
| 30 |
+
raise HTTPException(status_code=401, detail="Invalid Authorization header format")
|
| 31 |
+
if scheme.lower() != "bearer":
|
| 32 |
+
raise HTTPException(status_code=401, detail="Invalid auth scheme")
|
| 33 |
+
if token != EXPECTED_BEARER:
|
| 34 |
+
raise HTTPException(status_code=401, detail="Invalid token")
|
| 35 |
+
return True
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
app = FastAPI(title="Hair Swap API", version="1.0.0")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@app.get("/health")
|
| 42 |
+
def health():
|
| 43 |
+
return {"status": "healthy"}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class HairSwapRequest(BaseModel):
|
| 47 |
+
source_id: str
|
| 48 |
+
reference_id: str
|
| 49 |
+
converter_scale: float = 1.0
|
| 50 |
+
scale: float = 1.0
|
| 51 |
+
guidance_scale: float = 1.5
|
| 52 |
+
controlnet_conditioning_scale: float = 1.0
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Initialize model lazily on first request
|
| 56 |
+
_model: Optional[StableHair] = None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_model() -> StableHair:
|
| 60 |
+
global _model
|
| 61 |
+
if _model is None:
|
| 62 |
+
LOGGER.info("Loading StableHair model ...")
|
| 63 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 64 |
+
dtype = torch.float16 if device == "cuda" else torch.float32
|
| 65 |
+
_model = StableHair(config="./configs/hair_transfer.yaml", device=device, weight_dtype=dtype)
|
| 66 |
+
LOGGER.info("Model loaded")
|
| 67 |
+
return _model
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
UPLOAD_DIR = os.path.join(os.getcwd(), "uploads")
|
| 71 |
+
RESULTS_DIR = os.path.join(os.getcwd(), "results")
|
| 72 |
+
LOGS_DIR = os.path.join(os.getcwd(), "logs")
|
| 73 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 74 |
+
os.makedirs(RESULTS_DIR, exist_ok=True)
|
| 75 |
+
os.makedirs(LOGS_DIR, exist_ok=True)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@app.post("/upload")
|
| 79 |
+
async def upload_image(image: UploadFile = File(...), _=Depends(verify_bearer)):
|
| 80 |
+
if not image.filename:
|
| 81 |
+
raise HTTPException(status_code=400, detail="No file name provided")
|
| 82 |
+
contents = await image.read()
|
| 83 |
+
try:
|
| 84 |
+
Image.open(io.BytesIO(contents)).convert("RGB")
|
| 85 |
+
except Exception:
|
| 86 |
+
raise HTTPException(status_code=400, detail="Invalid image file")
|
| 87 |
+
|
| 88 |
+
image_id = str(uuid.uuid4())
|
| 89 |
+
ext = os.path.splitext(image.filename)[1] or ".png"
|
| 90 |
+
path = os.path.join(UPLOAD_DIR, image_id + ext)
|
| 91 |
+
with open(path, "wb") as f:
|
| 92 |
+
f.write(contents)
|
| 93 |
+
return {"id": image_id, "filename": os.path.basename(path)}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@app.post("/get-hairswap")
|
| 97 |
+
def get_hairswap(req: HairSwapRequest, _=Depends(verify_bearer)):
|
| 98 |
+
# Resolve file paths
|
| 99 |
+
def find_file(image_id: str) -> str:
|
| 100 |
+
for name in os.listdir(UPLOAD_DIR):
|
| 101 |
+
if name.startswith(image_id):
|
| 102 |
+
return os.path.join(UPLOAD_DIR, name)
|
| 103 |
+
raise HTTPException(status_code=404, detail=f"Image id not found: {image_id}")
|
| 104 |
+
|
| 105 |
+
source_path = find_file(req.source_id)
|
| 106 |
+
reference_path = find_file(req.reference_id)
|
| 107 |
+
|
| 108 |
+
model = get_model()
|
| 109 |
+
# Prepare kwargs similar to infer_full
|
| 110 |
+
id_np, out_np, bald_np, ref_np = model.Hair_Transfer(
|
| 111 |
+
source_image=source_path,
|
| 112 |
+
reference_image=reference_path,
|
| 113 |
+
random_seed=-1,
|
| 114 |
+
step=30,
|
| 115 |
+
guidance_scale=req.guidance_scale,
|
| 116 |
+
scale=req.scale,
|
| 117 |
+
controlnet_conditioning_scale=req.controlnet_conditioning_scale,
|
| 118 |
+
size=512,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Save result
|
| 122 |
+
result_id = str(uuid.uuid4())
|
| 123 |
+
out_img = Image.fromarray((out_np * 255.).astype(np.uint8))
|
| 124 |
+
filename = f"{result_id}.png"
|
| 125 |
+
out_path = os.path.join(RESULTS_DIR, filename)
|
| 126 |
+
out_img.save(out_path)
|
| 127 |
+
|
| 128 |
+
return {"result": filename}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@app.get("/download/{filename}")
|
| 132 |
+
def download(filename: str, _=Depends(verify_bearer)):
|
| 133 |
+
path = os.path.join(RESULTS_DIR, filename)
|
| 134 |
+
if not os.path.exists(path):
|
| 135 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 136 |
+
return FileResponse(path, media_type="image/png", filename=filename)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@app.get("/logs")
|
| 140 |
+
def logs(_=Depends(verify_bearer)):
|
| 141 |
+
# Simple in-memory/log-file placeholder
|
| 142 |
+
return JSONResponse({"logs": ["service running"]})
|
| 143 |
+
|
| 144 |
+
|