Video_Face_swapping / face_swap.py
pulkitbuilds007's picture
Rename face_swap to face_swap.py
4737335 verified
Raw History Blame Contribute Delete
14.9 kB
"""Face Swap Pro: Hugging Face Space (Gradio) version of face_swap_pro.ipynb."""
import os, shutil, subprocess, tempfile, urllib.request, warnings
from types import SimpleNamespace
warnings.filterwarnings("ignore", category=FutureWarning)
import cv2
import numpy as np
import gradio as gr
import onnxruntime as ort
import insightface
from insightface.app import FaceAnalysis
from huggingface_hub import hf_hub_download
# ---------------- settings for the hosted app ----------------
MODELS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
MAX_SECONDS = float(os.environ.get("MAX_SECONDS", 8)) # longest clip processed
MAX_SIDE = int(os.environ.get("MAX_SIDE", 1280)) # larger frames are downscaled
DET_SIZE = (640, 640)
CROP = 512
os.makedirs(MODELS_DIR, exist_ok=True)
assert shutil.which("ffmpeg"), "ffmpeg not found (add it to packages.txt)."
# ---------------- model download ----------------
SWAP_MODEL = os.path.join(MODELS_DIR, "inswapper_128.onnx")
if not os.path.exists(SWAP_MODEL):
hf_hub_download(repo_id="ezioruan/inswapper_128.onnx", filename="inswapper_128.onnx",
local_dir=MODELS_DIR)
GH = "https://github.com/facefusion/facefusion-assets/releases/download"
HF = "https://huggingface.co/facefusion"
EXTRA = {"gfpgan_1.4.onnx": "models-3.0.0",
"xseg_1.onnx": "models-3.1.0",
"bisenet_resnet_34.onnx": "models-3.0.0"}
def download(name, tag):
dest = os.path.join(MODELS_DIR, name)
if os.path.exists(dest) and os.path.getsize(dest) > 1_000_000:
return dest
for url in (f"{GH}/{tag}/{name}", f"{HF}/{tag}/resolve/main/{name}"):
try:
tmp = dest + ".part"
urllib.request.urlretrieve(url, tmp)
if os.path.getsize(tmp) < 1_000_000:
raise IOError("downloaded file too small")
os.replace(tmp, dest)
return dest
except Exception as e:
print(f"failed {url}: {e}")
print(f"!! could not download {name}; that feature is disabled")
return None
for _n, _t in EXTRA.items():
download(_n, _t)
# ---------------- load models ----------------
if hasattr(ort, "preload_dlls"):
try:
ort.preload_dlls()
except Exception as e:
print("preload_dlls warning:", e)
def build(providers):
fa = FaceAnalysis(name="buffalo_l", providers=providers,
allowed_modules=["detection", "recognition"])
fa.prepare(ctx_id=0 if providers[0] != "CPUExecutionProvider" else -1, det_size=DET_SIZE)
sw = insightface.model_zoo.get_model(SWAP_MODEL, providers=providers)
return fa, sw
def selftest(fa, sw):
fa.det_model.detect(np.zeros((640, 640, 3), dtype=np.uint8), max_num=1)
feeds = {}
for inp in sw.session.get_inputs():
shape = [d if isinstance(d, int) else 1 for d in inp.shape]
feeds[inp.name] = np.zeros(shape, dtype=np.float32)
sw.session.run(None, feeds)
USING_GPU = False
if "CUDAExecutionProvider" in ort.get_available_providers():
try:
app, swapper = build(["CUDAExecutionProvider", "CPUExecutionProvider"])
selftest(app, swapper)
USING_GPU = True
except Exception as e:
print("GPU failed, using CPU:", str(e).splitlines()[-1][:300])
if not USING_GPU:
app, swapper = build(["CPUExecutionProvider"])
PROVIDERS = ["CUDAExecutionProvider", "CPUExecutionProvider"] if USING_GPU else ["CPUExecutionProvider"]
print("Running on:", "GPU (CUDA)" if USING_GPU else "CPU (slow)")
def load_optional(name):
path = os.path.join(MODELS_DIR, name)
if not os.path.exists(path):
return None
so = ort.SessionOptions()
so.log_severity_level = 3
return ort.InferenceSession(path, sess_options=so, providers=PROVIDERS)
enh_sess = load_optional("gfpgan_1.4.onnx")
occ_sess = load_optional("xseg_1.onnx")
parse_sess = load_optional("bisenet_resnet_34.onnx")
# ---------------- pipeline (from the notebook) ----------------
FFHQ_512 = np.array([[192.98138, 239.94708], [318.90277, 240.19360], [256.63416, 314.01935],
[201.26117, 371.41043], [313.08905, 371.15118]], dtype=np.float32)
PARSE_KEEP = [1, 2, 3, 4, 5, 6, 10, 11, 12, 13]
_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
def _to3(M):
return np.vstack([M, [0, 0, 1]]).astype(np.float64)
def ffhq_matrix(kps):
M, _ = cv2.estimateAffinePartial2D(kps.astype(np.float32), FFHQ_512, method=cv2.LMEDS)
return M
def enhance_face(img512):
x = img512[:, :, ::-1].astype(np.float32) / 255.0
x = ((x - 0.5) / 0.5).transpose(2, 0, 1)[None]
y = enh_sess.run(None, {enh_sess.get_inputs()[0].name: x})[0][0]
y = (np.clip(y, -1, 1) + 1) / 2
return (y.transpose(1, 2, 0) * 255.0).round().astype(np.uint8)[:, :, ::-1]
def _soft(m):
return (cv2.GaussianBlur(m.clip(0, 1), (0, 0), 5).clip(0.5, 1) - 0.5) * 2
def occlusion_mask(crop512):
x = cv2.resize(crop512, (256, 256))[None].astype(np.float32) / 255.0
m = occ_sess.run(None, {occ_sess.get_inputs()[0].name: x})[0][0, :, :, 0]
return _soft(cv2.resize(m, (CROP, CROP)))
def parser_mask(crop512):
x = cv2.resize(crop512, (512, 512))[:, :, ::-1].astype(np.float32) / 255.0
x = ((x - _MEAN) / _STD).transpose(2, 0, 1)[None].astype(np.float32)
out = parse_sess.run(None, {parse_sess.get_inputs()[0].name: x})[0][0]
m = np.isin(out.argmax(0), PARSE_KEEP).astype(np.float32)
return _soft(cv2.resize(m, (CROP, CROP)))
def box_mask(T, cfg):
inset = max(int(128 * cfg.box_inset), 1)
m = np.zeros((128, 128), np.float32)
m[inset:-inset, inset:-inset] = 1.0
m = cv2.warpAffine(m, T, (CROP, CROP), flags=cv2.INTER_LINEAR)
return cv2.GaussianBlur(m, (0, 0), max(CROP * 0.5 * cfg.feather * 0.25, 0.5))
def color_match(swapped, original, mask, strength):
reg = mask > 0.5
if reg.sum() < 2000:
return swapped
s = cv2.cvtColor(swapped.astype(np.float32) / 255.0, cv2.COLOR_BGR2LAB)
o = cv2.cvtColor(original.astype(np.float32) / 255.0, cv2.COLOR_BGR2LAB)
out = s.copy()
for c in range(3):
sm, ss = s[..., c][reg].mean(), s[..., c][reg].std() + 1e-6
om, os_ = o[..., c][reg].mean(), o[..., c][reg].std() + 1e-6
out[..., c] = (s[..., c] - sm) * np.clip(os_ / ss, 0.75, 1.25) + om
out = s + strength * (out - s)
return np.clip(cv2.cvtColor(out, cv2.COLOR_LAB2BGR) * 255.0, 0, 255).astype(np.uint8)
def paste(frame, face512, mask512, M):
H, W = frame.shape[:2]
IM = cv2.invertAffineTransform(M)
scale = float(np.sqrt(abs(np.linalg.det(IM[:, :2]))))
if scale < 0.7:
n = max(int(round(CROP * scale * 1.5)), 64)
face512 = cv2.resize(face512, (n, n), interpolation=cv2.INTER_AREA)
mask512 = cv2.resize(mask512, (n, n), interpolation=cv2.INTER_AREA)
IM = (_to3(IM) @ np.diag([CROP / n, CROP / n, 1.0]))[:2]
n = face512.shape[0]
corners = np.array([[0, 0], [n, 0], [n, n], [0, n]], np.float32)
pts = cv2.transform(corners[None], IM)[0]
x0, y0 = np.floor(pts.min(0)).astype(int)
x1, y1 = np.ceil(pts.max(0)).astype(int)
x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, W), min(y1, H)
if x1 - x0 < 2 or y1 - y0 < 2:
return frame
IMr = IM.copy()
IMr[0, 2] -= x0
IMr[1, 2] -= y0
size = (x1 - x0, y1 - y0)
f = cv2.warpAffine(face512, IMr, size, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
m = cv2.warpAffine(mask512, IMr, size, flags=cv2.INTER_LINEAR)[..., None]
roi = frame[y0:y1, x0:x1].astype(np.float32)
frame[y0:y1, x0:x1] = (roi * (1 - m) + f.astype(np.float32) * m).round().astype(np.uint8)
return frame
def swap_one(src_frame, out, face, src_face, cfg):
bgr_fake, M_arc = swapper.get(src_frame, face, src_face, paste_back=False)
M = ffhq_matrix(face.kps)
if M is None:
return out
T = (_to3(M) @ np.linalg.inv(_to3(M_arc)))[:2]
orig512 = cv2.warpAffine(src_frame, M, (CROP, CROP), flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REPLICATE)
swap512 = cv2.warpAffine(bgr_fake, T, (CROP, CROP), flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REPLICATE)
mask = box_mask(T, cfg)
if cfg.use_occluder and occ_sess is not None:
mask = np.minimum(mask, occlusion_mask(orig512))
if cfg.use_parser and parse_sess is not None:
mask = np.minimum(mask, parser_mask(orig512))
if cfg.color_strength > 0:
swap512 = color_match(swap512, orig512, mask, cfg.color_strength)
if cfg.use_enhancer and enh_sess is not None:
enh = enhance_face(swap512)
swap512 = cv2.addWeighted(enh, cfg.enhance_blend, swap512, 1 - cfg.enhance_blend, 0)
return paste(out, swap512, mask, M)
def smooth_kps(face, prev, new_prev, max_dim, smooth):
c = face.kps.mean(axis=0)
best, best_d = None, 1e9
for pk in prev:
d = np.linalg.norm(pk.mean(axis=0) - c)
if d < best_d:
best, best_d = pk, d
if best is not None and best_d < 0.15 * max_dim:
face.kps = smooth * best + (1 - smooth) * face.kps
new_prev.append(face.kps.copy())
def process_frame(frame, src_face, cfg, prev_kps):
out, new_prev, n = frame.copy(), [], 0
for face in app.get(frame):
if cfg.smooth > 0:
smooth_kps(face, prev_kps, new_prev, max(frame.shape[:2]), cfg.smooth)
out = swap_one(frame, out, face, src_face, cfg)
n += 1
return out, new_prev, n
def pick_encoder():
r = subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=c=black:s=256x256:d=0.1",
"-c:v", "h264_nvenc", "-f", "null", "-"], capture_output=True)
if r.returncode == 0:
return ["-c:v", "h264_nvenc", "-preset", "p5", "-rc", "vbr", "-cq", "18", "-b:v", "0"]
return ["-c:v", "libx264", "-preset", "veryfast", "-crf", "18"]
def fit(frame):
h, w = frame.shape[:2]
s = MAX_SIDE / max(h, w)
if s < 1:
frame = cv2.resize(frame, (int(w * s) // 2 * 2, int(h * s) // 2 * 2), interpolation=cv2.INTER_AREA)
return frame
# ---------------- Gradio handlers ----------------
def run(src_path, vid_path, consent, use_enhancer, enhance_blend, color_strength,
use_occluder, use_parser, feather, smooth, progress=gr.Progress()):
if not consent:
raise gr.Error("Please confirm consent before running.")
if src_path is None or vid_path is None:
raise gr.Error("Upload a source face image and an input video.")
src_img = cv2.imread(src_path)
if src_img is None:
raise gr.Error("Could not read the source image.")
faces = app.get(src_img)
if not faces:
raise gr.Error("No face found in the source image. Use a clear, front-facing photo.")
src_face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
cfg = SimpleNamespace(use_enhancer=use_enhancer, enhance_blend=enhance_blend,
color_strength=color_strength, use_occluder=use_occluder,
use_parser=use_parser, feather=feather, smooth=smooth, box_inset=0.10)
cap = cv2.VideoCapture(vid_path)
if not cap.isOpened():
raise gr.Error("Could not open the video.")
fps = cap.get(cv2.CAP_PROP_FPS) or 25
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
limit = int(fps * MAX_SECONDS)
total = min(total, limit) if total > 0 else limit
ok, frame = cap.read()
if not ok:
raise gr.Error("Could not read the first frame.")
frame = fit(frame)
h, w = frame.shape[:2]
out_path = os.path.join(tempfile.mkdtemp(), "output.mp4")
cmd = ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "bgr24",
"-s", f"{w}x{h}", "-framerate", f"{fps:.6f}", "-i", "-",
"-i", vid_path, "-map", "0:v:0", "-map", "1:a:0?",
"-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", *pick_encoder(),
"-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-shortest", out_path]
enc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL)
prev, n_frames = [], 0
try:
while True:
out, prev, _ = process_frame(frame, src_face, cfg, prev)
enc.stdin.write(np.ascontiguousarray(out).tobytes())
n_frames += 1
progress(n_frames / max(total, 1), desc=f"Frame {n_frames}/{total}")
if n_frames >= limit:
break
ok, frame = cap.read()
if not ok:
break
frame = fit(frame)
except BrokenPipeError:
raise gr.Error("ffmpeg stopped early.")
finally:
cap.release()
try:
enc.stdin.close()
except Exception:
pass
enc.wait()
if enc.returncode != 0:
raise gr.Error("Encoding failed.")
return out_path
with gr.Blocks(title="Face Swap Pro") as demo:
gr.Markdown(
"# Face Swap Pro\n"
f"Running on **{'GPU' if USING_GPU else 'CPU (slow)'}**. Clips are cut to the first "
f"{MAX_SECONDS:g} s and frames larger than {MAX_SIDE}px are downscaled.\n\n"
"Only use faces of people who have consented. Models are for non-commercial research use."
)
with gr.Row():
with gr.Column():
src = gr.Image(type="filepath", label="Source face (pasted INTO the video)")
vid = gr.Video(label="Input video")
with gr.Column():
res = gr.Video(label="Result")
consent = gr.Checkbox(label="I have consent from everyone whose face is used, and I will label the output as synthetic.")
with gr.Accordion("Quality settings", open=False):
use_enh = gr.Checkbox(value=enh_sess is not None, interactive=enh_sess is not None,
label="Face enhancer (GFPGAN)")
enh_blend = gr.Slider(0, 1, 0.8, step=0.05, label="Enhance blend (higher = sharper, lower = closer to raw swap)")
col = gr.Slider(0, 1, 0.8, step=0.05, label="Colour match strength")
use_occ = gr.Checkbox(value=occ_sess is not None, interactive=occ_sess is not None,
label="Occlusion mask (keeps hands, mics, glasses in front)")
use_par = gr.Checkbox(value=parse_sess is not None, interactive=parse_sess is not None,
label="Face parser (skip hair, hats, ears)")
feather = gr.Slider(0.1, 0.5, 0.3, step=0.05, label="Feather (raise if you see a seam)")
smooth = gr.Slider(0, 0.9, 0.6, step=0.05, label="Landmark smoothing")
btn = gr.Button("Swap faces", variant="primary")
btn.click(run, [src, vid, consent, use_enh, enh_blend, col, use_occ, use_par, feather, smooth], res)
demo.queue(max_size=5, default_concurrency_limit=1)
if __name__ == "__main__":
demo.launch()