Update app.py
Browse files16 unmodified lines171819202122268 unmodified lines291292293294295296264 unmodified lines5615625635645655661 unmodified line568569570571572573574575576577578105 unmodified lines68468568668768868969069169251 unmodified lines7447457467477487497507517527537547557567573 unmodified lines7617627637647657667677687697707717727736 unmodified lines7807817827837847856 unmodified lines79279379479579679779813 unmodified lines81281381481581681722 unmodified lines84084184284384484584684784884985085185223 unmodified lines87687787887988088111 unmodified lines8938948958968978988999009019029039049059069079089091 unmodified line91191291391491591691713 unmodified lines93193293393493593642 unmodified lines97998098198298398414 unmodified lines99910001001100210031004100514 unmodified lines10201021102210231024102516 unmodified linesNude frame mode: fresh render same seed (default), fresh render new seed,or reveal from the clothed picture (img2img). LoRA slot and sampler dropdown.Compel weights the clothed and nude words so the two frames really differ.Fiction only. Adult women 21+ (late 20s) only."""268 unmodified linesART_KIND = {ART_CARTOON: "anime", ART_PHOTO: "photo"}STYLE_RANDOM = "Roll random"FIELDS = ["chef", "style", "scene", "outfit", "nude_look", "pose", "light", "camera", "woman"]# ---------------------------------------------------------------------------264 unmodified lines_pipe_chef = None_img2img = None_base_sched_config = Nonedef _hf_token():1 unmodified linedef unload_pipe():global _pipe, _pipe_chef, _img2img, _base_sched_config_pipe = None_pipe_chef = None_img2img = None_base_sched_config = Nonegc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()105 unmodified linesreturn Nonedef _gpu(fn):# 90 s reservation: ZeroGPU checks this against your remaining daily timereturn spaces.GPU(duration=90)(fn) if SPACES_AVAILABLE else fnWEIGHT_SYNTAX = re.compile(r"\(([^()]*)\)[0-9.]+")51 unmodified lines@_gpudef render_frames(chef_name, frames, seeds, steps, guidance_scale, width, height,nude_mode=DEFAULT_NUDE_MODE, reveal_strength=DEFAULT_REVEAL_STRENGTH,lora=None, lora_strength=DEFAULT_LORA_STRENGTH, sampler=DEFAULT_SAMPLER):"""frames: list of (label, positive, negative); seeds: one seed per frame.Frame 1 is always txt2img. Later frames are txt2img with their own prompt(fresh render modes) or img2img on frame 1 (reveal mode)."""pipe = get_pipe(chef_name)device = "cuda" if torch.cuda.is_available() else "cpu"lora_note = apply_lora(pipe, lora, lora_strength)images = []encoders = []3 unmodified linesgen = torch.Generator(device=device).manual_seed(int(seeds[i]))prompt_kwargs, enc_name = _prompt_kwargs(pipe, positive, negative)encoders.append(enc_name)if nude_mode == NUDE_MODE_REVEAL and i > 0 and first_image is not None:i2i = get_img2img(pipe)i2i.scheduler = make_scheduler(sampler)out = i2i(**prompt_kwargs,image=first_image.copy(),strength=float(reveal_strength),num_inference_steps=int(steps),guidance_scale=float(guidance_scale),generator=gen,6 unmodified lineslogger.warning(f"sampler {sampler} failed, keeping current: {e}")out = pipe(**prompt_kwargs,num_inference_steps=int(steps),guidance_scale=float(guidance_scale),width=int(width),6 unmodified linesfinally:if lora_note:clear_lora(pipe)return images, lora_note, encoders# ---------------------------------------------------------------------------13 unmodified linesdef _cook(recipe, seed, tease_reveal, extra, size_name, steps, guidance_scale,nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,username, gallery_items, history):"""Shared render path for Spin and Re-roll. Returns UI outputs."""user_key = username or "anonymous"22 unmodified linesseeds = [seed] + [random.randint(0, 2**31 - 1) for _ in frames[1:]]else:seeds = [seed] * len(frames)LAST_GEN_TIME[user_key] = nowtry:results, lora_note, encoders = render_frames(recipe["chef"], frames, seeds, use_steps, use_guidance, width, height,nude_mode=use_mode, reveal_strength=use_reveal_strength,lora=lora, lora_strength=use_lora_strength, sampler=use_sampler,)except Exception as e:logger.exception("render failed")23 unmodified lines]if use_mode == NUDE_MODE_REVEAL:notes.append(f"Reveal strength {use_reveal_strength:.2f}")if lora:notes.append(f"LoRA: {lora_note}" if lora_note else f"LoRA {lora[0]} failed to load, rendered without it")prompt_text = prompt_text + "\n\n[Settings]\n" + "\n".join(notes)11 unmodified linesdef on_spin(recipe, art_mode, style_pick, new_woman, tease_reveal, extra, size_name, steps, guidance_scale,seed_value, nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,username, gallery_items, history, *lock_flags):rolled = roll_recipe(recipe, _locks_from_flags(lock_flags), new_woman=bool(new_woman),art_mode=art_mode, style_pick=style_pick)return _cook(rolled, _resolve_seed(seed_value), tease_reveal, extra, size_name, steps,guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,lora_repo, lora_file, sampler, username, gallery_items, history)def on_reroll_history(choice, tease_reveal, extra, size_name, steps, guidance_scale,nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,username, gallery_items, history):history = list(history or [])labels = [history_label(i, h) for i, h in enumerate(history)]if not choice or choice not in labels:1 unmodified linepicked = history[labels.index(choice)]["recipe"]return _cook(dict(picked), _resolve_seed(-1), tease_reveal, extra, size_name, steps,guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,lora_repo, lora_file, sampler, username, gallery_items, history)def on_load_history(choice, history):13 unmodified linesreturn rolled, recipe_card(rolled), "\n\n".join(f"[{l}]\n{p}" for l, p, _ in frames)def on_art_mode(art_mode, style_pick):"""Refill the Style dropdown with the styles that suit the art mode."""pool = styles_for_mode(art_mode)42 unmodified linesreveal_strength = gr.Slider(REVEAL_MIN, REVEAL_MAX, value=DEFAULT_REVEAL_STRENGTH, step=0.05,label="Reveal strength (reveal mode only; low keeps more of the clothed picture)")extra = gr.Textbox(label="Extra tags (optional)", placeholder="e.g. glossy lips, rain on skin")with gr.Accordion("LoRA and sampler", open=False):lora_choice = gr.Dropdown(LORA_CHOICES, value=LORA_NONE, label="LoRA")lora_strength = gr.Slider(0.0, 1.5, value=DEFAULT_LORA_STRENGTH, step=0.05, label="LoRA strength")14 unmodified linesreroll_btn = gr.Button("Re-roll this recipe, new seed")load_btn = gr.Button("Load into card (then lock and spin)")advanced = [nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler]outputs = [gallery, gallery_state, card, prompt_box, recipe_state, history_state, history_dd]spin_btn.click(14 unmodified linesinputs=[recipe_state, art_mode, style_pick, new_woman, tease_reveal, extra] + lock_boxes,outputs=[recipe_state, card, prompt_box],)art_mode.change(on_art_mode, inputs=[art_mode, style_pick], outputs=[style_pick])demo.load(fn=None, inputs=None, outputs=[user_id], js=js_visitor)return demo16 unmodified lines171819202122232425268 unmodified lines294295296297298299300301302303304305306307308309310311312313314315316317318319320321264 unmodified lines5865875885895905915921 unmodified line594595596597598599600601602603604605105 unmodified lines71171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878951 unmodified lines8418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778783 unmodified lines8828838848858868878888898908918928938948958968978988999009016 unmodified lines9089099109119129139146 unmodified lines92192292392492592692713 unmodified lines94194294394494594694722 unmodified lines97097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100523 unmodified lines1029103010311032103310341035103610371038103910401041104210431044104511 unmodified lines1057105810591060106110621063106410651066106710681069107010711072107310741075107610771 unmodified line1079108010811082108310841085108613 unmodified lines11001101110211031104110511061107110811091110111111121113111442 unmodified lines1157115811591160116111621163116411651166116711681169117014 unmodified lines1185118611871188118911901191119214 unmodified lines1207120812091210121112121213121416 unmodified linesNude frame mode: fresh render same seed (default), fresh render new seed,or reveal from the clothed picture (img2img). LoRA slot and sampler dropdown.Compel weights the clothed and nude words so the two frames really differ.Picture upload (optional): "Copy the look" steers style, outfit and mood withIP-Adapter; "Redraw my pic" repaints your picture with img2img. Faces alwayscome from the random deck, never from the uploaded picture.Fiction only. Adult women 21+ (late 20s) only."""268 unmodified linesART_KIND = {ART_CARTOON: "anime", ART_PHOTO: "photo"}STYLE_RANDOM = "Roll random"# Reference picture uploadPIC_OFF = "Off"PIC_LOOK = "Copy the look"PIC_REDRAW = "Redraw my pic"PIC_MODES = [PIC_OFF, PIC_LOOK, PIC_REDRAW]DEFAULT_PIC_MODE = PIC_OFFDEFAULT_LOOK_STRENGTH = 0.6LOOK_MIN, LOOK_MAX = 0.2, 1.0DEFAULT_REDRAW_STRENGTH = 0.6REDRAW_MIN, REDRAW_MAX = 0.3, 0.9# IP-Adapter for SDXL, ViT-H variant (file list checked on the HF Hub API, Oct 24 2026).# General look adapter only: the face adapters in that repo are deliberately not used.IP_REPO = "h94/IP-Adapter"IP_SUBFOLDER = "sdxl_models"IP_WEIGHT = "ip-adapter_sdxl_vit-h.safetensors"IP_ENCODER_FOLDER = "models/image_encoder" # ViT-H encoder, 2.5 GB (smaller than the bigG one)IP_FILES = [f"{IP_SUBFOLDER}/{IP_WEIGHT}",f"{IP_ENCODER_FOLDER}/config.json",f"{IP_ENCODER_FOLDER}/model.safetensors",]FIELDS = ["chef", "style", "scene", "outfit", "nude_look", "pose", "light", "camera", "woman"]# ---------------------------------------------------------------------------264 unmodified lines_pipe_chef = None_img2img = None_base_sched_config = None_ip_loaded = Falsedef _hf_token():1 unmodified linedef unload_pipe():global _pipe, _pipe_chef, _img2img, _base_sched_config, _ip_loaded_pipe = None_pipe_chef = None_img2img = None_base_sched_config = None_ip_loaded = Falsegc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()105 unmodified linesreturn Nonedef prefetch_ip_adapter():"""Download the IP-Adapter files on the CPU side, before the GPU clock starts.Returns None when ready, or an error string."""try:for f in IP_FILES:hf_hub_download(IP_REPO, f, token=_hf_token())return Noneexcept Exception as e:logger.warning(f"IP-Adapter download failed: {e}")return str(e)def ensure_ip_adapter(pipe, want):"""Load IP-Adapter once per cached chef, or unload it when not wanted.Returns (ok, error_text). The img2img twin is rebuilt after any change so itpicks up the new image encoder and attention processors."""global _ip_loaded, _img2imgif want and not _ip_loaded:try:pipe.load_ip_adapter(IP_REPO, subfolder=IP_SUBFOLDER, weight_name=IP_WEIGHT,image_encoder_folder=IP_ENCODER_FOLDER, token=_hf_token(),)_ip_loaded = True_img2img = Nonelogger.info("IP-Adapter loaded")except Exception as e:logger.warning(f"IP-Adapter load failed, rendering without it: {e}")try:pipe.unload_ip_adapter()except Exception:pass_ip_loaded = False_img2img = Nonereturn False, str(e)elif not want and _ip_loaded:try:pipe.unload_ip_adapter()except Exception as e:logger.warning(f"IP-Adapter unload warning: {e}")_ip_loaded = False_img2img = Nonereturn (_ip_loaded if want else True), Nonedef fit_picture(img, width, height):"""Resize and center crop the upload to the chosen size preset."""from PIL import Image, ImageOpsif img is None:return Noneif not isinstance(img, Image.Image):img = Image.fromarray(img)return ImageOps.fit(img.convert("RGB"), (int(width), int(height)), Image.LANCZOS)def _gpu_duration(*args, **kwargs):# Copy the look may load IP-Adapter onto the GPU, so it gets a little more roomreturn 120 if kwargs.get("picture_mode") == PIC_LOOK else 90def _gpu(fn):# 90 s reservation (120 s with Copy the look): ZeroGPU checks this against your remaining daily timeif not SPACES_AVAILABLE:return fntry:return spaces.GPU(duration=_gpu_duration)(fn)except Exception as e:logger.warning(f"dynamic GPU duration not supported ({e}), using 120 s")return spaces.GPU(duration=120)(fn)WEIGHT_SYNTAX = re.compile(r"\(([^()]*)\)[0-9.]+")51 unmodified lines@_gpudef render_frames(chef_name, frames, seeds, steps, guidance_scale, width, height,nude_mode=DEFAULT_NUDE_MODE, reveal_strength=DEFAULT_REVEAL_STRENGTH,lora=None, lora_strength=DEFAULT_LORA_STRENGTH, sampler=DEFAULT_SAMPLER,ref_image=None, picture_mode=DEFAULT_PIC_MODE,look_strength=DEFAULT_LOOK_STRENGTH, redraw_strength=DEFAULT_REDRAW_STRENGTH):"""frames: list of (label, positive, negative); seeds: one seed per frame.No picture: frame 1 is txt2img; later frames are txt2img (fresh modes) orimg2img on frame 1 (reveal mode).Copy the look: same as above, with IP-Adapter steering every frame.Redraw my pic: frame 1 is img2img from the upload; the nude frame is img2imgfrom the upload too (strength + 0.1), unless reveal mode is on.ref_image arrives already fitted to width x height."""pipe = get_pipe(chef_name)device = "cuda" if torch.cuda.is_available() else "cpu"use_look = picture_mode == PIC_LOOK and ref_image is not Noneuse_redraw = picture_mode == PIC_REDRAW and ref_image is not Noneip_ok, ip_error = ensure_ip_adapter(pipe, use_look)ip_kwargs = {}if use_look and ip_ok:try:pipe.set_ip_adapter_scale(float(look_strength))ip_kwargs = {"ip_adapter_image": ref_image}except Exception as e:logger.warning(f"IP-Adapter scale failed, rendering without it: {e}")ip_error = str(e)ensure_ip_adapter(pipe, False)ip_ok = Falseif use_look:ip_note = (f"on at {float(look_strength):.2f}" if ip_kwargselse f"failed, rendered without it ({str(ip_error)[:160]})")else:ip_note = Nonelora_note = apply_lora(pipe, lora, lora_strength)images = []encoders = []3 unmodified linesgen = torch.Generator(device=device).manual_seed(int(seeds[i]))prompt_kwargs, enc_name = _prompt_kwargs(pipe, positive, negative)encoders.append(enc_name)source, strength = None, Noneif nude_mode == NUDE_MODE_REVEAL and i > 0 and first_image is not None:source, strength = first_image, float(reveal_strength)elif use_redraw:bump = 0.0 if i == 0 else 0.1source, strength = ref_image, min(REDRAW_MAX, float(redraw_strength) + bump)if source is not None:i2i = get_img2img(pipe)i2i.scheduler = make_scheduler(sampler)out = i2i(**prompt_kwargs,**ip_kwargs,image=source.copy(),strength=strength,num_inference_steps=int(steps),guidance_scale=float(guidance_scale),generator=gen,6 unmodified lineslogger.warning(f"sampler {sampler} failed, keeping current: {e}")out = pipe(**prompt_kwargs,**ip_kwargs,num_inference_steps=int(steps),guidance_scale=float(guidance_scale),width=int(width),6 unmodified linesfinally:if lora_note:clear_lora(pipe)return images, lora_note, encoders, ip_note# ---------------------------------------------------------------------------13 unmodified linesdef _cook(recipe, seed, tease_reveal, extra, size_name, steps, guidance_scale,nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,ref_image, picture_mode, look_strength, redraw_strength,username, gallery_items, history):"""Shared render path for Spin and Re-roll. Returns UI outputs."""user_key = username or "anonymous"22 unmodified linesseeds = [seed] + [random.randint(0, 2**31 - 1) for _ in frames[1:]]else:seeds = [seed] * len(frames)use_pic_mode = picture_mode if picture_mode in PIC_MODES else DEFAULT_PIC_MODEpic_note = Noneif use_pic_mode != PIC_OFF and ref_image is None:pic_note = f"Picture mode {use_pic_mode} picked but no picture uploaded, so it ran Off"use_pic_mode = PIC_OFFuse_look_strength = float(max(LOOK_MIN, min(LOOK_MAX, float(look_strength or DEFAULT_LOOK_STRENGTH))))use_redraw_strength = float(max(REDRAW_MIN, min(REDRAW_MAX, float(redraw_strength or DEFAULT_REDRAW_STRENGTH))))fitted = Noneif use_pic_mode != PIC_OFF:try:fitted = fit_picture(ref_image, width, height)except Exception as e:logger.warning(f"could not read the uploaded picture: {e}")pic_note = f"Could not read the uploaded picture, so it ran Off ({e})"use_pic_mode = PIC_OFFif use_pic_mode == PIC_LOOK:# download before the GPU clock startserr = prefetch_ip_adapter()if err:pic_note = f"Copy the look: IP-Adapter download failed, rendered without it ({err[:160]})"use_pic_mode, fitted = PIC_OFF, NoneLAST_GEN_TIME[user_key] = nowtry:results, lora_note, encoders, ip_note = render_frames(recipe["chef"], frames, seeds, use_steps, use_guidance, width, height,nude_mode=use_mode, reveal_strength=use_reveal_strength,lora=lora, lora_strength=use_lora_strength, sampler=use_sampler,ref_image=fitted, picture_mode=use_pic_mode,look_strength=use_look_strength, redraw_strength=use_redraw_strength,)except Exception as e:logger.exception("render failed")23 unmodified lines]if use_mode == NUDE_MODE_REVEAL:notes.append(f"Reveal strength {use_reveal_strength:.2f}")notes.append(f"Picture mode: {use_pic_mode}")if use_pic_mode == PIC_LOOK:notes.append(f"Copy the look (IP-Adapter {IP_WEIGHT}): {ip_note}")if use_pic_mode == PIC_REDRAW:if use_mode == NUDE_MODE_REVEAL:notes.append(f"Redraw strength {use_redraw_strength:.2f} on the clothed picture, nude picture revealed from it")else:notes.append(f"Redraw strength {use_redraw_strength:.2f} clothed, "f"{min(REDRAW_MAX, use_redraw_strength + 0.1):.2f} nude, both from your picture")if pic_note:notes.append(pic_note)if lora:notes.append(f"LoRA: {lora_note}" if lora_note else f"LoRA {lora[0]} failed to load, rendered without it")prompt_text = prompt_text + "\n\n[Settings]\n" + "\n".join(notes)11 unmodified linesdef on_spin(recipe, art_mode, style_pick, new_woman, tease_reveal, extra, size_name, steps, guidance_scale,seed_value, nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,ref_image, picture_mode, look_strength, redraw_strength,username, gallery_items, history, *lock_flags):rolled = roll_recipe(recipe, _locks_from_flags(lock_flags), new_woman=bool(new_woman),art_mode=art_mode, style_pick=style_pick)return _cook(rolled, _resolve_seed(seed_value), tease_reveal, extra, size_name, steps,guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,lora_repo, lora_file, sampler, ref_image, picture_mode, look_strength,redraw_strength, username, gallery_items, history)def on_reroll_history(choice, tease_reveal, extra, size_name, steps, guidance_scale,nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,ref_image, picture_mode, look_strength, redraw_strength,username, gallery_items, history):"""Re-roll uses whatever picture is in the upload box right now."""history = list(history or [])labels = [history_label(i, h) for i, h in enumerate(history)]if not choice or choice not in labels:1 unmodified linepicked = history[labels.index(choice)]["recipe"]return _cook(dict(picked), _resolve_seed(-1), tease_reveal, extra, size_name, steps,guidance_scale, nude_mode, reveal_strength, lora_choice, lora_strength,lora_repo, lora_file, sampler, ref_image, picture_mode, look_strength,redraw_strength, username, gallery_items, history)def on_load_history(choice, history):13 unmodified linesreturn rolled, recipe_card(rolled), "\n\n".join(f"[{l}]\n{p}" for l, p, _ in frames)def on_picture_upload(picture_mode):"""A fresh upload switches Off to Copy the look; any other pick is kept."""return gr.update(value=PIC_LOOK if picture_mode in (None, PIC_OFF) else picture_mode)def on_picture_clear():return gr.update(value=PIC_OFF)def on_art_mode(art_mode, style_pick):"""Refill the Style dropdown with the styles that suit the art mode."""pool = styles_for_mode(art_mode)42 unmodified linesreveal_strength = gr.Slider(REVEAL_MIN, REVEAL_MAX, value=DEFAULT_REVEAL_STRENGTH, step=0.05,label="Reveal strength (reveal mode only; low keeps more of the clothed picture)")extra = gr.Textbox(label="Extra tags (optional)", placeholder="e.g. glossy lips, rain on skin")with gr.Accordion("Your picture (optional)", open=False):ref_image = gr.Image(type="pil", label="Reference picture", sources=["upload", "clipboard"])gr.Markdown("Use for pose, outfit, style and mood. Faces come from the random deck, not your pic.")picture_mode = gr.Radio(PIC_MODES, value=DEFAULT_PIC_MODE, label="Picture mode")look_strength = gr.Slider(LOOK_MIN, LOOK_MAX, value=DEFAULT_LOOK_STRENGTH, step=0.05,label="Look strength (Copy the look; high copies more of your pic)")redraw_strength = gr.Slider(REDRAW_MIN, REDRAW_MAX, value=DEFAULT_REDRAW_STRENGTH, step=0.05,label="Redraw strength (Redraw my pic; low stays close to your pic)")with gr.Accordion("LoRA and sampler", open=False):lora_choice = gr.Dropdown(LORA_CHOICES, value=LORA_NONE, label="LoRA")lora_strength = gr.Slider(0.0, 1.5, value=DEFAULT_LORA_STRENGTH, step=0.05, label="LoRA strength")14 unmodified linesreroll_btn = gr.Button("Re-roll this recipe, new seed")load_btn = gr.Button("Load into card (then lock and spin)")advanced = [nude_mode, reveal_strength, lora_choice, lora_strength, lora_repo, lora_file, sampler,ref_image, picture_mode, look_strength, redraw_strength]outputs = [gallery, gallery_state, card, prompt_box, recipe_state, history_state, history_dd]spin_btn.click(14 unmodified linesinputs=[recipe_state, art_mode, style_pick, new_woman, tease_reveal, extra] + lock_boxes,outputs=[recipe_state, card, prompt_box],)ref_image.upload(on_picture_upload, inputs=[picture_mode], outputs=[picture_mode])ref_image.clear(on_picture_clear, inputs=None, outputs=[picture_mode])art_mode.change(on_art_mode, inputs=[art_mode, style_pick], outputs=[style_pick])demo.load(fn=None, inputs=None, outputs=[user_id], js=js_visitor)return demo
app.py+202-13