prithivMLmods commited on
Commit
58e741f
Β·
verified Β·
1 Parent(s): 3d4e651

update app [ncii@device=-1]

Browse files
Files changed (1) hide show
  1. app.py +51 -4
app.py CHANGED
@@ -53,6 +53,8 @@ except Exception as e:
53
  print(f"Warning: Could not set FA3 processor: {e}")
54
 
55
  # ── NCII safety guard ────────────────────────────────────────────────────────
 
 
56
  NCII_MODEL_ID = "hfmlsoc/ncii-guard-v02"
57
  NCII_UNSAFE_LABEL = "ncii"
58
  NCII_THRESHOLD = 0.5
@@ -60,17 +62,49 @@ NCII_BLOCK_MESSAGE = "You entered prompt is NCII (non-consensual intimate imager
60
 
61
  print("Loading NCII safety guard model...")
62
  try:
63
- ncii_guard = hf_pipeline("text-classification", model=NCII_MODEL_ID, device=-1)
64
- print("NCII guard loaded successfully.")
 
 
 
 
65
  except Exception as e:
66
  ncii_guard = None
67
  print(f"Warning: Could not load NCII guard model ({NCII_MODEL_ID}): {e}")
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def check_ncii_safety(prompt_text):
 
 
70
  if ncii_guard is None or not prompt_text or not prompt_text.strip():
71
  return False, "unknown", 0.0
 
 
 
 
 
 
72
  try:
73
- out = ncii_guard(prompt_text.strip())
 
 
 
 
74
  if isinstance(out, list) and len(out) > 0:
75
  top = out[0]
76
  label = str(top.get("label", "")).lower()
@@ -79,8 +113,20 @@ def check_ncii_safety(prompt_text):
79
  return is_unsafe, label, score
80
  except Exception as e:
81
  print(f"NCII guard inference error: {e}")
 
 
 
 
 
 
 
 
 
 
 
82
  return False, "unknown", 0.0
83
 
 
84
  # ── Examples Config ───────────────────────────────────────────────────────────
85
  EXAMPLES_CONFIG = [
86
  {"images": ["examples/1.jpg"], "prompt": "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed 'Fire-Edit' preserving realistic texture and details."},
@@ -192,6 +238,7 @@ def infer(
192
 
193
  Returns {"image": <base64 PNG data URL>, "seed": <seed used>, "status": "success"}
194
  or {"status": "blocked", "message": <warning>} if NCII triggers.
 
195
  """
196
  gc.collect()
197
  torch.cuda.empty_cache()
@@ -202,7 +249,7 @@ def infer(
202
  if not prompt or prompt.strip() == "":
203
  raise gr.Error("Please enter an edit prompt.")
204
 
205
- # ── NCII safety check ──
206
  is_unsafe, _, _ = check_ncii_safety(prompt)
207
  if is_unsafe:
208
  gc.collect()
 
53
  print(f"Warning: Could not set FA3 processor: {e}")
54
 
55
  # ── NCII safety guard ────────────────────────────────────────────────────────
56
+ # Loaded on CPU initially; moved to GPU at inference time inside the
57
+ # @spaces.GPU-decorated function so NCII runs on GPU, not CPU.
58
  NCII_MODEL_ID = "hfmlsoc/ncii-guard-v02"
59
  NCII_UNSAFE_LABEL = "ncii"
60
  NCII_THRESHOLD = 0.5
 
62
 
63
  print("Loading NCII safety guard model...")
64
  try:
65
+ ncii_guard = hf_pipeline(
66
+ "text-classification",
67
+ model=NCII_MODEL_ID,
68
+ device=-1, # load on CPU; will be moved to GPU inside @spaces.GPU
69
+ )
70
+ print("NCII guard loaded successfully (CPU initial).")
71
  except Exception as e:
72
  ncii_guard = None
73
  print(f"Warning: Could not load NCII guard model ({NCII_MODEL_ID}): {e}")
74
 
75
+
76
+ def _move_ncii_to(target_device: str):
77
+ """Move NCII model to the target device if possible."""
78
+ if ncii_guard is None:
79
+ return False
80
+ try:
81
+ cur = next(ncii_guard.model.parameters()).device
82
+ tgt = torch.device(target_device)
83
+ if cur != tgt:
84
+ ncii_guard.model = ncii_guard.model.to(tgt)
85
+ return True
86
+ except Exception as e:
87
+ print(f"NCII guard device move to {target_device} failed: {e}")
88
+ return False
89
+
90
+
91
  def check_ncii_safety(prompt_text):
92
+ """Run NCII safety check on GPU (must be called inside @spaces.GPU).
93
+ Falls back to CPU if GPU is unavailable."""
94
  if ncii_guard is None or not prompt_text or not prompt_text.strip():
95
  return False, "unknown", 0.0
96
+
97
+ # Move to GPU if available β€” inference now happens under the @spaces.GPU context
98
+ on_gpu = False
99
+ if torch.cuda.is_available():
100
+ on_gpu = _move_ncii_to("cuda")
101
+
102
  try:
103
+ out = ncii_guard(
104
+ prompt_text.strip(),
105
+ truncation=True,
106
+ max_length=512,
107
+ )
108
  if isinstance(out, list) and len(out) > 0:
109
  top = out[0]
110
  label = str(top.get("label", "")).lower()
 
113
  return is_unsafe, label, score
114
  except Exception as e:
115
  print(f"NCII guard inference error: {e}")
116
+ return False, "unknown", 0.0
117
+ finally:
118
+ # Release GPU memory after inference β€” move model back to CPU.
119
+ # This is important on ZeroGPU so the model params don't get
120
+ # orphaned when the GPU context is torn down.
121
+ if on_gpu:
122
+ _move_ncii_to("cpu")
123
+ try:
124
+ torch.cuda.empty_cache()
125
+ except Exception:
126
+ pass
127
  return False, "unknown", 0.0
128
 
129
+
130
  # ── Examples Config ───────────────────────────────────────────────────────────
131
  EXAMPLES_CONFIG = [
132
  {"images": ["examples/1.jpg"], "prompt": "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed 'Fire-Edit' preserving realistic texture and details."},
 
238
 
239
  Returns {"image": <base64 PNG data URL>, "seed": <seed used>, "status": "success"}
240
  or {"status": "blocked", "message": <warning>} if NCII triggers.
241
+ The NCII safety check now runs on GPU inside this @spaces.GPU context.
242
  """
243
  gc.collect()
244
  torch.cuda.empty_cache()
 
249
  if not prompt or prompt.strip() == "":
250
  raise gr.Error("Please enter an edit prompt.")
251
 
252
+ # ── NCII safety check (now runs on GPU within @spaces.GPU) ──
253
  is_unsafe, _, _ = check_ncii_safety(prompt)
254
  if is_unsafe:
255
  gc.collect()