File size: 4,961 Bytes
e06521d
 
 
 
 
 
 
 
 
 
 
 
d62e52c
e06521d
 
 
 
 
c3a9c38
e06521d
 
d62e52c
e06521d
 
 
 
 
 
d62e52c
 
e06521d
 
c3a9c38
e06521d
 
 
 
c3a9c38
 
e06521d
d62e52c
 
 
 
e06521d
 
 
c3a9c38
 
 
e06521d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""IrisMix for the Hugging Face Space (ZeroGPU), on the irismix package (a copy of the repository's).

ZeroGPU gives a GPU only inside @spaces.GPU calls, which run in a worker process: every network is built on the CPU and
moved to `cuda` at import time, and each GPU call is a pure function (photo, references, options -> result and layer), so
nothing has to survive between calls. The layer edits run on the CPU in the main process from the returned arrays. The
IrisMix weights come from a private model repository read with the HF_TOKEN secret; FLUX.2 [klein] 4B, the face parser and
the MediaPipe landmarker are public."""
import os
from pathlib import Path

HERE = Path(__file__).resolve().parent
WEIGHT_REPO = os.environ.get('IRISMIX_WEIGHT_REPO', 'ming0531/IrisMix')
os.environ.setdefault('IRISMIX_CACHE', str(HERE / 'cache'))          # shipped: the decomposer prompt embeddings, landmarker
os.environ.setdefault('IRISMIX_CACHE_ITEMS', '8')


def fetch_weights():
    if 'IRISMIX_WEIGHTS' in os.environ: return
    print('downloading the IrisMix weights', flush=True)
    from huggingface_hub import hf_hub_download
    w = HERE / 'weights'
    for f in ('irismix_lora_init.safetensors', 'irismix_decomposer.safetensors', 'irismix_renderer.safetensors'):
        hf_hub_download(WEIGHT_REPO, f, local_dir=w, token=os.environ.get('HF_TOKEN'))
    os.environ['IRISMIX_WEIGHTS'] = str(w)


fetch_weights()
import numpy as np  # noqa: E402
from irismix import config, decomposer as DEC, pipeline as PL, render as RD  # noqa: E402
from irismix.renderer import Renderer  # noqa: E402
from irismix.viewer.engine import Engine  # noqa: E402

OCCLUDERS = os.environ.get('IRISMIX_SPACE_OCCLUDERS', '0') == '1'   # glasses / bangs need one more transformer


def build_engine():
    """all networks on the CPU, then on `cuda` (ZeroGPU places them when a call gets the GPU)."""
    import time
    t0 = time.time(); log = lambda m: print(f'[{time.time() - t0:6.0f} s] {m}', flush=True)
    e = Engine('cuda', keep_models=True)
    log('loading the decomposer (no text encoder: cached prompt embeddings)')
    e.models['s1'] = DEC.Decomposer(config.DECOMPOSER_CKPT, 'cuda', lora_init=config.LORA_INIT, skip_text_encoder=True)
    log('loading the renderer')
    rm = Renderer('cuda', ckpt=config.RENDERER_CKPT, text_encoder=True, lora_init=config.LORA_INIT); rm.skips.eval()
    e.models['rm'] = rm
    if OCCLUDERS:
        from irismix import occluder as OC
        log('loading the occluder editor (shares the text encoder and VAE)')
        e.models['editor'] = OC.load_editor('cuda', share=rm.p)
    log('models ready')
    return e


ENGINE = build_engine()


def _pack(o):
    """the arrays the CPU edits need, compact for the trip back from the GPU worker."""
    u8 = lambda x: (np.clip(x, 0, 1) * 255 + .5).astype(np.uint8)
    return dict(photo=u8(o['photo']), target=o['target_u8'], paste=u8(o['paste']), result=u8(o['result']),
                alpha=o['alpha'].astype(np.float16), F=o['F'].astype(np.float16), w=o['w'].astype(np.float16), mm=o['mm'],
                mean_L=o['mean_L'], timings=o['timings'], total=o['total'], caption=o.get('caption', ''), rendered=o['rendered'],
                bare=o.get('bare'), free=o.get('free'))


def look(photo, refs, target='as_is', keep=(), xform=None, render=True):
    """photo uint8, refs {slot: uint8} (slot = whole | eyes | lips | face | forehead) -> packed result (GPU)."""
    e = ENGINE
    e.models['rm'].p.text_encoder.to('cuda')               # Engine.run parks it on the CPU after encoding the caption
    e.set_source(photo); e.refs.clear(); e.layers.clear(); e.free.clear()
    for slot, img in refs.items():
        if img is not None: e.set_ref(slot, img)
    e.set_options(target=target, keep=list(keep), xform=xform or dict(dx=0.0, dy=0.0, scale=1.0, mirror=False))
    return _pack(e.run(render=render))


def suggest(photo, cands):
    """rank candidate looks [(name, uint8)] on the photo (GPU): aesthetic + CLIP preference + colour harmony."""
    e = ENGINE
    e.set_source(photo); e.out = {}
    rows = e.recommend_looks(cands)
    return [{k: v for k, v in r.items()} for r in rows]


def edit(st, strength, part_strength, lip_hue, lip_rgb, soft_eyes, soft_lips, finish):
    """closed-form edit of the returned layer on the CPU -> uint8 image."""
    rec = {}
    if lip_rgb:
        from irismix.shades import lab1, hex2rgb
        rec['lips'] = [float(x) for x in lab1(hex2rgb(lip_rgb))]
    out, _, _ = PL.apply_edits(st['alpha'].astype(np.float32), st['F'].astype(np.float32), st['target'], st['w'].astype(np.float32),
                               strength, (), rec or None, {'lips': lip_hue} if lip_hue else None, part_strength,
                               {k: v for k, v in (('eyes', soft_eyes), ('lips', soft_lips)) if v} or None,
                               {'lips': finish} if finish else None, st['mm'])
    return (np.clip(out, 0, 1) * 255 + .5).astype(np.uint8)