Download app.py from ming0531/IrisMix: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/ming0531/IrisMix/resolve/main/app.py
- Command line
-
hf download hf://spaces/ming0531/IrisMix/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ming0531/IrisMix/resolve/main/app.py
18.6 kB
| """IrisMix Studio (Hugging Face Space, ZeroGPU). | |
| 1. Photo and look: upload or paste a photo and one reference for the whole look (or one per part); optional preparation: | |
| remove the photo's own makeup (re-make-up, optionally keeping some of its parts) or lift glasses / bangs off. | |
| 2. Transfer (the decomposer + transfer rules) or Render (adds the one-step the renderer render and the closed-form layer recovery). | |
| 3. The recovered layer is edited on the CPU without another network call: strength, per-part strength, lip colour and | |
| hue, softness, lip finish. Suggest ranks the example looks for the photo. | |
| """ | |
| import json | |
| import os | |
| import time | |
| import gradio as gr | |
| import numpy as np | |
| import spaces | |
| from PIL import Image | |
| import engine_space as ES | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| EX = os.path.join(HERE, 'assets', 'examples') | |
| MAN = json.load(open(os.path.join(EX, 'examples.json'))) | |
| FACES = [os.path.join(EX, e['file']) for e in MAN['sources']] | |
| LOOKS = [os.path.join(EX, e['file']) for e in MAN['references']] | |
| LOOK_NAMES = [e['name'] for e in MAN['references']] | |
| PARTS = ['lips', 'eyes', 'brows', 'face', 'forehead'] | |
| TARGET = {'As is': 'as_is', 'Remove makeup': 'remake', 'Glasses': 'glasses', 'Bangs': 'bangs'} | |
| if not ES.OCCLUDERS: TARGET = {k: v for k, v in TARGET.items() if v not in ('glasses', 'bangs')} | |
| MAX_SIDE = 1280 | |
| ROSE = gr.themes.Color(c50='#fdf4f5', c100='#fae7ea', c200='#f4cfd5', c300='#ebb0ba', c400='#e3949f', c500='#d9798a', | |
| c600='#c25f70', c700='#a24b5a', c800='#7f3c48', c900='#63313a', c950='#401f25', name='rose_irismix') | |
| THEME = gr.themes.Soft(primary_hue=ROSE, secondary_hue=ROSE, neutral_hue='stone', radius_size='lg', | |
| font=[gr.themes.Font('Pretendard'), gr.themes.Font('Apple SD Gothic Neo'), 'sans-serif']).set( | |
| body_background_fill='#f7f1ef', block_background_fill='#ffffff', block_border_color='#f0e4e1', block_border_width='1px', | |
| block_label_background_fill='rgba(255,255,255,.92)', block_label_text_color='#8b7b7f', block_label_text_weight='500', | |
| block_title_text_color='#4a3b3f', block_title_text_weight='600', block_title_text_size='13px', | |
| block_label_border_width='0px', block_shadow='none', | |
| input_background_fill='#fbf7f6', slider_color='*primary_400', | |
| checkbox_label_background_fill='#fbf7f6', checkbox_label_background_fill_selected='*primary_50', | |
| checkbox_label_text_color_selected='*primary_700', checkbox_label_border_color_selected='*primary_300', | |
| checkbox_background_color_selected='*primary_500', checkbox_border_color_selected='*primary_500', | |
| button_primary_background_fill='linear-gradient(135deg, #e3949f, #c25f70)', | |
| button_primary_background_fill_hover='linear-gradient(135deg, #d9798a, #a24b5a)', | |
| button_primary_text_color='#ffffff', button_primary_border_color='transparent', | |
| button_secondary_background_fill='#ffffff', button_secondary_border_color='#ebdcd8', button_secondary_text_color='#4a3b3f', | |
| color_accent='*primary_500', color_accent_soft='*primary_50', border_color_accent='*primary_300') | |
| CSS = """ | |
| @import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css'); | |
| .gradio-container { max-width: 1480px !important; font-family: Pretendard, 'Apple SD Gothic Neo', sans-serif !important; } | |
| #hdr { display: flex; align-items: center; gap: 12px; padding: 10px 6px 0; flex-wrap: wrap; } | |
| #hdr .logo { width: 34px; height: 34px; border-radius: 50%; background: radial-gradient(circle at 50% 50%, #fff 0 26%, #e3949f 28%, #c25f70 100%); | |
| box-shadow: 0 4px 14px rgba(194,95,112,.35); } | |
| #hdr b { font-size: 24px; letter-spacing: -.03em; color: #2e2326; } | |
| #hdr .pill { font-size: 12px; color: #a24b5a; background: #fae7ea; padding: 4px 12px; border-radius: 99px; font-weight: 600; } | |
| #hdr .links { margin-left: auto; display: flex; gap: 8px; } | |
| #hdr .links a { font-size: 13px; color: #4a3b3f; text-decoration: none; padding: 6px 14px; border-radius: 99px; background: #fff; | |
| border: 1px solid #ebdcd8; transition: .15s; } | |
| #hdr .links a:hover { border-color: #e3949f; color: #a24b5a; } | |
| #sub { color: #8b7b7f; font-size: 13.5px; margin: 4px 6px 10px; } | |
| .card { background: #fff !important; border: 1px solid #f0e4e1 !important; border-radius: 22px !important; | |
| box-shadow: 0 10px 30px rgba(120,70,80,.06) !important; padding: 16px !important; gap: 10px !important; } | |
| .step h3 { font-size: 15px !important; margin: 2px 0 0 !important; color: #2e2326; font-weight: 700; letter-spacing: -.01em; } | |
| .step h3 .n { display: inline-flex; width: 22px; height: 22px; border-radius: 50%; background: #fae7ea; color: #a24b5a; font-size: 12px; | |
| align-items: center; justify-content: center; margin-right: 8px; vertical-align: 1px; } | |
| .step h3 .hint { font-weight: 500; font-size: 12px; color: #a99a9d; margin-left: 6px; } | |
| .strip .grid-wrap { overflow-x: auto !important; overflow-y: hidden !important; padding: 2px 0 8px !important; height: auto !important; } | |
| .strip .grid-container { grid-auto-flow: column !important; grid-template-columns: none !important; grid-template-rows: 64px !important; | |
| grid-auto-columns: 64px !important; grid-auto-rows: unset !important; gap: 8px !important; } | |
| .strip .thumbnail-item { border-radius: 14px !important; border: 2px solid transparent !important; box-shadow: none !important; } | |
| .strip .thumbnail-item:hover, .strip .thumbnail-item.selected { border-color: #e3949f !important; } | |
| .strip .grid-wrap::-webkit-scrollbar { height: 6px; } .strip .grid-wrap::-webkit-scrollbar-thumb { background: #ebd6d9; border-radius: 9px; } | |
| .actions { gap: 10px !important; } | |
| .wide-only { padding-bottom: 6px !important; border-bottom: 1px solid #f3e8e5; margin-bottom: 2px; } | |
| .narrow-only { display: none !important; } | |
| .actions button { height: 48px !important; font-size: 15px !important; font-weight: 600 !important; border-radius: 14px !important; } | |
| button.render { box-shadow: 0 8px 20px rgba(194,95,112,.32) !important; } | |
| #status { font-size: 13px; color: #7d6d71; background: #fbf5f4; border-radius: 12px; padding: 8px 12px; } | |
| #status p { margin: 0 !important; } | |
| .tabs .tab-nav button, .tab-wrapper button { font-weight: 600 !important; } | |
| .tab-wrapper button.selected, .tabs button.selected { color: #a24b5a !important; } | |
| .tab-wrapper button.selected::after { background: #c25f70 !important; } | |
| .segment .wrap { gap: 6px !important; } | |
| #download { border-radius: 14px !important; } | |
| label[data-testid="block-label"], .block-label { border-radius: 99px !important; padding: 3px 10px !important; | |
| box-shadow: 0 1px 4px rgba(80,40,50,.08) !important; } | |
| .strip { padding-top: 26px !important; } | |
| .strip label[data-testid="block-label"] { box-shadow: none !important; padding-left: 2px !important; } | |
| .sticky { position: sticky !important; top: 12px; align-self: flex-start; } | |
| footer { display: none !important; } | |
| @media (max-width: 900px) { #hdr .links { margin-left: 0; } .sticky { position: static !important; } | |
| .wide-only { display: none !important; } .narrow-only { display: flex !important; } } | |
| """ | |
| HEADER = """<div id="hdr"><span class="logo"></span><b>IrisMix</b><span class="pill">Makeup Studio</span> | |
| <span class="links"><a href="https://ming053l.github.io/IrisMix/" target="_blank">Project page</a> | |
| <a href="https://github.com/ming053l/IrisMix" target="_blank">GitHub</a> | |
| <a href="https://ming053l.github.io/images/web/irismix-teaser.mp4" target="_blank">Video</a></span></div> | |
| <div id="sub">Compose a makeup look from reference photos, render it on a face, and keep editing the makeup layer afterwards.</div>""" | |
| def step(n, title, hint=''): | |
| return gr.Markdown(f'### <span class="n">{n}</span>{title}' + (f'<span class="hint">{hint}</span>' if hint else ''), elem_classes='step') | |
| def strip(paths, label): | |
| return gr.Gallery(paths, label=label, columns=len(paths), rows=1, height=86, allow_preview=False, object_fit='cover', | |
| show_download_button=False, show_fullscreen_button=False, show_share_button=False, elem_classes='strip') | |
| def fit(img): | |
| if img is None: return None | |
| img = np.asarray(img)[..., :3] | |
| h, w = img.shape[:2]; s = min(1.0, MAX_SIDE / max(h, w)) | |
| if s < 1: img = np.asarray(Image.fromarray(img).resize((round(w * s), round(h * s)), Image.LANCZOS)) | |
| return np.ascontiguousarray(img) | |
| def gpu_look(photo, refs, target, keep, xform, render): | |
| t0 = time.perf_counter() | |
| out = ES.look(photo, refs, target, keep, xform, render) | |
| out['gpu_s'] = time.perf_counter() - t0 | |
| return out | |
| def gpu_suggest(photo, cands): | |
| return ES.suggest(photo, cands) | |
| def checker(st): | |
| a = st['alpha'].astype(np.float32)[..., None]; F = st['F'].astype(np.float32) | |
| h, w = a.shape[:2]; yy, xx = np.mgrid[:h, :w] | |
| ck = np.where(((yy // 16 + xx // 16) % 2)[..., None] == 0, 0.97, 0.88).astype(np.float32) | |
| return (np.clip(a * F + (1 - a) * ck, 0, 1) * 255 + .5).astype(np.uint8) | |
| def do_edit(st, strength, p0, p1, p2, p3, p4, lip_hue, lip_on, lip_col, soft_eyes, soft_lips, finish): | |
| if not st: return None, None | |
| img = ES.edit(st, strength, [p0, p1, p2, p3, p4], lip_hue, lip_col if lip_on else None, soft_eyes, soft_lips, finish) | |
| path = os.path.join(os.environ.get('GRADIO_TEMP_DIR', '/tmp'), f'irismix_{int(time.time() * 1000)}.png') | |
| Image.fromarray(img).save(path) | |
| return (st['photo'], img), path | |
| def run(render, photo, mode, whole, eyes, lips, face, forehead, prepare, keep, dx, dy, scale, mirror, *edits): | |
| photo = fit(photo) | |
| if photo is None: raise gr.Error('Upload or paste a photo first.') | |
| refs = {'whole': fit(whole)} if mode == 'Whole look' else {k: fit(v) for k, v in | |
| (('eyes', eyes), ('lips', lips), ('face', face), ('forehead', forehead)) if v is not None} | |
| target = TARGET[prepare] | |
| if not any(v is not None for v in refs.values()) and not (target == 'remake' and keep): | |
| raise gr.Error('Choose a look: one reference for the whole look, or at least one part.') | |
| try: | |
| st = gpu_look(photo, refs, target, list(keep or []), dict(dx=dx, dy=dy, scale=scale, mirror=bool(mirror)), render) | |
| except Exception as e: | |
| raise gr.Error(str(e)) | |
| slider, path = do_edit(st, *edits) | |
| t = st['timings']; f = lambda x: f'{x * 1000:.0f} ms' if x < 1 else f'{x:.2f} s' | |
| status = ' · '.join([f'{k} {f(v)}' for k, v in t.items()] + [f'total {f(st["total"])}']) | |
| prep = st['bare'] if st.get('bare') is not None else st['free'] | |
| return (st, slider, st['result'] if st['rendered'] else None, st['paste'], checker(st), prep, path, | |
| f'**{"Rendered" if st["rendered"] else "Transferred (preview)"}.** {status}. Edit the layer on the right; no further GPU time is needed.') | |
| def suggest(photo): | |
| photo = fit(photo) | |
| if photo is None: raise gr.Error('Upload or paste a photo first.') | |
| cands = [(n, fit(np.asarray(Image.open(p).convert('RGB')))) for n, p in zip(LOOK_NAMES, LOOKS)] | |
| rows = gpu_suggest(photo, cands) | |
| ok = [r for r in rows if 'score' in r] | |
| gal = [(r['crop'], f"{r['name']} · {r['score']:.0f}") for r in ok] | |
| md = '\n'.join(f"{k + 1}. **{r['name']}** ({r['score']:.0f}): " + '; '.join(_reason(x) for x in r['reasons']) for k, r in enumerate(ok[:6])) | |
| return gal, [r['i'] for r in ok], md | |
| def _reason(x): | |
| if x['part'] == 'lips': | |
| rel = {'match': 'match', 'warmer': 'are warmer than', 'cooler': 'are cooler than', 'neutral': 'suit'}[x['rel']] | |
| return f"{x['colour']} lips {rel} your {x['ut']} undertone" | |
| return f"{x['colour']} eyes {'flatter' if x['rel'] == 'flatter' else 'contrast with'} your {x['ut']} colouring" | |
| def pick(order, evt: gr.SelectData): | |
| return rgb(LOOKS[order[evt.index]]), 'Whole look' | |
| SLOTS = ['Eyes', 'Lips', 'Face', 'Forehead'] | |
| def rgb(path): return np.asarray(Image.open(path).convert('RGB')) | |
| def pick_face(evt: gr.SelectData): return rgb(FACES[evt.index]) | |
| def pick_look(mode, slot, evt: gr.SelectData): | |
| """an example look goes to the whole-look reference, or to the chosen part tab.""" | |
| img = rgb(LOOKS[evt.index]) | |
| if mode == 'Whole look': return [img] + [gr.update()] * len(SLOTS) + [gr.update()] | |
| return [gr.update()] + [img if s == slot else gr.update() for s in SLOTS] + [gr.Tabs(selected=slot)] | |
| with gr.Blocks(title='IrisMix Studio', css=CSS, theme=THEME) as demo: | |
| gr.HTML(HEADER) | |
| st = gr.State(None); order = gr.State([]) | |
| with gr.Row(equal_height=False): | |
| with gr.Column(scale=4, elem_classes='card'): | |
| step(1, 'Photo', 'upload · paste · webcam') | |
| photo = gr.Image(label='Your photo', type='numpy', sources=['upload', 'clipboard', 'webcam'], height=280, value=FACES[0]) | |
| faces = strip(FACES, 'Or try an example face') | |
| prepare = gr.Radio(list(TARGET), value='As is', label='Before the transfer', elem_classes='segment') | |
| keep = gr.CheckboxGroup(PARTS, label='Keep from my own makeup', visible=False) | |
| step(2, 'Look', 'one photo, or one per part') | |
| mode = gr.Radio(['Whole look', 'Mix per part'], value='Whole look', show_label=False, elem_classes='segment') | |
| with gr.Group(visible=True) as wholebox: | |
| whole = gr.Image(label='Makeup reference', type='numpy', sources=['upload', 'clipboard'], height=220, value=LOOKS[0]) | |
| with gr.Group(visible=False) as partbox: | |
| with gr.Tabs(selected='Eyes') as part_tabs: | |
| part_imgs = [] | |
| for s in SLOTS: | |
| with gr.Tab(s, id=s): | |
| part_imgs.append(gr.Image(type='numpy', sources=['upload', 'clipboard'], height=200, show_label=False)) | |
| eyes, lips, face, forehead = part_imgs | |
| slot = gr.Radio(SLOTS, value='Eyes', label='Example looks go to', elem_classes='segment') | |
| looks = strip(LOOKS, 'Example looks') | |
| with gr.Accordion('Place face paint · move, scale, mirror', open=False): | |
| dx = gr.Slider(-0.4, 0.4, 0, step=0.01, label='Left / right') | |
| dy = gr.Slider(-0.4, 0.4, 0, step=0.01, label='Up / down') | |
| scale = gr.Slider(0.5, 1.6, 1, step=0.01, label='Scale') | |
| mirror = gr.Checkbox(False, label='Mirror') | |
| with gr.Row(elem_classes=['actions', 'narrow-only']): # phones: the buttons follow the inputs | |
| m_transfer = gr.Button('Preview', size='lg', scale=2, min_width=0) | |
| m_render = gr.Button('✨ Render', variant='primary', size='lg', scale=3, min_width=0, elem_classes='render') | |
| with gr.Column(scale=6, elem_classes='card'): | |
| step(3, 'Result', 'drag the handle to compare') | |
| slider = gr.ImageSlider(show_label=False, type='numpy', height=600) | |
| status = gr.Markdown('Pick a photo and a look, then press ✨ Render.', elem_id='status') | |
| with gr.Accordion('Intermediate steps', open=False): | |
| with gr.Tabs(): | |
| with gr.Tab('Render'): render_img = gr.Image(type='numpy', show_label=False, height=280, interactive=False) | |
| with gr.Tab('Warp only'): warp_img = gr.Image(type='numpy', show_label=False, height=280, interactive=False) | |
| with gr.Tab('Makeup layer'): layer_img = gr.Image(type='numpy', show_label=False, height=280, interactive=False) | |
| with gr.Tab('Prepared face'): prep_img = gr.Image(type='numpy', show_label=False, height=280, interactive=False) | |
| download = gr.DownloadButton('Download the edited image', elem_id='download') | |
| with gr.Column(scale=4, elem_classes=['card', 'sticky']): | |
| with gr.Row(elem_classes=['actions', 'wide-only']): # desktop: always in view beside the result | |
| b_transfer = gr.Button('Preview', size='lg', scale=2, min_width=0) | |
| b_render = gr.Button('✨ Render', variant='primary', size='lg', scale=3, min_width=0, elem_classes='render') | |
| step(4, 'Edit the layer', 'live · no GPU') | |
| with gr.Tabs(): | |
| with gr.Tab('Adjust'): | |
| strength = gr.Slider(0, 1.5, 1, step=0.01, label='Overall strength') | |
| ps = [gr.Slider(0, 1.5, 1, step=0.01, label=p.capitalize()) for p in PARTS] | |
| with gr.Tab('Colour & finish'): | |
| with gr.Row(): | |
| lip_on = gr.Checkbox(False, label='Recolour lips') | |
| lip_col = gr.ColorPicker('#b8323f', label='Lip colour') | |
| lip_hue = gr.Slider(-180, 180, 0, step=1, label='Lip hue (°)') | |
| finish = gr.Slider(-1, 1, 0, step=0.05, label='Lip finish · matte ↔ glossy') | |
| soft_eyes = gr.Slider(0, 5, 0, step=0.1, label='Eye softness (mm)') | |
| soft_lips = gr.Slider(0, 3, 0, step=0.1, label='Lip softness (mm)') | |
| with gr.Tab('Suggest'): | |
| gr.Markdown('Try every example look on this photo and rank them by an aesthetic score and colour harmony with ' | |
| 'the skin. Click a result to use it.') | |
| b_suggest = gr.Button('Find looks for this face', variant='primary') | |
| gallery = gr.Gallery(columns=3, height=420, show_label=False, allow_preview=False, object_fit='cover') | |
| reasons = gr.Markdown() | |
| edits = [strength, *ps, lip_hue, lip_on, lip_col, soft_eyes, soft_lips, finish] | |
| ins = [photo, mode, whole, eyes, lips, face, forehead, prepare, keep, dx, dy, scale, mirror, *edits] | |
| outs = [st, slider, render_img, warp_img, layer_img, prep_img, download, status] | |
| for b in (b_transfer, m_transfer): b.click(lambda *a: run(False, *a), ins, outs) | |
| for b in (b_render, m_render): b.click(lambda *a: run(True, *a), ins, outs) | |
| for c in edits: c.change(do_edit, [st, *edits], [slider, download], show_progress='hidden') | |
| lip_col.change(lambda: True, None, lip_on, show_progress='hidden') | |
| mode.change(lambda m: (gr.update(visible=m == 'Whole look'), gr.update(visible=m != 'Whole look')), mode, [wholebox, partbox]) | |
| prepare.change(lambda p: gr.update(visible=p == 'Remove makeup'), prepare, keep) | |
| faces.select(pick_face, None, photo) | |
| looks.select(pick_look, [mode, slot], [whole, *part_imgs, part_tabs]) | |
| slot.change(lambda s: gr.Tabs(selected=s), slot, part_tabs) | |
| b_suggest.click(suggest, photo, [gallery, order, reasons]) | |
| gallery.select(pick, order, [whole, mode]) | |
| if __name__ == '__main__': | |
| demo.queue(max_size=20).launch(show_api=False) | |