Spaces:
Running on Zero
Running on Zero
Upload app.py with huggingface_hub
Browse files365 unmodified lines3663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454465 unmodified lines4524534544554564574584594604614624634644654664674684691166 unmodified lines16361637163816391640164119 unmodified lines1661166216631664166516661 unmodified line166816691670167116721673365 unmodified linesreturn max(16, (nw // 16) * 16), max(16, (nh // 16) * 16)# duration=120 gives headroom so high-res (1536-2048) runs don't hit the default# ~60s ZeroGPU wall limit ("GPU task aborted"). Billing is on ACTUAL seconds, so a# fast 1024 run still costs little; this only raises the admission reservation.@spaces.GPU(size="xlarge", duration=120)def infer(images_b64_json,prompt,lora_adapter,seed,randomize_seed,guidance_scale,steps,preserve_identity=True,identity_strength=65,output_size=1280,fix_hands=False,progress=gr.Progress(track_tqdm=True),):gc.collect()torch.cuda.empty_cache()pil_images = b64_to_pil_list(images_b64_json)if not pil_images:raise gr.Error("Please upload at least one image to edit.")if not prompt or prompt.strip() == "":raise gr.Error("Please enter an edit prompt.")# Identity lock (pose-friendly): append a strength-scaled "same person, pose may# change" instruction so the model re-poses the head while preserving the# face/identity. No masking/compositing β the head is edited so it can follow the# new pose. `preserve_identity` is the master on/off (uncheck for anime/3D);# `identity_strength` (0-100) sets how forcefully identity is locked. Applies on# top of ANY selected LoRA.eff_strength = int(identity_strength) if bool(preserve_identity) else 0prompt_used = _identity_prompt(prompt, eff_strength)# Anatomy lock + realism/HD boost on person edits (positive prompt β works even# at Guidance=1).if eff_strength > 0:prompt_used = prompt_used + ANATOMY_POS + REALISM_POSspec = ADAPTER_SPECS.get(lora_adapter)if not spec:raise gr.Error(f"Configuration not found for: {lora_adapter}")adapter_name = spec["adapter_name"]if adapter_name not in LOADED_ADAPTERS:print(f"--- Downloading and Loading Adapter: {lora_adapter} ---")try:pipe.load_lora_weights(spec["repo"], weight_name=spec["weights"], adapter_name=adapter_name)LOADED_ADAPTERS.add(adapter_name)except Exception as e:raise gr.Error(f"Failed to load adapter {lora_adapter}: {e}")else:print(f"--- Adapter {lora_adapter} already loaded. ---")pipe.set_adapters([adapter_name], adapter_weights=[1.0])# "Fix hands": the anti-extra-finger terms live in the NEGATIVE prompt, which is# ignored at Guidance=1 (CFG off on this distilled model). Raising Guidance turns# true-CFG on so those negatives actually suppress extra/fused fingers; a couple# more steps give CFG room to work. Costs ~2x time β hence it's opt-in.if bool(fix_hands):guidance_scale = max(float(guidance_scale), float(os.getenv("FIXHANDS_CFG", "2.5")))steps = max(int(steps), int(os.getenv("FIXHANDS_STEPS", "6")))if randomize_seed:seed = random.randint(0, MAX_SEED)generator = torch.Generator(device=device).manual_seed(seed)negative_prompt = ("worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, ""extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry")# Identity + anatomy negatives (active when Guidance > 1). Reinforce face lock# and suppress extra hands / >5 fingers / duplicated limbs.if eff_strength > 0:negative_prompt = negative_prompt + ", " + IDENTITY_NEG + ", " + ANATOMY_NEGwidth, height = update_dimensions_on_upload(pil_images[0], output_size)5 unmodified linesnegative_prompt=negative_prompt,height=height,width=width,num_inference_steps=steps,generator=generator,true_cfg_scale=guidance_scale,).images[0]return result_image, seedexcept Exception as e:raise efinally:gc.collect()torch.cuda.empty_cache()css = r"""@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');*{box-sizing:border-box;margin:0;padding:0}1166 unmodified linesrun_btn = gr.Button("Run", elem_id="gradio-run-btn")demo.load(fn=None, js=gallery_js)demo.load(fn=None, js=wire_outputs_js)19 unmodified linesconst fhVal = fhEl ? fhEl.checked : fh;return [imgsJson, promptVal, loraVal, s, rs, gs, st, presVal, idstVal, oszVal, fhVal];}""",)example_load_btn.click(1 unmodified lineinputs=[example_idx],outputs=[example_result],queue=False,)if __name__ == "__main__":365 unmodified lines3663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284295 unmodified lines4354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115121166 unmodified lines16791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171119 unmodified lines17311732173317341735173617371 unmodified line1739174017411742174317441745365 unmodified linesreturn max(16, (nw // 16) * 16), max(16, (nh // 16) * 16)def _run_edit(pil_images, prompt, lora_adapter, seed, randomize_seed,guidance_scale, steps, preserve_identity, identity_strength,output_size, fix_hands):"""Core image edit shared by the UI (`infer`) and the API (`api_predict`).Runs inside a @spaces.GPU entry. Returns (PIL result image, seed_used)."""gc.collect()torch.cuda.empty_cache()pil_images = [im for im in (pil_images or []) if im is not None]if not pil_images:raise gr.Error("Please provide at least one image to edit.")if not prompt or str(prompt).strip() == "":raise gr.Error("Please enter an edit prompt.")# Identity lock (pose-friendly): append a strength-scaled "same person, pose may# change" instruction. `preserve_identity` master on/off; `identity_strength`# (0-100). Applies on top of ANY selected LoRA.eff_strength = int(identity_strength) if bool(preserve_identity) else 0prompt_used = _identity_prompt(str(prompt), eff_strength)# Anatomy lock + realism/HD boost on person edits (positive prompt, works at CFG=1).if eff_strength > 0:prompt_used = prompt_used + ANATOMY_POS + REALISM_POS# Optional style LoRA. Empty / unknown adapter -> plain base-model edit.spec = ADAPTER_SPECS.get(lora_adapter) if lora_adapter else Noneif spec:adapter_name = spec["adapter_name"]if adapter_name not in LOADED_ADAPTERS:print(f"--- Downloading and Loading Adapter: {lora_adapter} ---")try:pipe.load_lora_weights(spec["repo"], weight_name=spec["weights"], adapter_name=adapter_name)LOADED_ADAPTERS.add(adapter_name)except Exception as e:raise gr.Error(f"Failed to load adapter {lora_adapter}: {e}")pipe.set_adapters([adapter_name], adapter_weights=[1.0])else:try:pipe.disable_lora() # no style requested β clear any adapter from a prior callexcept Exception:pass# "Fix hands": the anti-extra-finger terms live in the NEGATIVE prompt, ignored at# Guidance=1 (CFG off on this distilled model). Raising Guidance turns true-CFG on# so those negatives suppress extra/fused fingers; +steps give CFG room. ~2x time.if bool(fix_hands):guidance_scale = max(float(guidance_scale), float(os.getenv("FIXHANDS_CFG", "2.5")))steps = max(int(steps), int(os.getenv("FIXHANDS_STEPS", "6")))if randomize_seed:seed = random.randint(0, MAX_SEED)seed = int(seed)generator = torch.Generator(device=device).manual_seed(seed)negative_prompt = ("worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, ""extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry")# Identity + anatomy negatives (active when Guidance > 1).if eff_strength > 0:negative_prompt = negative_prompt + ", " + IDENTITY_NEG + ", " + ANATOMY_NEGwidth, height = update_dimensions_on_upload(pil_images[0], output_size)5 unmodified linesnegative_prompt=negative_prompt,height=height,width=width,num_inference_steps=int(steps),generator=generator,true_cfg_scale=float(guidance_scale),).images[0]return result_image, seedfinally:gc.collect()torch.cuda.empty_cache()# duration=120 gives headroom so high-res (1536-2048) runs don't hit the default# ~60s ZeroGPU wall limit ("GPU task aborted"). Billing is on ACTUAL seconds, so a# fast 1024 run still costs little; this only raises the admission reservation.@spaces.GPU(size="xlarge", duration=120)def infer(images_b64_json,prompt,lora_adapter,seed,randomize_seed,guidance_scale,steps,preserve_identity=True,identity_strength=65,output_size=1280,fix_hands=False,progress=gr.Progress(track_tqdm=True),):pil_images = b64_to_pil_list(images_b64_json)return _run_edit(pil_images, prompt, lora_adapter, seed, randomize_seed,guidance_scale, steps, preserve_identity, identity_strength,output_size, fix_hands)def _as_pil(x):if x is None:return Noneif isinstance(x, Image.Image):return x.convert("RGB")try:return Image.fromarray(x).convert("RGB")except Exception:return None@spaces.GPU(size="xlarge", duration=120)def api_predict(image, prompt, lora_adapter="", image2=None, seed=0,randomize_seed=True, guidance_scale=1.0, steps=4,preserve_identity=True, identity_strength=65, output_size=1280,fix_hands=False, progress=gr.Progress(track_tqdm=True)):"""Edit an image from a text prompt (Qwen-Image-Edit-2511). Returns [result_image, seed_used].image : the image to edit (the person/subject whose identity is kept).prompt : what to change, e.g. "change her outfit to a red dress; turn to look left".lora_adapter : optional style name from the adapter list ("" = no style LoRA / base edit).image2 : optional second reference image (e.g. a style or lighting reference).seed : int seed (ignored if randomize_seed=True).randomize_seed : pick a new random seed each call.guidance_scale : true-CFG. 1.0 = fastest; >1 (e.g. 2.5) activates the negative promptthat suppresses extra fingers / identity drift (slower).steps : denoise steps. 4 is native for this distilled model.preserve_identity : keep the person's face while allowing pose/head to change.identity_strength : 0-100, how forcefully identity is locked.output_size : long-side pixels 1024-2048. Higher = more HD detail, slower.fix_hands : raise CFG/steps to suppress extra/fused fingers (slower)."""imgs = [im for im in (_as_pil(image), _as_pil(image2)) if im is not None]return _run_edit(imgs, prompt, lora_adapter, seed, randomize_seed,guidance_scale, steps, preserve_identity, identity_strength,output_size, fix_hands)css = r"""@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');*{box-sizing:border-box;margin:0;padding:0}1166 unmodified linesrun_btn = gr.Button("Run", elem_id="gradio-run-btn")# ββ Documented public API endpoint: /edit ββββββββββββββββββββββββββββββββββ# Typed inputs so API/MCP callers pass a real image + prompt (not the UI's# internal base64 blob). Hidden from the UI; fully functional over the API.with gr.Row(visible=False):api_image = gr.Image(type="pil", label="image")api_image2 = gr.Image(type="pil", label="image2")api_prompt = gr.Textbox(label="prompt")api_lora = gr.Textbox(label="lora_adapter", value="")api_seed = gr.Number(label="seed", value=0, precision=0)api_rand = gr.Checkbox(label="randomize_seed", value=True)api_cfg = gr.Number(label="guidance_scale", value=1.0)api_steps = gr.Number(label="steps", value=4, precision=0)api_pres = gr.Checkbox(label="preserve_identity", value=True)api_idst = gr.Number(label="identity_strength", value=65, precision=0)api_size = gr.Number(label="output_size", value=1280, precision=0)api_fix = gr.Checkbox(label="fix_hands", value=False)api_out = gr.Image(label="result_image", type="pil", format="png")api_seed_o = gr.Number(label="seed_used", precision=0)api_btn = gr.Button("api_edit")api_btn.click(fn=api_predict,inputs=[api_image, api_prompt, api_lora, api_image2, api_seed, api_rand,api_cfg, api_steps, api_pres, api_idst, api_size, api_fix],outputs=[api_out, api_seed_o],api_name="edit",)demo.load(fn=None, js=gallery_js)demo.load(fn=None, js=wire_outputs_js)19 unmodified linesconst fhVal = fhEl ? fhEl.checked : fh;return [imgsJson, promptVal, loraVal, s, rs, gs, st, presVal, idstVal, oszVal, fhVal];}""",show_api=False, # internal UI path; the public API is /edit (api_predict))example_load_btn.click(1 unmodified lineinputs=[example_idx],outputs=[example_result],queue=False,show_api=False,)if __name__ == "__main__":
app.py+126-54