Spaces:
Running
Run swaps as background jobs, and add a Head Swap toggle to the app page
Browse filesFull-quality output takes minutes on the free CPU tier — head super-resolution
alone is ~6 minutes — which no HTTP request survives. /api/swap now validates
and decodes the inputs, then returns 202 with a job_id; the pipeline runs on a
worker thread and /api/swap/status/<job_id> reports real progress and finally
the result, in the same shape the synchronous endpoint returned.
Jobs run one at a time: the Space has 2 vCPUs that the models already saturate,
so overlapping swaps would just make each one slower. Results hold multi-MB
base64 images, so finished jobs expire after 20 minutes and the store is capped.
The pipeline moved into _perform_swap(), which takes plain options instead of
reading request.form and raises SwapError for input problems, so it no longer
depends on a request context.
The progress bar now follows the server's real stage instead of a timer that
animated a guess. The motivational captions still rotate on their own — the wait
is longer now, so there's more of it to fill, not less.
Head Swap is exposed as a toggle in the top-right corner of the app page,
mirroring the Home button. It transplants the whole head (shape + hair) rather
than just the inner face. Off by default, since it changes much more of the
photo.
Verified end-to-end against a local server: submit returns in 1.6s, progress
reports 2 -> 28 -> 40 -> 50 -> 78 -> 88 -> done, and both head_swap=0 and
head_swap=1 complete (alignment 92.4 / 92.1, blend 93.7, naturalness 98.0).
Frontend builds; 14 tests pass.
Files changed (2)
- frontend/src/pages/AppPage.jsx+70-10
- web_app.py+158-19
174 unmodified lines17517617717817918090 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030136 unmodified lines338339340341342343174 unmodified linesconst [stream, setStream] = useState(null);const [camActive, setCamActive] = useState(false);const [swapping, setSwapping] = useState(false);const [progress, setProgress] = useState(0);const [pLabel, setPLabel] = useState('');90 unmodified linesif (!srcFile && !srcB64) return setToast('Please provide your photo.');if (!location) return setToast('Please choose a location.');setSwapping(true); setResult(null); setProgress(5); setPLabel('Initialising...');let idx = 0;const timer = setInterval(() => {if (idx < STAGES.length) { const [p,l] = STAGES[idx++]; setProgress(p); setPLabel(l); }}, 1100);const fd = new FormData();if (srcFile) fd.append('source_file', srcFile); else fd.append('source_b64', srcB64);fd.append('name', name.trim());fd.append('gender', gender);fd.append('location', location);try {const resp = await fetch('/api/swap', { method: 'POST', body: fd });const text = await resp.text();let data;try { data = JSON.parse(text); }catch { throw new Error(`Server error ${resp.status}: ${text.slice(0, 120)}`); }clearInterval(timer);if (!data.ok) { setToast(data.error || 'Swap failed.'); setSwapping(false); return; }setProgress(100); setPLabel('Done!');setTimeout(() => { setResult(data); setSwapping(false); }, 400);} catch (e) {clearInterval(timer);setToast('Network error: ' + e.message);setSwapping(false);}36 unmodified linesHome</button><main className="flex-1 w-full max-w-5xl mx-auto px-3 sm:px-6 pt-14 sm:pt-16 pb-6 flex flex-col gap-3.5 sm:gap-4">{/* ── PAGE HEADER ──────────────────────────────────────────────── */}174 unmodified lines17517617717817918018118218318418590 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633736 unmodified lines374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403174 unmodified linesconst [stream, setStream] = useState(null);const [camActive, setCamActive] = useState(false);// Head swap transplants the source's whole head — shape + hair — instead of// only the inner face, then blends hair, neck and background into the scene.// Off by default: it changes more of the photo, so it's a deliberate choice.const [headSwap, setHeadSwap] = useState(false);const [swapping, setSwapping] = useState(false);const [progress, setProgress] = useState(0);const [pLabel, setPLabel] = useState('');90 unmodified linesif (!srcFile && !srcB64) return setToast('Please provide your photo.');if (!location) return setToast('Please choose a location.');setSwapping(true); setResult(null); setProgress(2); setPLabel(STAGES[0][1]);// The progress BAR tracks the server's real stage, but the caption keeps// cycling the motivational copy — the swap now runs for minutes, so there's// more of that wait to fill, not less.let msgIdx = 0;const msgTimer = setInterval(() => {msgIdx = (msgIdx + 1) % STAGES.length;setPLabel(STAGES[msgIdx][1]);}, 4000);const fd = new FormData();if (srcFile) fd.append('source_file', srcFile); else fd.append('source_b64', srcB64);fd.append('name', name.trim());fd.append('gender', gender);fd.append('location', location);fd.append('head_swap', headSwap ? '1' : '0');try {// The full-quality pipeline runs for minutes on the free CPU tier, far// longer than a request can stay open, so the server hands back a job id// and we poll it for real progress instead of animating a guess.const resp = await fetch('/api/swap', { method: 'POST', body: fd });const text = await resp.text();let data;try { data = JSON.parse(text); }catch { throw new Error(`Server error ${resp.status}: ${text.slice(0, 120)}`); }if (!data.ok || !data.job_id) {clearInterval(msgTimer);setToast(data.error || 'Swap failed.'); setSwapping(false); return;}const jobId = data.job_id;for (;;) {await new Promise(r => setTimeout(r, 2000));let s;try {const sr = await fetch(`/api/swap/status/${jobId}`, { cache: 'no-store' });s = await sr.json();} catch {continue; // transient network blip — keep polling}if (s.state === 'error' || s.ok === false) {clearInterval(msgTimer);setToast(s.error || 'Swap failed.'); setSwapping(false); return;}if (s.state === 'done') {clearInterval(msgTimer);setProgress(100); setPLabel('Done!');setTimeout(() => { setResult(s); setSwapping(false); }, 400);return;}if (typeof s.progress === 'number') setProgress(s.progress);}} catch (e) {clearInterval(msgTimer);setToast('Network error: ' + e.message);setSwapping(false);}36 unmodified linesHome</button>{/* Head Swap toggle — opposite corner to Home. Swaps the whole head(shape + hair) instead of just the face, blending hair, neck andbackground into the scene. */}<button onClick={() => setHeadSwap(v => !v)} disabled={swapping}title={headSwap? 'Head swap ON - transplants your whole head (shape + hair) and blends hair, neck and background': 'Head swap OFF - swaps the face only, keeping the photo\'s hair'}aria-pressed={headSwap}className={`absolute top-4 right-4 sm:top-6 sm:right-6 z-50 flex items-center gap-2 text-xs sm:text-sm rounded-lg px-3 sm:px-4 py-1.5 sm:py-2 border backdrop-blur-md transition-all duration-200 whitespace-nowrap font-bold shadow-sm hover:shadow disabled:opacity-50 disabled:cursor-not-allowed ${headSwap? 'bg-teal text-white border-teal hover:bg-teal-dark': 'bg-white/90 text-navy border-border/60 hover:border-teal/50 hover:bg-white'}`}><svg className={`w-4 h-4 shrink-0 ${headSwap ? 'text-white' : 'text-teal'}`}fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M5.5 21a6.5 6.5 0 0 1 13 0"/></svg>Head Swap<span className={`ml-0.5 text-[10px] font-extrabold rounded px-1.5 py-0.5 ${headSwap ? 'bg-white/25 text-white' : 'bg-bg3 text-slate'}`}>{headSwap ? 'ON' : 'OFF'}</span></button><main className="flex-1 w-full max-w-5xl mx-auto px-3 sm:px-6 pt-14 sm:pt-16 pb-6 flex flex-col gap-3.5 sm:gap-4">{/* ── PAGE HEADER ──────────────────────────────────────────────── */}
14 unmodified lines151617181920586 unmodified lines60760860961061161261361461561661761861962062138 unmodified lines66066166266366466566666723 unmodified lines69169269369469569669769869970070170270370470570670770870971071128 unmodified lines7407417427437447457463 unmodified lines7507517527537547557567577581 unmodified line7607617627637647659 unmodified lines77577677777877978078112 unmodified lines7947957967977987998003 unmodified lines8048058068078088095 unmodified lines81581681781881982043 unmodified lines86486586686786886911 unmodified lines8818828838848858861 unmodified line8888898908918928938948951 unmodified line89789889990090190290390490590690790814 unmodified linesos.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")import ioimport reimport base64import threadingimport traceback586 unmodified linesreturn jsonify({"ok": False, "error": str(e)}), 500@app.route("/api/swap", methods=["POST"])def api_swap():"""Full face-swap pipeline: InsightFace swap → GFPGAN face restoration →RealESRGAN 4K upscale (for download).Accepts multipart/form-data:- source_file (file) OR source_b64 (string) - source face- target_file (file) - target faceReturns JSON with result_image (base64), quality metrics, delta_e."""try:# -- decode source ----------------------------------------------------38 unmodified linesif source is None or target is None:return jsonify({"ok": False, "error": "Could not decode one or both images"}), 400user_name = (request.form.get("name") or "").strip()# -- resize -----------------------------------------------------------# Working resolution: 1536 on GPU (sharper composite + better landmarks;# the RTX-class card handles it easily) and 1024 on CPU to stay fast.23 unmodified lines# -- enhance inputs (upscale small + GFPGAN restore) so detail isn't# lost through the pipeline; the output is enhanced again at the end.source = _enhance_input(source)target = _enhance_input(target)# -- face detection ---------------------------------------------------faces_src = _safe_detect(source)faces_tgt = _safe_detect(target)if not faces_src:return jsonify({"ok": False, "error":"No face detected in source image. Tips: ensure good lighting, ""face the camera directly, remove heavy occlusions (mask/sunglasses), ""and use a photo where the face is at least 10% of the frame."}), 400if not faces_tgt:return jsonify({"ok": False, "error":"No face detected in target image. Tips: ensure good lighting, ""face the camera directly, and use a clear frontal portrait."}), 400# -- warn on very small detected faces (quality will be poor) ---------warnings = []28 unmodified lines## 1. (optional) HEAD SWAP — transplant the source head shape+hair.base = targetif request.form.get("head_swap", "0") in ("1", "true", "on"):try:hs = full_head_swap(source, target)if hs is not None:3 unmodified lines# 2. FACE SWAP — the main event. Source identity onto the main face only# (background/poster faces are never swapped).swapped = swap_face_insightface(source, base)# 3. GFPGAN face restoration — recovers detail lost in the 128px swap.swapped = restore_faces(swapped)# 3b. Laplacian pyramid blend over the FACE-swap boundary — smooths the1 unmodified line# it composites the swapped FACE over the target everywhere else, so if# it ran after the hair it would overwrite the newly-transferred hair# (which lies outside the face mask) with the target's original hair.try:from core.segmentor import segment_hair_neck_skin_fmask = segment_hair_neck_skin(swapped).get("face_mask")9 unmodified lines# composites the FULL long hair back into the scene (the parse crop +# region clamp were widened so long hair is no longer cut off). ON by# default (set swap_hair=0 for a fast face-only swap).if request.form.get("swap_hair", "1") in ("1", "true", "on"):hf_portrait = Nonetry:hf_portrait = transfer_hair(face_bgr=swapped, shape_bgr=source,12 unmodified linesprint(f"[swap] hair compose error: {e}")# 6. Glasses (no-op if the source isn't wearing any).if request.form.get("keep_glasses", "1") in ("1", "true", "on"):try:swapped = transfer_glasses(swapped, source)except Exception as e:3 unmodified lines# visible skin (face + neck + arms + hands) to the SOURCE complexion;# clothes/background are excluded. Done AFTER the Laplacian blend so the# blend can't pull the face colour back toward the target's tone.try:swapped = match_skin_to_source(swapped, source, faces_src[0], faces_tgt[0], strength=0.925 unmodified lines# Scored BEFORE step 8 below: that step adds deliberate grain/noise for# visual realism, which would otherwise inflate the noise/discontinuity# penalties in compute_quality_score and understate the swap's real quality.quality = compute_quality_score(swapped, target, None, None)# Real alignment: how closely the swapped face's 5 landmarks sit on the43 unmodified lines# 9. Paste the changed region back onto the FULL-RESOLUTION target so the# background and body keep the original photo's detail rather than the# downscaled-then-interpolated version. No-op if nothing was resized._work_h, _work_w = swapped.shape[:2]try:swapped = composite_onto_original(swapped, target, target_orig)11 unmodified lines_sr_bbox = (x1 * _fs, y1 * _fs, x2 * _fs, y2 * _fs)except Exception:passhi_res = upscale_image(swapped, scale=4, focus_bbox=_sr_bbox)# The 4K result is returned inline as a base64 data-URI so the user can1 unmodified line# server-side — nothing is written to disk (privacy + no disk growth).download_uri = _encode_image(hi_res, fmt="JPEG", quality=95)return jsonify({"ok": True,"result_image": _encode_image(swapped, fmt="JPEG", quality=92),"download_image": download_uri,"quality": quality,1 unmodified line"src_tone": src_tone,"tgt_tone": tgt_tone,"warnings": warnings,"name": user_name,})except Exception as e:traceback.print_exc()return jsonify({"ok": False, "error": str(e)}), 500def _prewarm_models():14 unmodified lines1516171819202122586 unmodified lines60961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472538 unmodified lines76476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379423 unmodified lines81881982082182282382482582682782882983083183283383483583683783883984028 unmodified lines8698708718728738748753 unmodified lines8798808818828838848858868878888891 unmodified line8918928938948958968979 unmodified lines90790890991091191291391412 unmodified lines9279289299309319329333 unmodified lines9379389399409419429435 unmodified lines94995095195295395495543 unmodified lines99910001001100210031004100511 unmodified lines10171018101910201021102210231 unmodified line102510261027102810291030103110321 unmodified line1034103510361037103810391040104110421043104410451046104714 unmodified linesos.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")import ioimport reimport timeimport uuidimport base64import threadingimport traceback586 unmodified linesreturn jsonify({"ok": False, "error": str(e)}), 500class SwapError(Exception):"""A user-facing problem with the inputs (no face found, undecodable, …)."""class _JobStore:"""Background jobs for /api/swap.The full-quality pipeline runs for minutes on the free CPU tier — headsuper-resolution alone is ~6 minutes — which no HTTP request survives. So aswap is submitted, run on a worker thread, and polled for.Jobs run ONE AT A TIME. The Space has 2 vCPUs and the models are alreadysaturating them; overlapping swaps would only make every one of them slower.Results hold multi-MB base64 images, so finished jobs are dropped after aTTL and the store is capped."""TTL_SECONDS = 20 * 60MAX_JOBS = 40def __init__(self):self._jobs = {}self._lock = threading.Lock()self._run_lock = threading.Lock() # serialises the actual workdef _prune(self):now = time.time()stale = [k for k, j in self._jobs.items()if now - j["updated"] > self.TTL_SECONDS]for k in stale:self._jobs.pop(k, None)if len(self._jobs) > self.MAX_JOBS:for k in sorted(self._jobs, key=lambda k: self._jobs[k]["updated"])[:len(self._jobs) - self.MAX_JOBS]:self._jobs.pop(k, None)def submit(self, source, target, opts):job_id = uuid.uuid4().hexwith self._lock:self._prune()self._jobs[job_id] = {"state": "queued", "progress": 0,"message": "Queued…", "result": None,"error": None, "updated": time.time()}threading.Thread(target=self._run, args=(job_id, source, target, opts),daemon=True).start()return job_iddef _set(self, job_id, **kw):with self._lock:job = self._jobs.get(job_id)if job is not None:job.update(kw)job["updated"] = time.time()def _run(self, job_id, source, target, opts):def progress(pct, msg):self._set(job_id, state="running", progress=int(pct), message=msg)with self._run_lock:try:progress(2, "Starting…")result = _perform_swap(source, target, opts, progress)self._set(job_id, state="done", progress=100,message="Done", result=result)except SwapError as e:self._set(job_id, state="error", message=str(e), error=str(e))except Exception as e:traceback.print_exc()self._set(job_id, state="error", message=str(e), error=str(e))def get(self, job_id):with self._lock:job = self._jobs.get(job_id)return dict(job) if job else None_jobs = _JobStore()@app.route("/api/swap/status/<job_id>", methods=["GET"])def api_swap_status(job_id):"""Poll a submitted swap. While running returns state/progress/message; oncedone the full result is returned in the same shape the old synchronous/api/swap used, so the client renders it identically."""job = _jobs.get(job_id)if job is None:return jsonify({"ok": False, "error": "Unknown or expired job."}), 404if job["state"] == "done":resp = jsonify({"ok": True, "state": "done", "progress": 100,**(job["result"] or {})})elif job["state"] == "error":resp = jsonify({"ok": False, "state": "error","error": job["error"] or "Swap failed."})else:resp = jsonify({"ok": True, "state": job["state"],"progress": job["progress"], "message": job["message"]})resp.headers["Cache-Control"] = "no-store"return resp@app.route("/api/swap", methods=["POST"])def api_swap():"""Submit a face swap. Returns 202 with a job_id — poll/api/swap/status/<job_id> for progress and the result.Accepts multipart/form-data:- source_file (file) OR source_b64 (string) - source face- target_file (file) OR gender + location - target scene"""try:# -- decode source ----------------------------------------------------38 unmodified linesif source is None or target is None:return jsonify({"ok": False, "error": "Could not decode one or both images"}), 400opts = {"name": (request.form.get("name") or "").strip(),"head_swap": request.form.get("head_swap", "0"),"swap_hair": request.form.get("swap_hair", "1"),"keep_glasses": request.form.get("keep_glasses", "1"),}job_id = _jobs.submit(source, target, opts)return jsonify({"ok": True, "job_id": job_id, "state": "queued"}), 202except Exception as e:traceback.print_exc()return jsonify({"ok": False, "error": str(e)}), 500def _perform_swap(source, target, opts, progress=None):"""The swap pipeline. Runs on a worker thread with no request context, so ittakes plain options and returns a plain dict; input problems raiseSwapError. `progress(pct, message)` drives the client's progress bar."""def note(pct, msg):if progress:progress(pct, msg)try:# -- resize -----------------------------------------------------------# Working resolution: 1536 on GPU (sharper composite + better landmarks;# the RTX-class card handles it easily) and 1024 on CPU to stay fast.23 unmodified lines# -- enhance inputs (upscale small + GFPGAN restore) so detail isn't# lost through the pipeline; the output is enhanced again at the end.note(8, "Preparing images…")source = _enhance_input(source)target = _enhance_input(target)# -- face detection ---------------------------------------------------note(15, "Detecting faces…")faces_src = _safe_detect(source)faces_tgt = _safe_detect(target)if not faces_src:raise SwapError("No face detected in source image. Tips: ensure good lighting, ""face the camera directly, remove heavy occlusions (mask/sunglasses), ""and use a photo where the face is at least 10% of the frame.")if not faces_tgt:raise SwapError("No face detected in target image. Tips: ensure good lighting, ""face the camera directly, and use a clear frontal portrait.")# -- warn on very small detected faces (quality will be poor) ---------warnings = []28 unmodified lines## 1. (optional) HEAD SWAP — transplant the source head shape+hair.base = targetif opts.get("head_swap", "0") in ("1", "true", "on"):try:hs = full_head_swap(source, target)if hs is not None:3 unmodified lines# 2. FACE SWAP — the main event. Source identity onto the main face only# (background/poster faces are never swapped).note(28, "Swapping face…")swapped = swap_face_insightface(source, base)# 3. GFPGAN face restoration — recovers detail lost in the 128px swap.note(40, "Restoring facial detail…")swapped = restore_faces(swapped)# 3b. Laplacian pyramid blend over the FACE-swap boundary — smooths the1 unmodified line# it composites the swapped FACE over the target everywhere else, so if# it ran after the hair it would overwrite the newly-transferred hair# (which lies outside the face mask) with the target's original hair.note(50, "Blending the seam…")try:from core.segmentor import segment_hair_neck_skin_fmask = segment_hair_neck_skin(swapped).get("face_mask")9 unmodified lines# composites the FULL long hair back into the scene (the parse crop +# region clamp were widened so long hair is no longer cut off). ON by# default (set swap_hair=0 for a fast face-only swap).if opts.get("swap_hair", "1") in ("1", "true", "on"):note(58, "Transferring hair…")hf_portrait = Nonetry:hf_portrait = transfer_hair(face_bgr=swapped, shape_bgr=source,12 unmodified linesprint(f"[swap] hair compose error: {e}")# 6. Glasses (no-op if the source isn't wearing any).if opts.get("keep_glasses", "1") in ("1", "true", "on"):try:swapped = transfer_glasses(swapped, source)except Exception as e:3 unmodified lines# visible skin (face + neck + arms + hands) to the SOURCE complexion;# clothes/background are excluded. Done AFTER the Laplacian blend so the# blend can't pull the face colour back toward the target's tone.note(72, "Matching skin tone…")try:swapped = match_skin_to_source(swapped, source, faces_src[0], faces_tgt[0], strength=0.925 unmodified lines# Scored BEFORE step 8 below: that step adds deliberate grain/noise for# visual realism, which would otherwise inflate the noise/discontinuity# penalties in compute_quality_score and understate the swap's real quality.note(78, "Scoring quality…")quality = compute_quality_score(swapped, target, None, None)# Real alignment: how closely the swapped face's 5 landmarks sit on the43 unmodified lines# 9. Paste the changed region back onto the FULL-RESOLUTION target so the# background and body keep the original photo's detail rather than the# downscaled-then-interpolated version. No-op if nothing was resized.note(84, "Restoring full-resolution background…")_work_h, _work_w = swapped.shape[:2]try:swapped = composite_onto_original(swapped, target, target_orig)11 unmodified lines_sr_bbox = (x1 * _fs, y1 * _fs, x2 * _fs, y2 * _fs)except Exception:passnote(88, "Enhancing to 4K (this is the slow part)…")hi_res = upscale_image(swapped, scale=4, focus_bbox=_sr_bbox)# The 4K result is returned inline as a base64 data-URI so the user can1 unmodified line# server-side — nothing is written to disk (privacy + no disk growth).download_uri = _encode_image(hi_res, fmt="JPEG", quality=95)note(100, "Done")return {"result_image": _encode_image(swapped, fmt="JPEG", quality=92),"download_image": download_uri,"quality": quality,1 unmodified line"src_tone": src_tone,"tgt_tone": tgt_tone,"warnings": warnings,"name": opts.get("name", ""),}except SwapError:raise # user-facing input problem — reported as-isexcept Exception:traceback.print_exc() # log where it actually broke, then surface itraisedef _prewarm_models():