Spaces:
Running on Zero
Running on Zero
update app
Browse files
app.py
CHANGED
|
@@ -10,7 +10,7 @@ import json
|
|
| 10 |
import html as html_lib
|
| 11 |
from io import BytesIO
|
| 12 |
from PIL import Image
|
| 13 |
-
from transformers import pipeline
|
| 14 |
|
| 15 |
MAX_SEED = np.iinfo(np.int32).max
|
| 16 |
LANCZOS = getattr(Image, "Resampling", Image).LANCZOS
|
|
@@ -51,14 +51,49 @@ try:
|
|
| 51 |
except Exception as e:
|
| 52 |
print(f"Warning: Could not set FA3 processor: {e}")
|
| 53 |
|
| 54 |
-
# ──
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
try:
|
| 57 |
-
|
| 58 |
-
print("NCII
|
| 59 |
except Exception as e:
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
EXAMPLES_CONFIG = [
|
| 64 |
{
|
|
@@ -203,21 +238,19 @@ def infer(images_b64_json, prompt, seed, randomize_seed, guidance_scale, steps,
|
|
| 203 |
torch.cuda.empty_cache()
|
| 204 |
pil_images = b64_to_pil_list(images_b64_json)
|
| 205 |
if not pil_images:
|
| 206 |
-
|
|
|
|
| 207 |
if not prompt or prompt.strip() == "":
|
| 208 |
-
|
|
|
|
| 209 |
|
| 210 |
# ── NCII safety check ──
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
torch.cuda.empty_cache()
|
| 218 |
-
return None, seed
|
| 219 |
-
except Exception as e:
|
| 220 |
-
print(f"NCII check error: {e}")
|
| 221 |
|
| 222 |
if randomize_seed:
|
| 223 |
seed = random.randint(0, MAX_SEED)
|
|
@@ -230,9 +263,10 @@ def infer(images_b64_json, prompt, seed, randomize_seed, guidance_scale, steps,
|
|
| 230 |
height=height, width=width, num_inference_steps=steps,
|
| 231 |
generator=generator, true_cfg_scale=guidance_scale,
|
| 232 |
).images[0]
|
| 233 |
-
return result_image, seed
|
| 234 |
except Exception as e:
|
| 235 |
-
|
|
|
|
| 236 |
finally:
|
| 237 |
gc.collect()
|
| 238 |
torch.cuda.empty_cache()
|
|
@@ -925,14 +959,6 @@ function init() {
|
|
| 925 |
window.__clickGradioRunBtn = function() {
|
| 926 |
if (!validateBeforeRun()) return;
|
| 927 |
syncPromptToGradio(); syncImagesToGradio(); showLoader();
|
| 928 |
-
window.__isProcessing = true;
|
| 929 |
-
|
| 930 |
-
const outPh = document.getElementById('output-placeholder');
|
| 931 |
-
if (outPh) {
|
| 932 |
-
outPh.textContent = 'Result will appear here';
|
| 933 |
-
outPh.style.display = '';
|
| 934 |
-
}
|
| 935 |
-
|
| 936 |
setTimeout(() => {
|
| 937 |
const gradioBtn = document.getElementById('gradio-run-btn');
|
| 938 |
if (!gradioBtn) return;
|
|
@@ -974,12 +1000,9 @@ function watchOutputs() {
|
|
| 974 |
|
| 975 |
function syncImage() {
|
| 976 |
const resultImg = resultContainer.querySelector('img');
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
const hasValidImage = resultImg && resultImg.src && !resultImg.src.endsWith('data:image/png;base64,') && !resultImg.src.endsWith('data:,');
|
| 981 |
-
|
| 982 |
-
if (hasValidImage) {
|
| 983 |
if (outPh) outPh.style.display = 'none';
|
| 984 |
let existing = outBody.querySelector('img.modern-out-img');
|
| 985 |
if (!existing) {
|
|
@@ -990,30 +1013,7 @@ function watchOutputs() {
|
|
| 990 |
if (existing.src !== resultImg.src) {
|
| 991 |
existing.src = resultImg.src;
|
| 992 |
if (dlBtn) dlBtn.classList.add('visible');
|
| 993 |
-
if (window.
|
| 994 |
-
if (window.__hideLoader) window.__hideLoader();
|
| 995 |
-
window.__isProcessing = false;
|
| 996 |
-
}
|
| 997 |
-
}
|
| 998 |
-
} else {
|
| 999 |
-
// No valid image present
|
| 1000 |
-
if (window.__isProcessing) {
|
| 1001 |
-
// Verify if the backend has finished processing by checking the button's disabled state
|
| 1002 |
-
const btn = document.querySelector('#gradio-run-btn button');
|
| 1003 |
-
const isFinished = btn ? !btn.disabled : true;
|
| 1004 |
-
|
| 1005 |
-
if (isFinished) {
|
| 1006 |
-
// Processing finished but no image (e.g., NCII blocked or error)
|
| 1007 |
-
if (window.__hideLoader) window.__hideLoader();
|
| 1008 |
-
const existing = outBody.querySelector('img.modern-out-img');
|
| 1009 |
-
if (existing) existing.remove();
|
| 1010 |
-
if (dlBtn) dlBtn.classList.remove('visible');
|
| 1011 |
-
if (outPh) {
|
| 1012 |
-
outPh.style.display = '';
|
| 1013 |
-
outPh.textContent = 'No Results';
|
| 1014 |
-
}
|
| 1015 |
-
window.__isProcessing = false;
|
| 1016 |
-
}
|
| 1017 |
}
|
| 1018 |
}
|
| 1019 |
}
|
|
@@ -1023,6 +1023,49 @@ function watchOutputs() {
|
|
| 1023 |
}
|
| 1024 |
watchOutputs();
|
| 1025 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1026 |
function watchSeed() {
|
| 1027 |
const seedContainer = document.getElementById('gradio-seed');
|
| 1028 |
const seedSlider = document.getElementById('custom-seed');
|
|
@@ -1104,6 +1147,7 @@ with gr.Blocks() as demo:
|
|
| 1104 |
guidance_scale = gr.Slider(minimum=1.0, maximum=10.0, step=0.1, value=1.0, elem_id="gradio-guidance", elem_classes="hidden-input", container=False)
|
| 1105 |
steps = gr.Slider(minimum=1, maximum=50, step=1, value=4, elem_id="gradio-steps", elem_classes="hidden-input", container=False)
|
| 1106 |
result = gr.Image(elem_id="gradio-result", elem_classes="hidden-input", container=False, format="png")
|
|
|
|
| 1107 |
|
| 1108 |
example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
|
| 1109 |
example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
|
|
@@ -1290,7 +1334,7 @@ with gr.Blocks() as demo:
|
|
| 1290 |
run_btn.click(
|
| 1291 |
fn=infer,
|
| 1292 |
inputs=[hidden_images_b64, prompt, seed, randomize_seed, guidance_scale, steps],
|
| 1293 |
-
outputs=[result, seed],
|
| 1294 |
js=r"""(imgs, p, s, rs, gs, st) => {
|
| 1295 |
const images = window.__uploadedImages || [];
|
| 1296 |
const b64Array = images.map(img => img.b64);
|
|
|
|
| 10 |
import html as html_lib
|
| 11 |
from io import BytesIO
|
| 12 |
from PIL import Image
|
| 13 |
+
from transformers import pipeline as hf_pipeline
|
| 14 |
|
| 15 |
MAX_SEED = np.iinfo(np.int32).max
|
| 16 |
LANCZOS = getattr(Image, "Resampling", Image).LANCZOS
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
print(f"Warning: Could not set FA3 processor: {e}")
|
| 53 |
|
| 54 |
+
# ── NCII safety guard ────────────────────────────────────────────────────────
|
| 55 |
+
# https://huggingface.co/hfmlsoc/ncii-light-guard-v01
|
| 56 |
+
# Classifies the edit prompt for non-consensual intimate imagery (NCII) intent
|
| 57 |
+
# before any image generation happens. Runs on CPU — it's a light text
|
| 58 |
+
# classifier and doesn't need the GPU slot reserved for the diffusion pipeline.
|
| 59 |
+
NCII_MODEL_ID = "hfmlsoc/ncii-light-guard-v01"
|
| 60 |
+
NCII_UNSAFE_LABEL = "ncii"
|
| 61 |
+
NCII_THRESHOLD = 0.5
|
| 62 |
+
NCII_BLOCK_MESSAGE = "You entered prompt is NCII (non-consensual intimate imagery) and you're request not be processed. Try with Safe Prompts"
|
| 63 |
+
|
| 64 |
+
print("Loading NCII safety guard model...")
|
| 65 |
try:
|
| 66 |
+
ncii_guard = hf_pipeline("text-classification", model=NCII_MODEL_ID, device=-1)
|
| 67 |
+
print("NCII guard loaded successfully.")
|
| 68 |
except Exception as e:
|
| 69 |
+
ncii_guard = None
|
| 70 |
+
print(f"Warning: Could not load NCII guard model ({NCII_MODEL_ID}): {e}")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def check_ncii_safety(prompt_text):
|
| 74 |
+
"""
|
| 75 |
+
Runs the NCII guard classifier on the prompt.
|
| 76 |
+
Returns (is_unsafe: bool, label: str, score: float).
|
| 77 |
+
|
| 78 |
+
Fails OPEN (treats the prompt as safe) if the guard model itself failed
|
| 79 |
+
to load or errors at inference time, so a guard outage doesn't take the
|
| 80 |
+
whole app down. Flip this to fail-closed (return True on failure) if you
|
| 81 |
+
want stricter behavior for a production deployment.
|
| 82 |
+
"""
|
| 83 |
+
if ncii_guard is None or not prompt_text or not prompt_text.strip():
|
| 84 |
+
return False, "unknown", 0.0
|
| 85 |
+
try:
|
| 86 |
+
out = ncii_guard(prompt_text.strip())
|
| 87 |
+
if isinstance(out, list) and len(out) > 0:
|
| 88 |
+
top = out[0]
|
| 89 |
+
label = str(top.get("label", "")).lower()
|
| 90 |
+
score = float(top.get("score", 0.0))
|
| 91 |
+
is_unsafe = (label == NCII_UNSAFE_LABEL) and (score >= NCII_THRESHOLD)
|
| 92 |
+
return is_unsafe, label, score
|
| 93 |
+
except Exception as e:
|
| 94 |
+
print(f"NCII guard inference error: {e}")
|
| 95 |
+
return False, "unknown", 0.0
|
| 96 |
+
|
| 97 |
|
| 98 |
EXAMPLES_CONFIG = [
|
| 99 |
{
|
|
|
|
| 238 |
torch.cuda.empty_cache()
|
| 239 |
pil_images = b64_to_pil_list(images_b64_json)
|
| 240 |
if not pil_images:
|
| 241 |
+
gr.Warning("Please upload at least one image to edit.")
|
| 242 |
+
return None, seed, "error"
|
| 243 |
if not prompt or prompt.strip() == "":
|
| 244 |
+
gr.Warning("Please enter an edit prompt.")
|
| 245 |
+
return None, seed, "error"
|
| 246 |
|
| 247 |
# ── NCII safety check ──
|
| 248 |
+
is_unsafe, _, _ = check_ncii_safety(prompt)
|
| 249 |
+
if is_unsafe:
|
| 250 |
+
gr.Warning(NCII_BLOCK_MESSAGE)
|
| 251 |
+
gc.collect()
|
| 252 |
+
torch.cuda.empty_cache()
|
| 253 |
+
return None, seed, "blocked"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
if randomize_seed:
|
| 256 |
seed = random.randint(0, MAX_SEED)
|
|
|
|
| 263 |
height=height, width=width, num_inference_steps=steps,
|
| 264 |
generator=generator, true_cfg_scale=guidance_scale,
|
| 265 |
).images[0]
|
| 266 |
+
return result_image, seed, "success"
|
| 267 |
except Exception as e:
|
| 268 |
+
print(f"Generation error: {e}")
|
| 269 |
+
return None, seed, "error"
|
| 270 |
finally:
|
| 271 |
gc.collect()
|
| 272 |
torch.cuda.empty_cache()
|
|
|
|
| 959 |
window.__clickGradioRunBtn = function() {
|
| 960 |
if (!validateBeforeRun()) return;
|
| 961 |
syncPromptToGradio(); syncImagesToGradio(); showLoader();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 962 |
setTimeout(() => {
|
| 963 |
const gradioBtn = document.getElementById('gradio-run-btn');
|
| 964 |
if (!gradioBtn) return;
|
|
|
|
| 1000 |
|
| 1001 |
function syncImage() {
|
| 1002 |
const resultImg = resultContainer.querySelector('img');
|
| 1003 |
+
// Only hide the loader and show the image if a valid, non-blank image is present.
|
| 1004 |
+
// Gradio sometimes uses a 'blank.png' placeholder internally.
|
| 1005 |
+
if (resultImg && resultImg.src && !resultImg.src.endsWith('blank.png')) {
|
|
|
|
|
|
|
|
|
|
| 1006 |
if (outPh) outPh.style.display = 'none';
|
| 1007 |
let existing = outBody.querySelector('img.modern-out-img');
|
| 1008 |
if (!existing) {
|
|
|
|
| 1013 |
if (existing.src !== resultImg.src) {
|
| 1014 |
existing.src = resultImg.src;
|
| 1015 |
if (dlBtn) dlBtn.classList.add('visible');
|
| 1016 |
+
if (window.__hideLoader) window.__hideLoader();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1017 |
}
|
| 1018 |
}
|
| 1019 |
}
|
|
|
|
| 1023 |
}
|
| 1024 |
watchOutputs();
|
| 1025 |
|
| 1026 |
+
function watchProcessState() {
|
| 1027 |
+
const stateContainer = document.getElementById('gradio-process-state');
|
| 1028 |
+
if (!stateContainer) { setTimeout(watchProcessState, 500); return; }
|
| 1029 |
+
|
| 1030 |
+
let lastState = 'idle';
|
| 1031 |
+
|
| 1032 |
+
function checkState() {
|
| 1033 |
+
const el = stateContainer.querySelector('textarea') || stateContainer.querySelector('input');
|
| 1034 |
+
if (!el) return;
|
| 1035 |
+
const val = el.value;
|
| 1036 |
+
if (val !== lastState) {
|
| 1037 |
+
lastState = val;
|
| 1038 |
+
// If the state is 'blocked' or 'error', hide the loader and reset the output view.
|
| 1039 |
+
if (val === 'blocked' || val === 'error') {
|
| 1040 |
+
if (window.__hideLoader) window.__hideLoader();
|
| 1041 |
+
const outBody = document.getElementById('output-image-container');
|
| 1042 |
+
const existing = outBody.querySelector('img.modern-out-img');
|
| 1043 |
+
if (existing) existing.remove();
|
| 1044 |
+
const dlBtn = document.getElementById('dl-btn-output');
|
| 1045 |
+
if (dlBtn) dlBtn.classList.remove('visible');
|
| 1046 |
+
const outPh = document.getElementById('output-placeholder');
|
| 1047 |
+
if (outPh) outPh.style.display = '';
|
| 1048 |
+
|
| 1049 |
+
if (val === 'error' && window.__showToast) {
|
| 1050 |
+
window.__showToast('An error occurred during generation. Please try again.', 'error');
|
| 1051 |
+
}
|
| 1052 |
+
}
|
| 1053 |
+
|
| 1054 |
+
// Reset the state to 'idle' so it can trigger again on the next run
|
| 1055 |
+
if (val === 'blocked' || val === 'error' || val === 'success') {
|
| 1056 |
+
el.value = 'idle';
|
| 1057 |
+
el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
|
| 1058 |
+
el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
|
| 1059 |
+
}
|
| 1060 |
+
}
|
| 1061 |
+
}
|
| 1062 |
+
|
| 1063 |
+
const obs = new MutationObserver(checkState);
|
| 1064 |
+
obs.observe(stateContainer, {childList:true, subtree:true, attributes:true, attributeFilter:['value']});
|
| 1065 |
+
setInterval(checkState, 500);
|
| 1066 |
+
}
|
| 1067 |
+
watchProcessState();
|
| 1068 |
+
|
| 1069 |
function watchSeed() {
|
| 1070 |
const seedContainer = document.getElementById('gradio-seed');
|
| 1071 |
const seedSlider = document.getElementById('custom-seed');
|
|
|
|
| 1147 |
guidance_scale = gr.Slider(minimum=1.0, maximum=10.0, step=0.1, value=1.0, elem_id="gradio-guidance", elem_classes="hidden-input", container=False)
|
| 1148 |
steps = gr.Slider(minimum=1, maximum=50, step=1, value=4, elem_id="gradio-steps", elem_classes="hidden-input", container=False)
|
| 1149 |
result = gr.Image(elem_id="gradio-result", elem_classes="hidden-input", container=False, format="png")
|
| 1150 |
+
process_state = gr.Textbox(value="idle", elem_id="gradio-process-state", elem_classes="hidden-input", container=False)
|
| 1151 |
|
| 1152 |
example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
|
| 1153 |
example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
|
|
|
|
| 1334 |
run_btn.click(
|
| 1335 |
fn=infer,
|
| 1336 |
inputs=[hidden_images_b64, prompt, seed, randomize_seed, guidance_scale, steps],
|
| 1337 |
+
outputs=[result, seed, process_state],
|
| 1338 |
js=r"""(imgs, p, s, rs, gs, st) => {
|
| 1339 |
const images = window.__uploadedImages || [];
|
| 1340 |
const b64Array = images.map(img => img.b64);
|