"
)
def _no_face_error(role: str) -> gr.Error:
return gr.Error(
f"No face detected in the {role} image (even after padded retry). "
"The face may occupy too much of the frame or be heavily occluded — "
"try turning off 'Align face' to run directly."
)
NO_CHANGE_4 = (gr.skip(), gr.skip(), gr.skip(), gr.skip())
SLIDER_CACHE_DIR = Path(tempfile.gettempdir()) / "rnv_slider_cache"
_LOSSLESS_LOCK = threading.Lock()
_LOSSLESS_MEM: OrderedDict[str, tuple[Image.Image, Image.Image, Image.Image | None, Image.Image | None]] = OrderedDict()
MAX_LOSSLESS_MEM = 64
def _stash_lossless_run(
full_pair: tuple[Image.Image, Image.Image],
crop_pair: tuple[Image.Image, Image.Image] | None = None,
) -> str:
"""Keep raw PIL outputs in a bounded RAM ring buffer (0 ms during inference; PNG encoded only on Download)."""
uid = uuid.uuid4().hex[:12]
cb, ca = (crop_pair[0], crop_pair[1]) if crop_pair is not None else (None, None)
with _LOSSLESS_LOCK:
_LOSSLESS_MEM[uid] = (full_pair[0], full_pair[1], cb, ca)
while len(_LOSSLESS_MEM) > MAX_LOSSLESS_MEM:
_LOSSLESS_MEM.popitem(last=False)
return uid
def export_lossless_png(req_json: str):
"""On-demand lossless 24-bit PNG export triggered only when user clicks Download."""
try:
req = json.loads(req_json or "{}")
except Exception:
return gr.skip()
uid = str(req.get("uid", ""))
use_crop = bool(req.get("crop", False))
try:
mix_pct = float(req.get("mix", 100.0))
except (TypeError, ValueError):
mix_pct = 100.0
safe_name = Path(str(req.get("name", "rnv_result.png"))).name
if not safe_name.lower().endswith(".png"):
safe_name += ".png"
with _LOSSLESS_LOCK:
entry = _LOSSLESS_MEM.get(uid)
if entry is None:
raise gr.Error("Lossless cache for this earlier run has expired; please re-run once to export lossless PNG.")
full_b, full_a, crop_b, crop_a = entry
before_im = crop_b if (use_crop and crop_b is not None and crop_a is not None) else full_b
after_im = crop_a if (use_crop and crop_b is not None and crop_a is not None) else full_a
if mix_pct < 99.5:
alpha = max(0.0, min(1.0, mix_pct / 100.0))
b_np = np.asarray(before_im, dtype=np.float32)
a_np = np.asarray(after_im, dtype=np.float32)
if b_np.shape != a_np.shape:
before_im = before_im.resize(after_im.size, Image.LANCZOS)
b_np = np.asarray(before_im, dtype=np.float32)
out_im = Image.fromarray(np.clip(b_np * (1.0 - alpha) + a_np * alpha + 0.5, 0.0, 255.0).astype(np.uint8))
else:
out_im = after_im
exp_root = SLIDER_CACHE_DIR / "lossless_exports"
out_dir = exp_root / uuid.uuid4().hex[:10]
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / safe_name
out_im.save(out_path, format="PNG", compress_level=1)
dirs = sorted([d for d in exp_root.iterdir() if d.is_dir()], key=lambda p: p.stat().st_mtime)
for old_d in dirs[:-30]:
shutil.rmtree(old_d, ignore_errors=True)
return str(out_path)
def _source_digest(img: Image.Image) -> str:
arr = np.asarray(img)
return hashlib.blake2b(np.ascontiguousarray(arr[::4, ::4]).tobytes(), digest_size=12).hexdigest()
def _prune_slider_cache() -> None:
for pat in ("b_*.jpg", "out_*.jpg"):
files = sorted(SLIDER_CACHE_DIR.glob(pat), key=lambda p: p.stat().st_mtime)
for old in files[:-160]:
try:
old.unlink()
except OSError:
pass
def _fast_slider_pair(pair: tuple[Image.Image, Image.Image]) -> tuple[str, str]:
"""Save 4:4:4 high-fidelity JPEGs (`subsampling=0`) for ~7x smaller/faster browser slider display."""
SLIDER_CACHE_DIR.mkdir(parents=True, exist_ok=True)
before, after = pair
b_hash = _source_digest(before)
src_cache = SLIDER_CACHE_DIR / f"src_{before.size[0]}x{before.size[1]}_{b_hash}.jpg"
if not src_cache.is_file():
before.save(src_cache, format="JPEG", quality=93, subsampling=0)
uid = uuid.uuid4().hex[:12]
before_path = SLIDER_CACHE_DIR / f"b_{uid}.jpg"
try:
os.link(src_cache, before_path)
except OSError:
shutil.copy2(src_cache, before_path)
after_path = SLIDER_CACHE_DIR / f"out_{uid}.jpg"
after.save(after_path, format="JPEG", quality=93, subsampling=0)
_prune_slider_cache()
return str(before_path), str(after_path)
def transfer(source, reference, balance, align, auto_res, res_px, seed, randomize):
if source is None or reference is None:
gr.Warning("Upload a source face and a reference makeup photo, or pick them from the examples below.")
return NO_CHANGE_4
seed = _seed(seed, randomize)
mode_key = _resolve_mode(balance)
src_img = _load(source)
ref_img = _load(reference)
if align:
if not ALIGNER.available:
raise gr.Error("Face detector weights are unavailable. Please turn off 'Align face' to run directly.")
src_geom = ALIGNER.detect_geometry(src_img)
if src_geom is None:
raise _no_face_error("Source")
ref_geom = ALIGNER.detect_geometry(ref_img)
if ref_geom is None:
raise _no_face_error("Reference")
target_res = _resolve_res(bool(auto_res), res_px, src_geom.crop_side)
src_rec = ALIGNER.warp_from_geometry(src_img, src_geom, target_res)
ref_rec = ALIGNER.warp_from_geometry(ref_img, ref_geom, target_res)
out, elapsed_s = _run_transfer(src_rec.face, ref_rec.face, seed, mode_key)
pair = ALIGNER.paste_back_pair(src_rec, out, max_side=MAX_SIDE)
crop_pair = (src_rec.face, out)
run_uid = _stash_lossless_run(pair, crop_pair)
return (
_fast_slider_pair(pair),
_fast_slider_pair(crop_pair),
seed,
_format_stats(target_res, elapsed_s, has_crop=True, run_uid=run_uid),
)
target_res = _resolve_res(bool(auto_res), res_px, min(src_img.size))
src_in = center_square(src_img, target_res)
ref_in = center_square(ref_img, target_res)
out, elapsed_s = _run_transfer(src_in, ref_in, seed, mode_key)
pair = (src_in, out)
run_uid = _stash_lossless_run(pair, None)
return (
_fast_slider_pair(pair),
None,
seed,
_format_stats(target_res, elapsed_s, has_crop=False, run_uid=run_uid),
)
def remove(image, align, auto_res, res_px, seed, randomize):
if image is None:
gr.Warning("Upload a portrait with makeup, or pick one from the examples below.")
return NO_CHANGE_4
seed = _seed(seed, randomize)
img = _load(image)
if align:
if not ALIGNER.available:
raise gr.Error("Face detector weights are unavailable. Please turn off 'Align face' to run directly.")
geom = ALIGNER.detect_geometry(img)
if geom is None:
raise _no_face_error("Portrait")
target_res = _resolve_res(bool(auto_res), res_px, geom.crop_side)
rec = ALIGNER.warp_from_geometry(img, geom, target_res)
out, elapsed_s = _run_remove(rec.face, seed)
pair = ALIGNER.paste_back_pair(rec, out, max_side=MAX_SIDE)
crop_pair = (rec.face, out)
run_uid = _stash_lossless_run(pair, crop_pair)
return (
_fast_slider_pair(pair),
_fast_slider_pair(crop_pair),
seed,
_format_stats(target_res, elapsed_s, has_crop=True, run_uid=run_uid),
)
target_res = _resolve_res(bool(auto_res), res_px, min(img.size))
img_in = center_square(img, target_res)
out, elapsed_s = _run_remove(img_in, seed)
pair = (img_in, out)
run_uid = _stash_lossless_run(pair, None)
return (
_fast_slider_pair(pair),
None,
seed,
_format_stats(target_res, elapsed_s, has_crop=False, run_uid=run_uid),
)
# ---------------------------------------------------------------------------
# examples (lightweight @2x preview thumbnails for gallery; full-res on click)
# ---------------------------------------------------------------------------
GALLERY_CACHE_DIR = Path(tempfile.gettempdir()) / "rnv_gallery_thumbs"
def _files(sub: str):
return sorted(str(p) for p in (ROOT / "examples" / sub).glob("*.jpg"))
def _gallery_thumbs(paths: list[str], max_side: int = 320) -> list[str]:
GALLERY_CACHE_DIR.mkdir(parents=True, exist_ok=True)
thumbs: list[str] = []
for p_str in paths:
p = Path(p_str)
st = p.stat()
key = hashlib.blake2b(f"{p.name}:{st.st_size}:{st.st_mtime_ns}:{max_side}".encode(), digest_size=8).hexdigest()
out = GALLERY_CACHE_DIR / f"th_{key}_{p.stem}.jpg"
if not out.is_file():
with Image.open(p) as raw:
im = ImageOps.exif_transpose(raw).convert("RGB")
if max(im.size) > max_side:
im.thumbnail((max_side, max_side), Image.LANCZOS)
im.save(out, format="JPEG", quality=82, optimize=True)
thumbs.append(str(out))
return thumbs
def _res_tier_label(px: int) -> str:
if px <= 608:
return "512"
if px <= 896:
return "768"
if px <= 1152:
return "1K"
if px <= 1472:
return "1.3K"
if px <= 1760:
return "1.5K"
return "2K"
def _compute_source_badges(paths: list[str], aligner: FaceAligner | None = None) -> list[list]:
GALLERY_CACHE_DIR.mkdir(parents=True, exist_ok=True)
sig_str = "|".join(f"{Path(p).name}:{Path(p).stat().st_size}:{Path(p).stat().st_mtime_ns}" for p in paths)
sig = hashlib.blake2b(sig_str.encode(), digest_size=10).hexdigest()
cache_fp = GALLERY_CACHE_DIR / f"src_badges_{sig}.json"
if cache_fp.is_file():
try:
return json.loads(cache_fp.read_text(encoding="utf-8"))
except Exception:
pass
if aligner is None:
aligner = FaceAligner(detector=load_default_detector())
badges: list[list] = []
has_det = aligner.available
for p_str in paths:
with Image.open(p_str) as raw:
im = ImageOps.exif_transpose(raw).convert("RGB")
if has_det:
geom = aligner.detect_geometry(im)
raw_px = geom.crop_side if geom is not None else float(min(im.size))
else:
raw_px = float(min(im.size))
snapped = snap_resolution(raw_px, min_res=AUTO_MIN_RES)
badges.append([_res_tier_label(snapped), int(snapped)])
if has_det:
try:
cache_fp.write_text(json.dumps(badges), encoding="utf-8")
except OSError:
pass
return badges
SOURCES = _files("sources")
REFERENCES = _files("references")
MAKEUP = _files("makeup") or REFERENCES
SRC_BADGES = _compute_source_badges(SOURCES, ALIGNER)
def pick(paths):
def _pick(evt: gr.SelectData):
return paths[evt.index]
return _pick
def gallery(items, label: str, extra_classes: list[str]):
return gr.Gallery(
value=_gallery_thumbs(items),
label=label,
height="auto",
allow_preview=False,
interactive=False,
object_fit="cover",
elem_classes=["rnv-gallery", *extra_classes],
)
# ---------------------------------------------------------------------------
# UI (Obsidian & Rosé editorial studio)
# ---------------------------------------------------------------------------
TIPS = {
"align": "Detects, aligns, and crops faces, then pastes the result back.",
"mode": (
'
Switches makeup transfer strength:
'
'
'
"
Vivid: Reproduces the full makeup look, including foundation and base coverage.
"
"
Balanced: Balances rich makeup reproduction with natural skin-tone blending.
"
"
Faithful: Preserves original skin tone and natural complexion, focusing on eye, lip, and cheek makeup.
"
"
"
),
"opacity": "Post-inference layer opacity: linearly blends the generated result over the original photo without re-running the model.",
"res": "Inference resolution (256–2048 px); Auto matches the aligned Source face crop size.",
"src_examples": "Corner badge shows the aligned face-crop size tier, which determines the Auto inference resolution.",
}
def _fader_html(role: str, pct: float, aria: str, dots: list[float] | None = None) -> str:
dots_html = "".join(f'' for d in (dots or []))
return (
f'