Spaces:
Running
Revert this session's changes back to the last known-good version
Browse filesRestores the tree to 4b38f72 exactly. The reported result was worse than the
version that was already working, across the swap output, the head swap and the
app generally, so the right move is to put the working version back rather than
keep patching on top of it.
Reverts, newest first:
f008eb7 head-swap pose gate + warnings in the UI
0ab4ea6 seam blend against base instead of target
b1cd367 workflow PDF + binary .gitattributes rules
f25d3bf glasses transfer made opt-in
74dd70d hair matte fix + removal of the crude hair fallback
b60d8aa background jobs + Head Swap toggle
ddb0022 head-only super-resolution
27e2136 composite onto the full-resolution original
9e549b6 grain confined to the parsed head
bb3e953 Control Panel sign-in inside the Hugging Face iframe
e522792 Flask debug off by default + threaded pre-warm
27bac33 scene-harmonisation regressions
Nothing is lost: each of the above is still in history and can be cherry-picked
back individually once we know which ones actually helped.
Files changed (9)
- .gitattributes-12
- core/head_swap.py+28-142
- core/super_res.py+23-73
- docs/WORKFLOW.pdfDeleted-175
- frontend/src/pages/AdminPage.jsx+7-51
- frontend/src/pages/AppPage.jsx+10-89
- scripts/make_workflow_pdf.pyDeleted-425
- utils/image_io.py-47
- web_app.py+40-248
12 unmodified lines13141516171819202122232425262712 unmodified lines*.md text eol=lf*.txt text eol=lfDockerfile text eol=lf# Never run line-ending conversion over binaries — it corrupts them. Git was# reporting "LF will be replaced by CRLF" for docs/WORKFLOW.pdf without this.*.pdf binary*.png binary*.jpg binary*.jpeg binary*.webp binary*.bmp binary*.ico binary*.onnx binary*.pth binary12 unmodified lines13141512 unmodified lines*.md text eol=lf*.txt text eol=lfDockerfile text eol=lf
121 unmodified lines122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157389 unmodified lines5475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835843 unmodified lines58858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062120 unmodified lines6426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816822 unmodified lines6856866876886896906916926936946956966976987 unmodified lines706707708709710711712713714715716717718719720721722723724725726121 unmodified linesreturn fullx1, y1, x2, y2 = [int(v) for v in bbox]bw, bh = x2 - x1, y2 - y1def _matte(up_, down_, side_):ex1 = max(0, x1 - int(bw * side_)); ey1 = max(0, y1 - int(bh * up_))ex2 = min(w, x2 + int(bw * side_)); ey2 = min(h, y2 + int(bh * down_))crop = image[ey1:ey2, ex1:ex2]if crop.size == 0:return Noneinp = cv2.resize(crop, (512, 512))rgb = cv2.cvtColor(inp, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0rgb = (rgb - 0.5) / 0.5t = torch.from_numpy(rgb.transpose(2, 0, 1)).unsqueeze(0).float().to(_device())with torch.no_grad():prob = torch.softmax(parser(t)[0], dim=1)[0, 17].cpu().numpy().astype(np.float32)out = np.zeros((h, w), np.float32)out[ey1:ey2, ex1:ex2] = cv2.resize(prob, (ex2 - ex1, ey2 - ey1))return out# The wide crop exists so long hair isn't cut off before parsing, but it# also shrinks the head inside the 512x512 parse input, and BiSeNet's hair# confidence falls with it. Measured on a 66x77 face: the wide crop peaks at# 0.341, leaving NOTHING above the 0.4 that swap_hair thresholds at, so the# hair mask came out empty and the transfer silently did nothing. So keep# the wide crop when it is confident, and tighten only when it is not.for factor in (1.0, 0.6, 0.38, 0.25):m = _matte(up * max(factor, 0.6), down * factor, side * factor)if m is None:continuefull = mif m.max() >= 0.5:breakreturn full389 unmodified linesh, w = result.shape[:2]res = result.astype(np.float32)# Grain must land on the HEAD, not on a rectangle around it. A box sprays# noise over whatever shares its bounds — background, shelves, clothing —# which dirties the scene and leaves the box's own feathered edge visible.# So parse the actual head/hair/neck shape and clamp it to a generous head# box, which keeps stray parse specks elsewhere from picking up grain.x1, y1, x2, y2 = [int(v) for v in face_bbox]bw, bh = x2 - x1, y2 - y1box = np.zeros((h, w), np.float32)rx1 = max(0, x1 - int(bw * 1.25)); ry1 = max(0, y1 - int(bh * 1.6))rx2 = min(w, x2 + int(bw * 1.25)); ry2 = min(h, y2 + int(bh * 3.0))box[ry1:ry2, rx1:rx2] = 1.0mask = Nonetry:# Same generous crop as the hair matte so long hair is parsed, not cut.# Class 18 (hat) is included HERE only: the parser labels part of the# hair as hat, and while that misfire matters when transferring hair# (_HEAD_CLASSES rightly drops it), leaving it out here punches an# ungrained hole in the top of the head.parsed = _parse_region_mask(result, face_bbox,_HEAD_CLASSES | _NECK_ONLY_CLASSES | {18},up=1.0, down=2.6, side=1.4)if parsed.max() > 0:mask = parsed * boxexcept Exception as e:print(f"[head_swap] harmonize parse failed, falling back to head box: {e}")if mask is None or mask.max() <= 0:mask = box# Small feather: enough to fade at the hairline, not so wide it bleeds the# grain back out into the scene the way the old box-sized blur did.mask = cv2.GaussianBlur(mask, (0, 0), max(1.5, min(h, w) * 0.006))m3 = mask[..., None]# (1) match the scene's grain (estimated from the target's high-freq luminance)3 unmodified lines2.5, 8.0)) * grainnoise = np.random.randn(h, w).astype(np.float32) * grain_stdres = res + noise[..., None] * m3except Exception as e:print(f"[head_swap] harmonize grain skipped: {e}")# (2) gentle colour-cast harmonisation: shift the head's mean toward the# scene's — sampled OUTSIDE the head mask (the surrounding scene), never from# inside it. `target` still shows the ORIGINAL target face (never overwritten# by the swap), so sampling the whole frame would pull the head's colour back# toward the target's own skin tone, undoing match_skin_to_source which runs# immediately before this step. LAB's L channel is darken-only, mirroring# _match_lighting's rule, so this can't wash hair/skin out to grey/silver# against a bright background.try:sel = mask > 0.4bg_sel = mask < 0.05if int(sel.sum()) > 200 and int(bg_sel.sum()) > 200:head_lab = cv2.cvtColor(np.clip(res, 0, 255).astype(np.uint8),cv2.COLOR_BGR2LAB).astype(np.float32)scene_lab = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(np.float32)head_mean = head_lab[sel].reshape(-1, 3).mean(0)scene_mean = scene_lab[bg_sel].reshape(-1, 3).mean(0)cast = np.zeros(3, np.float32)cast[0] = min(0.0, scene_mean[0] - head_mean[0]) * 0.35 # L: darken-onlycast[1:] = (scene_mean[1:] - head_mean[1:]) * 0.12 # a/b: gentle nudgeout_lab = head_lab + cast[None, None, :] * m3res = cv2.cvtColor(np.clip(out_lab, 0, 255).astype(np.uint8),cv2.COLOR_LAB2BGR).astype(np.float32)except Exception as e:print(f"[head_swap] harmonize colour-cast skipped: {e}")return np.clip(res, 0, 255).astype(np.uint8)20 unmodified linesreturn cv2.cvtColor(np.clip(out, 0, 255).astype(np.uint8), cv2.COLOR_LAB2BGR)#: Out-of-plane mismatch (degrees) past which a transplanted head reads as#: crooked. Warn above the first, refuse above the second.HEAD_POSE_WARN = 15.0HEAD_POSE_MAX = 25.0def head_pose_delta(source: np.ndarray, target: np.ndarray):"""(|d_pitch|, |d_yaw|) between the largest face in each image, or None if thedetector doesn't report pose.Roll is deliberately excluded: it is in-plane, and the similarity transformfull_head_swap fits already corrects it. Pitch and yaw are out-of-plane andit cannot — a head nodded down cannot be turned to face up by translating,rotating and scaling a flat image."""app = _get_insightface()if app is None:return Nonetry:area = lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])sfs, tfs = app.get(source), app.get(target)if not sfs or not tfs:return Nonesp = getattr(max(sfs, key=area), "pose", None)tp = getattr(max(tfs, key=area), "pose", None)if sp is None or tp is None:return Nonereturn abs(float(sp[0]) - float(tp[0])), abs(float(sp[1]) - float(tp[1]))except Exception:return Nonedef full_head_swap(source: np.ndarray, target: np.ndarray,feather: float = 0.012):"""Transplant the SOURCE's whole head — face SHAPE + skin + hair (+ glasses) —onto the target's body/scene. Unlike InsightFace (which keeps the target's2 unmodified linesproportions; only the head region is touched, so the BACKGROUND is untouched.Best when source and target face roughly the same way. Returns the compositedimage, or None if it can't (caller falls back to the face swap).Sharpness is bounded by the SOURCE photo. The head is warped by whateverscale maps the source's eyes/nose/mouth onto the target's, so a source whosehead is smaller than the target's gets upscaled and comes out visibly softerthan the surrounding photograph — measured at roughly 1.43x upscale for a66x77 source face against a 102x116 target one. A close, sharp source photois what makes this look right; no amount of blending recovers detail thatwas never captured."""app = _get_insightface()if app is None:7 unmodified linessf = max(src_faces, key=area)tf = max(tgt_faces, key=area)# Refuse when the two heads face different ways. The transform below is# a 2D similarity, so it can slide, spin and scale the source head but# cannot turn it: transplanting a head nodded down onto a body with its# chin up lands visibly crooked no matter how well the seam is blended.# Better to fall back to the clean face swap than to paste that.sp, tp = getattr(sf, "pose", None), getattr(tf, "pose", None)if sp is not None and tp is not None:d_pitch = abs(float(sp[0]) - float(tp[0]))d_yaw = abs(float(sp[1]) - float(tp[1]))if max(d_pitch, d_yaw) > HEAD_POSE_MAX:print(f"[head_swap] head angles too different "f"(pitch {d_pitch:.0f}deg, yaw {d_yaw:.0f}deg > {HEAD_POSE_MAX:.0f}) "f"— skipping head swap")return None# Similarity (no shear) keeps the source face SHAPE; aligns it to the# target's eyes/nose/mouth position, scale and rotation.M, _ = cv2.estimateAffinePartial2D(121 unmodified lines122123124125126127128129130131132133134135136137138139389 unmodified lines5295305315325335345355365375385395405413 unmodified lines54554654754854955055155255355455555655755855956056156256320 unmodified lines5845855865875885895905912 unmodified lines5945955965975985997 unmodified lines607608609610611612121 unmodified linesreturn fullx1, y1, x2, y2 = [int(v) for v in bbox]bw, bh = x2 - x1, y2 - y1ex1 = max(0, x1 - int(bw * side)); ey1 = max(0, y1 - int(bh * up))ex2 = min(w, x2 + int(bw * side)); ey2 = min(h, y2 + int(bh * down))crop = image[ey1:ey2, ex1:ex2]if crop.size == 0:return fullinp = cv2.resize(crop, (512, 512))rgb = cv2.cvtColor(inp, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0rgb = (rgb - 0.5) / 0.5t = torch.from_numpy(rgb.transpose(2, 0, 1)).unsqueeze(0).float().to(_device())with torch.no_grad():prob = torch.softmax(parser(t)[0], dim=1)[0, 17].cpu().numpy().astype(np.float32)full[ey1:ey2, ex1:ex2] = cv2.resize(prob, (ex2 - ex1, ey2 - ey1))return full389 unmodified linesh, w = result.shape[:2]res = result.astype(np.float32)x1, y1, x2, y2 = [int(v) for v in face_bbox]bw, bh = x2 - x1, y2 - y1mask = np.zeros((h, w), np.float32)rx1 = max(0, x1 - int(bw * 1.25)); ry1 = max(0, y1 - int(bh * 1.6))rx2 = min(w, x2 + int(bw * 1.25)); ry2 = min(h, y2 + int(bh * 1.2))mask[ry1:ry2, rx1:rx2] = 1.0mask = cv2.GaussianBlur(mask, (0, 0), max(2.0, min(h, w) * 0.02))m3 = mask[..., None]# (1) match the scene's grain (estimated from the target's high-freq luminance)3 unmodified lines2.5, 8.0)) * grainnoise = np.random.randn(h, w).astype(np.float32) * grain_stdres = res + noise[..., None] * m3except Exception:pass# (2) gentle colour-cast harmonisation: shift the head's mean toward the scene'stry:sel = mask > 0.4if int(sel.sum()) > 200:head_mean = res[sel].reshape(-1, 3).mean(0)scene_mean = target.astype(np.float32).reshape(-1, 3).mean(0)cast = (scene_mean - head_mean) * 0.12 # subtleres = res + cast[None, None, :] * m3except Exception:passreturn np.clip(res, 0, 255).astype(np.uint8)20 unmodified linesreturn cv2.cvtColor(np.clip(out, 0, 255).astype(np.uint8), cv2.COLOR_LAB2BGR)def full_head_swap(source: np.ndarray, target: np.ndarray,feather: float = 0.025):"""Transplant the SOURCE's whole head — face SHAPE + skin + hair (+ glasses) —onto the target's body/scene. Unlike InsightFace (which keeps the target's2 unmodified linesproportions; only the head region is touched, so the BACKGROUND is untouched.Best when source and target face roughly the same way. Returns the compositedimage, or None if it can't (caller falls back to the face swap)."""app = _get_insightface()if app is None:7 unmodified linessf = max(src_faces, key=area)tf = max(tgt_faces, key=area)# Similarity (no shear) keeps the source face SHAPE; aligns it to the# target's eyes/nose/mouth position, scale and rotation.M, _ = cv2.estimateAffinePartial2D(
128 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219128 unmodified linesdef upscale_image(image: np.ndarray, scale: int = 4,realesrgan_weight: float = 0.5,focus_bbox=None) -> np.ndarray:"""Upscale ~scale x for the high-resolution download.RealESRGAN adds resolution but, being a general-purpose model, it over-sharpensskin into a plastic/waxy texture on faces. So we BLEND it with a plain Lanczosupscale (realesrgan_weight controls the mix: 0 = pure natural Lanczos, 1 = fullRealESRGAN) — keeping most of the detail while killing the artificial texture.focus_bbox restricts RealESRGAN to the head region. Everything outside it isnow composited from the untouched full-resolution target (seeutils.image_io.composite_onto_original), so only the head — which camethrough the swap's 128x128 bottleneck — has detail worth reconstructing.That matters most on CPU: measured on this pipeline a full 1.57MP frametakes ~20 minutes, while the head crop alone is seconds, which is what makesreal super-resolution affordable on the free CPU tier instead of GPU-only.Passing no bbox on CPU keeps the old Lanczos-only behaviour."""h, w = image.shape[:2]lanczos = cv2.resize(image, (w * scale, h * scale),interpolation=cv2.INTER_LANCZOS4)on_gpu = _device() == "cuda"if not on_gpu and focus_bbox is None:print(f"[super_res] Lanczos {scale}x -> {w*scale}x{h*scale}")return lanczosupsampler = _load_realesrgan()if upsampler is None:print(f"[super_res] Lanczos {scale}x -> {w*scale}x{h*scale}")return lanczostry:if focus_bbox is None:output, _ = upsampler.enhance(image, outscale=scale)if output is None:return lanczosif output.shape[:2] != lanczos.shape[:2]:output = cv2.resize(output, (lanczos.shape[1], lanczos.shape[0]),interpolation=cv2.INTER_LANCZOS4)blended = cv2.addWeighted(output, realesrgan_weight,lanczos, 1.0 - realesrgan_weight, 0)print(f"[super_res] RealESRGAN+Lanczos {scale}x -> "f"{blended.shape[1]}x{blended.shape[0]} (re={realesrgan_weight})")return blended# -- head-only super-resolution ------------------------------------x1, y1, x2, y2 = [int(v) for v in focus_bbox]bw, bh = x2 - x1, y2 - y1# Generous margin so hair and jaw are reconstructed with the face, and# the feathered seam lands on background rather than on skin.cx1 = max(0, x1 - int(bw * 1.0)); cy1 = max(0, y1 - int(bh * 1.2))cx2 = min(w, x2 + int(bw * 1.0)); cy2 = min(h, y2 + int(bh * 1.6))crop = image[cy1:cy2, cx1:cx2]if crop.size == 0:return lanczosout_crop, _ = upsampler.enhance(crop, outscale=scale)if out_crop is None:return lanczostw, th = (cx2 - cx1) * scale, (cy2 - cy1) * scaleif (out_crop.shape[1], out_crop.shape[0]) != (tw, th):out_crop = cv2.resize(out_crop, (tw, th), interpolation=cv2.INTER_LANCZOS4)region = lanczos[cy1 * scale:cy2 * scale, cx1 * scale:cx2 * scale]mixed = cv2.addWeighted(out_crop, realesrgan_weight,region, 1.0 - realesrgan_weight, 0)# Feather the crop edge so the enhanced head doesn't end on a hard line.m = np.zeros((th, tw), np.float32)pad = max(2, int(min(th, tw) * 0.06))m[pad:th - pad, pad:tw - pad] = 1.0m = cv2.GaussianBlur(m, (0, 0), pad / 2.0)[..., None]out = lanczos.copy()out[cy1 * scale:cy2 * scale, cx1 * scale:cx2 * scale] = (mixed.astype(np.float32) * m + region.astype(np.float32) * (1.0 - m)).astype(np.uint8)print(f"[super_res] RealESRGAN on head {crop.shape[1]}x{crop.shape[0]} "f"+ Lanczos {scale}x -> {out.shape[1]}x{out.shape[0]}")return outexcept Exception as e:print(f"[super_res] RealESRGAN enhance failed: {e}")return lanczosdef enhance_resolution(image: np.ndarray, scale: int = 4) -> np.ndarray:128 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169128 unmodified linesdef upscale_image(image: np.ndarray, scale: int = 4,realesrgan_weight: float = 0.5) -> np.ndarray:"""Upscale the whole frame ~scale x for the high-resolution download.RealESRGAN adds resolution but, being a general-purpose model, it over-sharpensskin into a plastic/waxy texture on faces. So we BLEND it with a plain Lanczosupscale (realesrgan_weight controls the mix: 0 = pure natural Lanczos, 1 = fullRealESRGAN) — keeping most of the detail while killing the artificial texture.RealESRGAN is only used on GPU — on CPU (e.g. the HuggingFace free tier) a 4xpass is too slow, so we fall back to pure Lanczos there."""h, w = image.shape[:2]lanczos = cv2.resize(image, (w * scale, h * scale),interpolation=cv2.INTER_LANCZOS4)if _device() == "cuda":upsampler = _load_realesrgan()if upsampler is not None:try:output, _ = upsampler.enhance(image, outscale=scale)if output is not None:if output.shape[:2] != lanczos.shape[:2]:output = cv2.resize(output, (lanczos.shape[1], lanczos.shape[0]),interpolation=cv2.INTER_LANCZOS4)blended = cv2.addWeighted(output, realesrgan_weight,lanczos, 1.0 - realesrgan_weight, 0)print(f"[super_res] RealESRGAN+Lanczos {scale}x -> "f"{blended.shape[1]}x{blended.shape[0]} (re={realesrgan_weight})")return blendedexcept Exception as e:print(f"[super_res] RealESRGAN enhance failed: {e}")print(f"[super_res] Lanczos {scale}x -> {w*scale}x{h*scale}")return lanczosdef enhance_resolution(image: np.ndarray, scale: int = 4) -> np.ndarray:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175%PDF-1.3%���� ReportLab Generated PDF document (opensource)1 0 obj<</F1 2 0 R /F2 3 0 R /F3 5 0 R>>endobj2 0 obj<</BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font>>endobj3 0 obj<</BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font>>endobj4 0 obj<</Contents 14 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 13 0 R /Resources <</Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]>> /Rotate 0 /Trans <<
>> /Type /Page>>endobj5 0 obj<</BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding /Name /F3 /Subtype /Type1 /Type /Font>>endobj6 0 obj<</Contents 15 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 13 0 R /Resources <</Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]>> /Rotate 0 /Trans <<
>> /Type /Page>>endobj7 0 obj<</Contents 16 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 13 0 R /Resources <</Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]>> /Rotate 0 /Trans <<
>> /Type /Page>>endobj8 0 obj<</Contents 17 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 13 0 R /Resources <</Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]>> /Rotate 0 /Trans <<
>> /Type /Page>>endobj9 0 obj<</Contents 18 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 13 0 R /Resources <</Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]>> /Rotate 0 /Trans <<
>> /Type /Page>>endobj10 0 obj<</Contents 19 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 13 0 R /Resources <</Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]>> /Rotate 0 /Trans <<
>> /Type /Page>>endobj11 0 obj<</PageMode /UseNone /Pages 13 0 R /Type /Catalog>>endobj12 0 obj<</Author (Aditya Raj) /CreationDate (D:20260907100047+05'00') /Creator (anonymous) /Keywords () /ModDate (D:20260907100047+05'00') /Producer (ReportLab PDF Library - \(opensource\)) /Subject (unspecified) /Title (DeepFace Studio \204 project workflow) /Trapped /False>>endobj13 0 obj<</Count 6 /Kids [ 4 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R ] /Type /Pages>>endobj14 0 obj<</Filter [ /ASCII85Decode /FlateDecode ] /Length 2361>>streamGatn'>Ar9+'$&o..H[lO8(!=%FO!h=e4J&*2lOE&?NLqK9Nu=D;37`drq8FL/;^qp5$5`lP'SD"j\PJ,,<B5m5=ba6%fd^&E4pA/EFHN_a1$FuIt^\aR:QV2fb%=]!6'DaDf``tW7tRh]aaASfctJfg[tUa(1CU)6/]QT!,l`mbEk%tY`dP&Mmoqi$0udrJfB='H!pGC)o7*H,!$D#jU_ft$ZYbUFt,h(UcHML9#sqY?NPpo??.J%i0b;S[U:qGQlbguKKKiEljK70Akk5bMdTl0KC="?(QPiGL`6&2e,p9>[p3C0;H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qs]dZshQ?21YO222N]NNn%#bLAipDS1V)cp_%"TI[Cs'me4AHI*Bf$Pkee$=.b5NL"2#7[Gj6Xjeo59MM(FJM(:=)dTI"#@4#.?(lnRcp:as6!*89QUb0`?(m1ZZ.BY#D0/KN45.=I\s@+6>p%e[$dE&$hC[!5C`f.0;riMhcBbH%CM_O6Z&56glTYfY?1+%Xfp(?-%@1m)-&%Dhmk/UbV>B-W?8=m,AS+nkC'uK<bFu])(?.'!lN4o1a7Q#"rHJupcca%^U?_+ug.M:EG\#<GdkI.(.-n9J5P"t#"BlY)N9L7iA?<=BVXI9'gOf/JD-HoV]qN0,].<]@Ip`nmK9ToEq,4_Qe@6P8IfTdR>:9~>endstreamendobjxref0 200000000000 65535 f 0000000061 00000 n 0000000112 00000 n 0000000219 00000 n 0000000331 00000 n 0000000536 00000 n 0000000651 00000 n 0000000856 00000 n 0000001061 00000 n 0000001266 00000 n 0000001471 00000 n 0000001677 00000 n 0000001747 00000 n 0000002039 00000 n 0000002130 00000 n 0000004583 00000 n 0000007301 00000 n 0000009648 00000 n 0000011950 00000 n 0000014934 00000 n trailer<</ID [<00c2933906a873bcc440e328debc6d32><00c2933906a873bcc440e328debc6d32>]% ReportLab generated PDF document -- digest (opensource)
/Info 12 0 R/Root 11 0 R/Size 20>>startxref17471%%EOF1234567891011121314151617 unmodified lines343536373839404142434445464748495051525354555657585910 unmodified lines70717273747576777879808182838438 unmodified lines123124125126127128129130131132133134135136137138139140141142import { useState, useEffect, useRef } from 'react';import { useNavigate } from 'react-router-dom';import { motion, AnimatePresence } from 'framer-motion';import { auth, googleProvider, signInWithPopup, signInWithRedirect, getRedirectResult, signOut, onAuthStateChanged } from '../firebase';// Hugging Face serves the Space inside a cross-origin iframe. Google refuses to// render its sign-in there (it answers 403 "you do not have access to this// document"), so signInWithRedirect — which navigates THIS frame — is a dead end.// Popups can also be blocked by the frame's sandbox. When framed we therefore// never redirect; we offer to reopen the app in a top-level tab instead.const IN_IFRAME = (() => {try { return window.self !== window.top; } catch { return true; }})();// ═══ AUTHORISED OWNER EMAILS ═══════════════════════════════════════════════════// Only these Google accounts can open the Control Panel. Anyone else who signs17 unmodified lines// ── Google sign-in screen ─────────────────────────────────────────────────────function GoogleLogin({ denied }) {const [loading, setLoading] = useState(false);const [error, setError] = useState('');const [needsTab, setNeedsTab] = useState(false);// Complete a redirect sign-in (top-level tab only) and surface its error.// Without this the redirect path fails silently: you come back from Google// and just see the login screen again with no explanation.useEffect(() => {getRedirectResult(auth).catch((e) => {const code = e?.code || '';if (code) setError(`Sign-in failed: ${code}`);});}, []);const openInNewTab = () => {window.open(window.location.href, '_blank', 'noopener,noreferrer');};const signIn = async () => {setLoading(true); setError(''); setNeedsTab(false);try {const res = await signInWithPopup(auth, googleProvider);const email = (res.user.email || '').toLowerCase();10 unmodified linessetError('This site\'s domain isn\'t authorised in Firebase. Add it under '+ 'Firebase Console → Authentication → Settings → Authorized domains.');} else if (code === 'auth/popup-blocked' || code === 'auth/operation-not-supported-in-this-environment') {if (IN_IFRAME) {// Redirecting here would navigate the Hugging Face iframe to Google,// which answers 403 (it won't be embedded). Reopen top-level instead.setNeedsTab(true);setError('Google sign-in can\'t run inside the Hugging Face preview frame.');} else {try { await signInWithRedirect(auth, googleProvider); return; }catch { setError('Sign-in failed (popup blocked). Allow popups and retry.'); }}} else {setError(`Sign-in failed: ${code || e?.message || 'unknown error'}`);}38 unmodified lines)}</AnimatePresence>{/* Google won't render its sign-in inside the Hugging Face iframe, sooffer a top-level tab — shown up front when framed, and after ablocked popup anywhere else. */}{(needsTab || IN_IFRAME) && (<button onClick={openInNewTab}className="mt-3 w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-xs font-semibold text-teal border border-teal/40 bg-teal/5 hover:bg-teal/10 active:scale-95 transition-all"><svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>Open in a new tab to sign in</button>)}<p className="mt-5 text-[11px] text-slate text-center leading-relaxed">Access is restricted to a fixed list of owner accounts.</p>123456717 unmodified lines252627282930313233343510 unmodified lines46474849505152535438 unmodified lines939495969798import { useState, useEffect, useRef } from 'react';import { useNavigate } from 'react-router-dom';import { motion, AnimatePresence } from 'framer-motion';import { auth, googleProvider, signInWithPopup, signInWithRedirect, signOut, onAuthStateChanged } from '../firebase';// ═══ AUTHORISED OWNER EMAILS ═══════════════════════════════════════════════════// Only these Google accounts can open the Control Panel. Anyone else who signs17 unmodified lines// ── Google sign-in screen ─────────────────────────────────────────────────────function GoogleLogin({ denied }) {const [loading, setLoading] = useState(false);const [error, setError] = useState('');const signIn = async () => {setLoading(true); setError('');try {const res = await signInWithPopup(auth, googleProvider);const email = (res.user.email || '').toLowerCase();10 unmodified linessetError('This site\'s domain isn\'t authorised in Firebase. Add it under '+ 'Firebase Console → Authentication → Settings → Authorized domains.');} else if (code === 'auth/popup-blocked' || code === 'auth/operation-not-supported-in-this-environment') {// Popup blocked (or COOP) - fall back to full-page redirect sign-in.try { await signInWithRedirect(auth, googleProvider); return; }catch { setError('Sign-in failed (popup blocked). Allow popups and retry.'); }} else {setError(`Sign-in failed: ${code || e?.message || 'unknown error'}`);}38 unmodified lines)}</AnimatePresence><p className="mt-5 text-[11px] text-slate text-center leading-relaxed">Access is restricted to a fixed list of owner accounts.</p>
174 unmodified lines17517617717817918018118218318418590 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633736 unmodified lines374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403210 unmodified lines614615616617618619620621622623624625626627628629630631632633634635636637638174 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 ──────────────────────────────────────────────── */}210 unmodified lines</TiltedCard></div>{/* Server-side notes about this result — why the head swap wasskipped, a face too small to swap well, and so on. Withoutthese the pipeline silently falls back and the result justlooks like nothing happened. */}{Array.isArray(result.warnings) && result.warnings.length > 0 && (<div className="max-w-md w-full mx-auto mt-3 flex flex-col gap-2">{result.warnings.map((w, i) => (<p key={i}className="flex items-start gap-2 text-[11px] leading-relaxed font-medium text-amber-800 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2"><svg className="w-3.5 h-3.5 shrink-0 mt-px" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg><span>{w}</span></p>))}</div>)}{/* download row */}<div className="flex flex-col sm:flex-row gap-3 justify-center mt-2"><a href={result.download_image || result.result_image}174 unmodified lines17517617717817918090 unmodified lines27127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030136 unmodified lines338339340341342343210 unmodified lines554555556557558559174 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 ──────────────────────────────────────────────── */}210 unmodified lines</TiltedCard></div>{/* download row */}<div className="flex flex-col sm:flex-row gap-3 justify-center mt-2"><a href={result.download_image || result.result_image}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425"""Generate docs/WORKFLOW.pdf — how DeepFace Studio actually works end to end.
Kept in the repo so the document can be regenerated after the pipeline changes,instead of drifting away from the code the way a hand-drawn diagram would.
Run: python scripts/make_workflow_pdf.py"""import os
from reportlab.lib.pagesizes import A4from reportlab.lib.units import mmfrom reportlab.pdfgen import canvas
NAVY = (0.06, 0.09, 0.16)TEAL = (0.05, 0.58, 0.53)SLATE = (0.28, 0.33, 0.41)LIGHT = (0.95, 0.96, 0.97)BORDER = (0.80, 0.84, 0.88)AMBER = (0.85, 0.47, 0.05)
W, H = A4M = 18 * mm
def header(c, title, subtitle=None): c.setFillColorRGB(*NAVY) c.setFont("Helvetica-Bold", 17) c.drawString(M, H - M - 4, title) if subtitle: c.setFillColorRGB(*SLATE) c.setFont("Helvetica", 9.5) c.drawString(M, H - M - 19, subtitle) c.setStrokeColorRGB(*TEAL) c.setLineWidth(2) c.line(M, H - M - 26, W - M, H - M - 26) return H - M - 42
def footer(c, page, total): c.setFillColorRGB(*SLATE) c.setFont("Helvetica", 7.5) c.drawString(M, 12 * mm, "DeepFace Studio — project workflow") c.drawRightString(W - M, 12 * mm, f"{page} / {total}")
def box_height(body=None): """Height that fits a title plus these body lines, with even padding.""" return 24 + len(body or []) * 10 + 2
def box(c, x, y, w, h, title, body=None, fill=LIGHT, accent=TEAL, tsize=9.5): """ Rounded box with an accent bar; returns the y of its bottom edge. Pass h=None to size it from the body, so adding a line can't overflow it. """ if h is None: h = box_height(body) c.setFillColorRGB(*fill) c.setStrokeColorRGB(*BORDER) c.setLineWidth(0.8) c.roundRect(x, y - h, w, h, 3, stroke=1, fill=1) c.setFillColorRGB(*accent) c.roundRect(x, y - h, 3, h, 1.5, stroke=0, fill=1)
c.setFillColorRGB(*NAVY) c.setFont("Helvetica-Bold", tsize) c.drawString(x + 9, y - 12.5, title) if body: c.setFillColorRGB(*SLATE) c.setFont("Helvetica", 8.2) ty = y - 24 for line in body: c.drawString(x + 9, ty, line) ty -= 10 return y - h
def arrow(c, x, y1, y2, label=None): c.setStrokeColorRGB(*TEAL) c.setLineWidth(1.2) c.line(x, y1, x, y2) c.setFillColorRGB(*TEAL) c.setLineWidth(0) p = c.beginPath() p.moveTo(x, y2) p.lineTo(x - 3.2, y2 + 6) p.lineTo(x + 3.2, y2 + 6) p.close() c.drawPath(p, stroke=0, fill=1) if label: c.setFillColorRGB(*SLATE) c.setFont("Helvetica-Oblique", 7.5) c.drawString(x + 8, (y1 + y2) / 2 - 2, label)
def bullets(c, x, y, items, width_note=None): c.setFont("Helvetica", 9) for it in items: c.setFillColorRGB(*TEAL) c.drawString(x, y, "•") c.setFillColorRGB(*SLATE) c.drawString(x + 10, y, it) y -= 12.5 return y
# ── page 1 — overview ────────────────────────────────────────────────────────def page_overview(c): y = header(c, "DeepFace Studio", "AI face swap that places a visitor into a real campus photograph")
c.setFillColorRGB(*SLATE) c.setFont("Helvetica", 9.2) for line in [ "A visitor enters their name, uploads or captures a photo, and picks a campus location.", "Their face is swapped into the curated photograph for that location, then returned as a", "preview plus a high-resolution download.", ]: c.drawString(M, y, line) y -= 12.5 y -= 8
y = box(c, M, y, W - 2 * M, None, "Tech stack", [ "Frontend React 18 + Vite + TailwindCSS + Framer Motion (SPA, served by Flask)", "Backend Python + Flask, background worker threads for the swap pipeline", "Storage Supabase (location photographs) with a local Location/ folder fallback", "Auth Firebase Google Sign-In — gates the Control Panel to an email allowlist", ]) - 14
y = box(c, M, y, W - 2 * M, None, "Models", [ "buffalo_l (InsightFace) face detection + 5-point landmarks", "inswapper_128 (InsightFace) the identity swap itself, internally 128x128", "GFPGAN v1.4 restores facial detail lost to that 128px bottleneck", "RealESRGAN x4plus super-resolution, applied to the head region", "BiSeNet (facexlib) hair / skin / neck segmentation", "HairFastGAN (hosted Space) optional hairstyle transfer — needs HF_TOKEN", ]) - 14
y = box(c, M, y, W - 2 * M, None, "Hosting", [ "Hugging Face Space aditya-rAj19/FaceSWAP (Docker SDK, port 7860)", "Live https://aditya-raj19-faceswap.hf.space", "Hardware cpu-basic (free tier); CUDA is used automatically when present", "Deploy every push to main, via GitHub Actions", ]) - 14
box(c, M, y, W - 2 * M, None, "Why the pipeline is built the way it is", [ "The swap model works at 128x128, so the head is the only part of the frame that", "loses real detail. Everything else is taken from the original photograph untouched,", "and super-resolution is spent on the head alone rather than the whole image.", ], fill=(0.98, 0.96, 0.90), accent=AMBER)
# ── page 2 — architecture ────────────────────────────────────────────────────def page_architecture(c): y = header(c, "System architecture", "What talks to what, at request time")
cw = W - 2 * M y = box(c, M, y, cw, None, "Browser — React SPA", [ "/ landing /app swap page (Head Swap toggle) /admin Control Panel", ]) arrow(c, W / 2, y, y - 22, "HTTPS") y -= 22
y = box(c, M, y, cw, None, "Flask (web_app.py)", [ "Serves the built SPA and the JSON API. Static assets get explicit MIME types", "because the slim Python image ships an incomplete MIME database.", ]) arrow(c, W / 2, y, y - 22, "submit / poll") y -= 22
half = (cw - 10) / 2 y2 = box(c, M, y, half, None, "Job store (in memory)", [ "One swap at a time — the", "models already saturate the", "2 vCPUs. Results expire after", "20 minutes and are capped.", ]) box(c, M + half + 10, y, half, None, "Worker thread", [ "_perform_swap() runs the", "pipeline with no request", "context and reports progress", "back to the job.", ]) y = y2 arrow(c, W / 2, y, y - 22) y -= 22
y = box(c, M, y, cw, None, "core/ pipeline", [ "detector · swapper · super_res · head_swap · segmentor · blender · hair_transfer", ]) y -= 16
y2 = box(c, M, y, half, None, "Supabase", [ "Location photographs per", "gender. Falls back to the", "Location/ folder when unset.", ], accent=SLATE) box(c, M + half + 10, y, half, None, "Firebase", [ "Google Sign-In for the", "Control Panel; ID tokens are", "verified server-side too.", ], accent=SLATE)
c.setFillColorRGB(*SLATE) c.setFont("Helvetica-Oblique", 8) c.drawString(M, y2 - 16, "Nothing is written to disk during a swap — images are decoded, processed and returned in memory.")
# ── page 3 — request flow ────────────────────────────────────────────────────def page_request(c): y = header(c, "Request workflow", "Why a swap is a job rather than a single request")
box(c, M, y, W - 2 * M, None, "The constraint", [ "Full-quality output takes minutes on the free CPU tier — head super-resolution alone", "is about six. No HTTP request survives that, so the swap cannot be synchronous.", ], fill=(0.98, 0.96, 0.90), accent=AMBER) y -= 62
steps = [ ("1 POST /api/swap", [ "Validates and decodes the source, resolves the target from gender + location,", "creates a job and returns 202 with a job_id. Returns in about 1.5 seconds.", ]), ("2 Worker thread picks up the job", [ "Runs the pipeline, updating progress and a message at each stage.", ]), ("3 GET /api/swap/status/<job_id>", [ "Polled every 2 seconds. Returns state, progress and message while running.", ]), ("4 state = done", [ "The same payload the endpoint always returned: result_image, download_image,", "quality, delta_e, src_tone, tgt_tone, warnings, name.", ]), ] for i, (title, body) in enumerate(steps): y = box(c, M, y, W - 2 * M, None, title, body) if i < len(steps) - 1: arrow(c, W / 2, y, y - 18) y -= 18 y -= 20
c.setFillColorRGB(*NAVY) c.setFont("Helvetica-Bold", 11) c.drawString(M, y, "In the UI") y -= 16 bullets(c, M, y, [ "The progress bar follows the server's real stage, not a timer animating a guess.", "The motivational captions keep rotating on their own — the wait is longer now.", "Failures surface the server's message instead of failing silently.", ])
# ── page 4 — the pipeline ────────────────────────────────────────────────────def page_pipeline(c): y = header(c, "The swap pipeline", "Stage by stage, with measured CPU cost on a 1086x1448 photograph")
c.setFillColorRGB(*SLATE) c.setFont("Helvetica", 8.6) c.drawString(M, y, "Working resolution is 1024 on CPU and 1536 on CUDA. Optional stages are marked.") y -= 16
rows = [ ("Prepare", "Resize; pad a close-up until detectable; de-roll a tilted selfie so eyes are level.", "~7s"), ("Detect", "buffalo_l on source and target; retries with CLAHE, then Haar.", "~1s"), ("Head swap (opt-in)", "Transplants the whole head — shape and hair — instead of only the face.", "varies"), ("Face swap", "inswapper_128 puts the source identity on the main target face.", "~19s"), ("Restore", "GFPGAN rebuilds the detail the 128px swap threw away.", "~55s"), ("Blend seam", "Laplacian pyramid over the face boundary. Must run before hair.", "~14s"), ("Hair (opt-in)", "HairFastGAN only. No crude fallback — it smeared a blob over the head.", "~30s"), ("Glasses (opt-in)", "Off by default: it disfigured sources who wear glasses.", "~4s"), ("Skin tone", "Drives face, neck, arms and hands to the source complexion.", "~3s"), ("Score", "Alignment, blend, delta-E, naturalness — measured before grain is added.", "~2s"), ("Harmonise", "Adds the photo's grain over the parsed head so it isn't GAN-smooth.", "~1s"), ("Composite", "Pastes only what changed back onto the untouched full-resolution photo.", "~0.2s"), ("Enhance", "RealESRGAN on the head crop, Lanczos elsewhere, feathered between.", "~370s"), ]
c.setFillColorRGB(*NAVY) c.setFont("Helvetica-Bold", 8.4) c.drawString(M + 4, y, "STAGE") c.drawString(M + 108, y, "WHAT IT DOES") c.drawRightString(W - M - 4, y, "CPU") y -= 4 c.setStrokeColorRGB(*BORDER) c.setLineWidth(0.6) c.line(M, y, W - M, y) y -= 13
for i, (name, desc, cost) in enumerate(rows): if i % 2 == 0: c.setFillColorRGB(0.975, 0.98, 0.985) c.rect(M, y - 4, W - 2 * M, 15, stroke=0, fill=1) opt = "(opt-in)" in name c.setFillColorRGB(*(SLATE if opt else NAVY)) c.setFont("Helvetica-Bold", 8.2) c.drawString(M + 4, y, name) c.setFillColorRGB(*SLATE) c.setFont("Helvetica", 8) c.drawString(M + 108, y, desc) c.setFillColorRGB(*(AMBER if cost == "~370s" else SLATE)) c.setFont("Helvetica-Bold" if cost == "~370s" else "Helvetica", 8) c.drawRightString(W - M - 4, y, cost) y -= 15
y -= 12 box(c, M, y, W - 2 * M, None, "The two decisions that matter most", [ "Composite, not upscale — the background and body are never touched by the swap, so", "they are taken from the original photograph. Background sharpness went from 34% of", "the original to 100%, and the delivered image is native resolution rather than a", "downscaled frame blown back up.", ], fill=(0.94, 0.98, 0.97))
# ── page 5 — deployment ──────────────────────────────────────────────────────def page_deploy(c): y = header(c, "Deployment", "From a push on main to a running Space")
seq = [ ("git push origin main", ["The default branch is the deploy trigger."]), ("GitHub Actions", [ "ci.yml pytest on a lightweight dependency subset, plus a frontend build", "deploy.yml force-pushes the repository to the Hugging Face Space", ]), ("Hugging Face Space", [ "Rebuilds the Docker image on the new commit.", ]), ("Docker build", [ "Stage 1 node:20-slim builds the React app into static/react", "Stage 2 python:3.10-slim installs CPU torch, then requirements-deploy.txt", ]), ("startup.sh", [ "Downloads model weights in the BACKGROUND and starts Flask immediately —", "a container that doesn't answer on its port within ~60s is killed.", ]), ("Flask on :7860", [ "Debug off; models pre-warm on a daemon thread so the port binds at once.", ]), ] for i, (title, body) in enumerate(seq): y = box(c, M, y, W - 2 * M, None, title, body) if i < len(seq) - 1: arrow(c, W / 2, y, y - 16) y -= 16 y -= 22
c.setFillColorRGB(*NAVY) c.setFont("Helvetica-Bold", 11) c.drawString(M, y, "Configuration held outside the repository") y -= 16 y = bullets(c, M, y, [ "HF_TOKEN — GitHub secret for deploying; also lifts the HairFastGAN GPU quota.", "SUPABASE_URL / SUPABASE_SERVICE_KEY / SUPABASE_BUCKET — location photographs.", "ALLOWED_ADMIN_EMAILS / PRIMARY_ADMIN_EMAILS — Control Panel access.", "FLASK_DEBUG — unset in production; set to true only for local development.", ]) y -= 6 box(c, M, y, W - 2 * M, None, "Verifying a deploy", [ "Space state and commit: https://huggingface.co/api/spaces/aditya-rAj19/FaceSWAP/runtime", "Expect \"stage\":\"RUNNING\" with sha matching the pushed commit, then probe / and /api/locations.", ], fill=(0.94, 0.98, 0.97))
# ── page 6 — behaviour + gotchas ─────────────────────────────────────────────def page_notes(c): y = header(c, "Behaviour and known limits", "Things that are easy to misread from the code")
y = box(c, M, y, W - 2 * M, None, "CPU and GPU", [ "Both paths run the same pipeline; only cost and working resolution differ.", "CPU 1024px working resolution; RealESRGAN on the head crop (~6 min).", "GPU 1536px; RealESRGAN available for the full frame; local HairFastGAN possible.", "Full-frame super-resolution on CPU was measured at about 20 minutes, which is why", "it is confined to the head.", ]) - 14
y = box(c, M, y, W - 2 * M, None, "Hair transfer", [ "Real hair transfer requires HairFastGAN. On the Space it connects to the public", "AIRI-Institute/HairFastGAN ZeroGPU Space anonymously and hits its quota, so it fails", "and the target's own hair is kept.", "", "To enable it: set HF_TOKEN on the Space, or point HAIRFAST_SPACE at your own GPU", "Space. There is deliberately no fallback — warping hair in directly looked pasted.", ], fill=(0.98, 0.96, 0.90), accent=AMBER) - 14
y = box(c, M, y, W - 2 * M, None, "Opt-in stages, and why", [ "Head swap changes far more of the photo than a face swap; exposed as a toggle.", "Hair only runs when HairFastGAN returns a portrait.", "Glasses warped spectacles onto the face as a misaligned, translucent shape.", "Each is a form field on /api/swap, so any of them can be turned back on per request.", ]) - 14
y = box(c, M, y, W - 2 * M, None, "Quality metrics", [ "Reported per swap: alignment, blend, delta-E and naturalness. They are computed", "BEFORE the harmonise stage — that stage adds grain deliberately, and scoring after it", "penalised the pipeline for its own noise, understating every result.", ]) - 14
box(c, M, y, W - 2 * M, None, "Privacy", [ "Uploads are decoded in memory and the result is returned as a data URI; nothing is", "written to disk. Finished jobs, which hold the images, expire after 20 minutes.", ])
def main(): out_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "docs") os.makedirs(out_dir, exist_ok=True) path = os.path.join(out_dir, "WORKFLOW.pdf")
pages = [page_overview, page_architecture, page_request, page_pipeline, page_deploy, page_notes]
c = canvas.Canvas(path, pagesize=A4) c.setTitle("DeepFace Studio — project workflow") c.setAuthor("Aditya Raj") for i, page in enumerate(pages, 1): page(c) footer(c, i, len(pages)) c.showPage() c.save() print(f"wrote {path}")
if __name__ == "__main__": main()56 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810956 unmodified linesreturn cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)def composite_onto_original(result: np.ndarray, work_target: np.ndarray,orig_target: np.ndarray, threshold: int = 6,feather: float = 0.004) -> np.ndarray:"""Put everything the pipeline CHANGED back onto the full-resolution target.The swap runs at a reduced working resolution so the models stay affordable,and the 4x download then interpolates that whole frame back up. For a1086x1448 photo processed at 768x1024 that discards half the real detail —including the background and body, which the swap never touches. Here wediff the result against the working-resolution target to find what actuallychanged (the head, plus any skin the tone match reached), and paste onlythat onto the untouched original. Everything else stays pixel-exact.A diff-driven mask is used rather than a parsed head mask so that changesoutside the head — match_skin_to_source also recolours neck, arms and hands— are carried over too instead of being silently dropped."""if orig_target is None or result is None:return resultoh, ow = orig_target.shape[:2]rh, rw = result.shape[:2]if (oh, ow) == (rh, rw):return result # nothing was downscaledif work_target is None or work_target.shape[:2] != result.shape[:2]:return cv2.resize(result, (ow, oh), interpolation=cv2.INTER_LANCZOS4)diff = cv2.absdiff(result, work_target).max(axis=2)# Blur before thresholding so JPEG-level speckle doesn't fragment the mask.diff = cv2.GaussianBlur(diff, (0, 0), max(1.0, min(rh, rw) * 0.002))mask = (diff > threshold).astype(np.float32)if mask.max() <= 0:return orig_target.copy() # pipeline was a no-op# Close holes, then grow slightly so the seam sits outside the changed area.k = max(3, int(min(rh, rw) * 0.01) | 1)mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((k, k), np.uint8))mask = cv2.dilate(mask, np.ones((k, k), np.uint8))up_result = cv2.resize(result, (ow, oh), interpolation=cv2.INTER_LANCZOS4)up_mask = cv2.resize(mask, (ow, oh), interpolation=cv2.INTER_LINEAR)up_mask = cv2.GaussianBlur(up_mask, (0, 0), max(1.5, min(oh, ow) * feather))a = np.clip(up_mask, 0.0, 1.0)[..., None]out = up_result.astype(np.float32) * a + orig_target.astype(np.float32) * (1.0 - a)return np.clip(out, 0, 255).astype(np.uint8)def image_to_bytes(image: np.ndarray, fmt: str = "PNG") -> bytes:"""Convert BGR numpy array to encoded bytes."""rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)56 unmodified lines57585960616256 unmodified linesreturn cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)def image_to_bytes(image: np.ndarray, fmt: str = "PNG") -> bytes:"""Convert BGR numpy array to encoded bytes."""rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
14 unmodified lines1516171819202122232421 unmodified lines46474849505152186 unmodified lines239240241242243244245363 unmodified lines60961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472538 unmodified lines7647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937941 unmodified line79679779879980080180280380480580611 unmodified lines81881982082182282382482582682782882983083183283383483583683783883984028 unmodified lines8698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239244 unmodified lines9299309319329339349359367 unmodified lines9449459469479489499509519529539549559569579589599609619629639649659669673 unmodified lines9719729739749759769771 unmodified line97998098198298398498598698798898930 unmodified lines102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661 unmodified line1068106910701071107210731074107510761077107810791080108113 unmodified lines10951096109710981099110011011102110311041105110611071108110914 unmodified linesos.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")import ioimport reimport timeimport uuidimport base64import threadingimport tracebackimport mimetypes21 unmodified linesfrom core.blender import laplacian_blendfrom core.quality_checker import compute_quality_scorefrom core import supabase_storefrom utils.image_io import resize_keep_aspect, composite_onto_originalREACT_BUILD = os.path.join("static", "react")LOCATIONS_DIR = "Location" # Location/Male/<loc>/img + Location/Female/<loc>/img186 unmodified linesapp = Flask(__name__, static_folder="static")app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50 MB_debug_mode = os.environ.get("FLASK_DEBUG", "false").lower() == "true"CORS(app, origins=["http://localhost:5173", "http://127.0.0.1:5173"] if _debug_mode else "*")# Nothing is written to disk — uploads are decoded in memory and the result is363 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", "0"),}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.1 unmodified line# larger canvas mainly helps the final blend + the RealESRGAN 4x upscale.from core.super_res import _device as _sr_device_work_res = 1536 if _sr_device() == "cuda" else 1024# Keep the untouched full-resolution target: at the end only the region# the pipeline actually changed is pasted back onto it, so background and# body keep the original photo's detail instead of being downscaled here# and interpolated back up by the 4x pass.target_orig = targetsource = resize_keep_aspect(source, _work_res)target = resize_keep_aspect(target, _work_res)11 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:from core.head_swap import (head_pose_delta, HEAD_POSE_WARN,HEAD_POSE_MAX)_pose = head_pose_delta(source, target)hs = full_head_swap(source, target)if hs is not None:base = hsif _pose and max(_pose) > HEAD_POSE_WARN:warnings.append("Your head angle differs from the location photo "f"(about {max(_pose):.0f}°), so the head swap may not line up ""perfectly. A photo taken from the same angle works best.")elif _pose and max(_pose) > HEAD_POSE_MAX:# full_head_swap refused: the heads face different ways and a# 2D transform cannot turn one to match the other.warnings.append(f"Head swap was skipped — your head angle is about "f"{max(_pose):.0f}° away from the location photo, which would have ""looked crooked. The face swap was used instead. Try a photo ""facing the same way as the person in the location.")except Exception as e:print(f"[swap] head swap error: {e}")# 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 the# seam left by InsightFace's paste_back. MUST run BEFORE the hair step:# it composites the swapped FACE over the base everywhere else, so if# it ran after the hair it would overwrite the newly-transferred hair# (which lies outside the face mask) with the base's original hair.## Blend against `base`, NOT `target`. They are the same image unless# the head swap ran, and when it did, blending against `target` threw# the transplanted head and hair away everywhere outside the face# mask — measured as erasing about two thirds of the head swap, which# is why head_swap=1 and head_swap=0 came out looking identical.note(50, "Blending the seam…")try:from core.segmentor import segment_hair_neck_skin_fmask = segment_hair_neck_skin(swapped).get("face_mask")if _fmask is not None and _fmask.max() > 0:swapped = laplacian_blend(swapped, base, _fmask, levels=4)except Exception as e:print(f"[swap] Laplacian blend skipped: {e}")4 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,7 unmodified linescv2.BORDER_CONSTANT, value=(127, 127, 127))swapped = swap_hair(swapped, hf_padded, swapped, include_face=False)else:# No crude fallback. Warping the source's hair straight into# the scene composites a smeared, semi-transparent blob over# the head — visibly worse than simply keeping the target's# hair, which is what the clean face swap already gives.# Real hair transfer needs HairFastGAN: set HF_TOKEN on the# Space (the anonymous ZeroGPU quota is what fails here), or# HAIRFAST_SPACE for your own GPU Space.print("[swap] hair transfer unavailable (HairFastGAN) — ""keeping the target's hair")except Exception as e:print(f"[swap] hair compose error: {e}")# 6. Glasses — OPT-IN (keep_glasses=1). It warps the source's spectacles# onto the swapped face via a 2-point eye transform, and on a real# glasses-wearing source that lands as a semi-transparent, misaligned# lens shape floating over the face. Without it the result is clean;# the swap simply doesn't carry the glasses over.if opts.get("keep_glasses", "0") 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.921 unmodified lineexcept Exception as e:print(f"[swap] skin tone match skipped: {e}")# -- quality metrics --------------------------------------------------# 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 the30 unmodified linesexcept Exception as e:print(f"[swap] alignment metric skipped: {e}")# 8. HARMONISE — make the swapped head look PHOTOGRAPHED WITH the scene# (not pasted on it): add the photo's grain over the GAN-smooth face/hair# and gently match its colour cast. Runs AFTER quality scoring (so the# added grain doesn't skew the naturalness/blend metrics) but still last# before the output is encoded, so nothing smooths the grain away.try:swapped = harmonize_to_scene(swapped, target, faces_tgt[0], grain=0.9)except Exception as e:print(f"[swap] harmonize skipped: {e}")# 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)except Exception as e:print(f"[swap] original-resolution composite skipped: {e}")# -- 4K upscale for download (RealESRGAN on the head, Lanczos elsewhere)# The head is the only region that came through the swap's 128px# bottleneck; the rest is already native resolution from step 9, so# there's nothing there for a super-resolution model to reconstruct._sr_bbox = Nonetry:_fs = swapped.shape[1] / float(_work_w) # working -> composited scalex1, y1, x2, y2 = faces_tgt[0]_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 can# download it client-side (works on the HF Space too). We do NOT store it# 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():13 unmodified linesif __name__ == "__main__":port = int(os.environ.get("PORT", 5000))# Defaults to OFF: nothing sets FLASK_DEBUG on the deployed Space, and a# true default there serves the Werkzeug debugger on the public internet.# Opt in locally with FLASK_DEBUG=true.debug = _debug_modeprint(f"Starting Face Swap Web App on port {port}...")if not debug:# In a daemon thread so the port binds immediately — startup.sh# backgrounds the model downloads for the same reason (HF Spaces kills# a container that doesn't answer on its port within ~60s).threading.Thread(target=_prewarm_models, daemon=True).start()app.run(debug=debug, use_reloader=False, host="0.0.0.0", port=port)14 unmodified lines1516171819202121 unmodified lines43444546474849186 unmodified lines236237238239240241242363 unmodified lines60660760860961061161261361461561661761861962038 unmodified lines6596606616626636646656661 unmodified line66866967067167267311 unmodified lines68568668768868969069169269369469569669769869970070170270370470528 unmodified lines7347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637644 unmodified lines7697707717727737747757 unmodified lines7837847857867877887897907917927937943 unmodified lines7987998008018028031 unmodified line80580680780880981081181281381481581681781881982030 unmodified lines8518528538548558568578588598608618628638648658661 unmodified line86886987087187287387487587687787887913 unmodified lines89389489589689789889990090114 unmodified linesos.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")import ioimport reimport base64import tracebackimport mimetypes21 unmodified linesfrom core.blender import laplacian_blendfrom core.quality_checker import compute_quality_scorefrom core import supabase_storefrom utils.image_io import resize_keep_aspectREACT_BUILD = os.path.join("static", "react")LOCATIONS_DIR = "Location" # Location/Male/<loc>/img + Location/Female/<loc>/img186 unmodified linesapp = Flask(__name__, static_folder="static")app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50 MB_debug_mode = os.environ.get("FLASK_DEBUG", "true").lower() == "true"CORS(app, origins=["http://localhost:5173", "http://127.0.0.1:5173"] if _debug_mode else "*")# Nothing is written to disk — uploads are decoded in memory and the result is363 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.1 unmodified line# larger canvas mainly helps the final blend + the RealESRGAN 4x upscale.from core.super_res import _device as _sr_device_work_res = 1536 if _sr_device() == "cuda" else 1024source = resize_keep_aspect(source, _work_res)target = resize_keep_aspect(target, _work_res)11 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:base = hsexcept Exception as e:print(f"[swap] head swap error: {e}")# 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 the# seam left by InsightFace's paste_back. MUST run BEFORE the hair step:# 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")if _fmask is not None and _fmask.max() > 0:swapped = laplacian_blend(swapped, target, _fmask, levels=4)except Exception as e:print(f"[swap] Laplacian blend skipped: {e}")4 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,7 unmodified linescv2.BORDER_CONSTANT, value=(127, 127, 127))swapped = swap_hair(swapped, hf_padded, swapped, include_face=False)else:swapped = swap_hair(swapped, source, target, include_face=False)except Exception as e:print(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.921 unmodified lineexcept Exception as e:print(f"[swap] skin tone match skipped: {e}")# 8. HARMONISE — make the swapped head look PHOTOGRAPHED WITH the scene# (not pasted on it): add the photo's grain over the GAN-smooth face/hair# and gently match its colour cast. This is the last visual step, so the# grain isn't smoothed away by anything after it.try:swapped = harmonize_to_scene(swapped, target, faces_tgt[0], grain=0.9)except Exception as e:print(f"[swap] harmonize skipped: {e}")# -- quality metrics --------------------------------------------------quality = compute_quality_score(swapped, target, None, None)# Real alignment: how closely the swapped face's 5 landmarks sit on the30 unmodified linesexcept Exception as e:print(f"[swap] alignment metric skipped: {e}")# -- 4K upscale for download (RealESRGAN x4, Lanczos fallback) --------hi_res = upscale_image(swapped, scale=4)# The 4K result is returned inline as a base64 data-URI so the user can# download it client-side (works on the HF Space too). We do NOT store it# 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():13 unmodified linesif __name__ == "__main__":port = int(os.environ.get("PORT", 5000))debug = os.environ.get("FLASK_DEBUG", "true").lower() == "true"print(f"Starting Face Swap Web App on port {port}...")if not debug:_prewarm_models()app.run(debug=debug, use_reloader=False, host="0.0.0.0", port=port)