multimodalart HF Staff commited on
Commit
08f71fc
·
verified ·
1 Parent(s): 46adc4d

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +20 -54
app.py CHANGED
@@ -128,6 +128,14 @@ def guard_score(text: str) -> float:
128
  return torch.softmax(logits, dim=-1)[0, 1].item()
129
 
130
 
 
 
 
 
 
 
 
 
131
  # --------------------------------------------------------------------------------------
132
  # Prompt enhancement (delegated to the companion Space)
133
  # --------------------------------------------------------------------------------------
@@ -277,6 +285,11 @@ def generate_image(
277
  if len(image_paths) > MAX_INPUT_IMAGES:
278
  raise gr.Error(f"Up to {MAX_INPUT_IMAGES} input images are supported.")
279
 
 
 
 
 
 
280
  condition_images = [Image.open(p) for p in image_paths] or None
281
  width, height = resolve_size(resolution, aspect_ratio)
282
 
@@ -441,7 +454,10 @@ with gr.Blocks(title="Qwen-Image-2.1") as demo:
441
  label="True CFG scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0
442
  )
443
 
444
- final_prompt_state = gr.State("")
 
 
 
445
 
446
  gr.Markdown("### Examples")
447
  gr.Markdown("**Text to image**")
@@ -470,11 +486,11 @@ with gr.Blocks(title="Qwen-Image-2.1") as demo:
470
  generate_button.click(
471
  fn=prepare,
472
  inputs=[prompt, input_images, enhance, seed, randomize_seed, aspect_ratio],
473
- outputs=[final_prompt_state, rewritten_prompt_output, seed, aspect_ratio],
474
  ).then(
475
  fn=generate_image,
476
  inputs=[
477
- final_prompt_state,
478
  input_images,
479
  negative_prompt,
480
  true_cfg_scale,
@@ -484,59 +500,9 @@ with gr.Blocks(title="Qwen-Image-2.1") as demo:
484
  aspect_ratio,
485
  ],
486
  outputs=[result],
487
- api_name=False,
488
  )
489
 
490
- # The button chain passes the enhanced prompt through gr.State, which a remote caller
491
- # cannot supply, so the API / MCP surface gets its own single-call entry point that
492
- # runs the same guard -> enhance -> generate sequence.
493
- def run(
494
- prompt: str,
495
- input_images: list | None = None,
496
- enhance: bool = False,
497
- negative_prompt: str = "",
498
- true_cfg_scale: float = 1.0,
499
- num_inference_steps: int = 40,
500
- seed: int = 0,
501
- randomize_seed: bool = True,
502
- resolution: int = 1024,
503
- aspect_ratio: str = "Auto",
504
- ):
505
- """Generate or edit an image with Qwen-Image-2.1.
506
-
507
- Runs a whole request: the NCII guard on image-editing requests, optional prompt
508
- enhancement via the companion Space, then diffusion.
509
-
510
- Args:
511
- prompt: What to generate, or how to edit the inputs (<image1>…<image10>).
512
- input_images: Up to 10 condition image paths. Omit for text-to-image.
513
- enhance: Rewrite the prompt with the official Qwen prompt-enhancement models.
514
- negative_prompt: What to avoid. Only applied when true_cfg_scale > 1.
515
- true_cfg_scale: Classifier-free guidance scale; 1.0 disables it.
516
- num_inference_steps: Number of flow-matching steps.
517
- seed: Random seed, used when randomize_seed is false.
518
- randomize_seed: Draw a fresh seed instead of using ``seed``.
519
- resolution: Target side length in pixels (1024, 1536 or 2048).
520
- aspect_ratio: One of the model's supported ratios, or "Auto".
521
-
522
- Returns:
523
- The generated image, as RGBA (the model natively supports transparency).
524
- """
525
- final_prompt, _display, resolved_seed, resolved_ratio = prepare(
526
- prompt, input_images, enhance, seed, randomize_seed, aspect_ratio
527
- )
528
- return generate_image(
529
- final_prompt,
530
- input_images,
531
- negative_prompt,
532
- true_cfg_scale,
533
- num_inference_steps,
534
- resolved_seed,
535
- resolution,
536
- resolved_ratio,
537
- )
538
-
539
- gr.api(run, api_name="generate")
540
 
541
  demo.queue(default_concurrency_limit=1, max_size=20)
542
 
 
128
  return torch.softmax(logits, dim=-1)[0, 1].item()
129
 
130
 
131
+ def check_guard(prompt: str) -> None:
132
+ """Raise the non-explicit rejection error when the guard flags ``prompt``."""
133
+ score = guard_score(prompt)
134
+ print(f"[guard] score={score:.3f} threshold={GUARD_THRESHOLD}", flush=True)
135
+ if score >= GUARD_THRESHOLD:
136
+ raise gr.Error(GUARD_REJECTION_MESSAGE)
137
+
138
+
139
  # --------------------------------------------------------------------------------------
140
  # Prompt enhancement (delegated to the companion Space)
141
  # --------------------------------------------------------------------------------------
 
285
  if len(image_paths) > MAX_INPUT_IMAGES:
286
  raise gr.Error(f"Up to {MAX_INPUT_IMAGES} input images are supported.")
287
 
288
+ # The UI already screened this in `prepare`; repeating it here is cheap (a 270M CPU
289
+ # classifier) and keeps the guard in force for callers that hit /generate directly.
290
+ if image_paths:
291
+ check_guard(prompt)
292
+
293
  condition_images = [Image.open(p) for p in image_paths] or None
294
  width, height = resolve_size(resolution, aspect_ratio)
295
 
 
454
  label="True CFG scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0
455
  )
456
 
457
+ # A hidden Textbox rather than gr.State: it carries the enhanced prompt from
458
+ # `prepare` into `generate_image`, and being a real component it is also what
459
+ # makes `prompt` a first-class parameter of the /generate API endpoint.
460
+ final_prompt_box = gr.Textbox(visible=False, label="Prompt")
461
 
462
  gr.Markdown("### Examples")
463
  gr.Markdown("**Text to image**")
 
486
  generate_button.click(
487
  fn=prepare,
488
  inputs=[prompt, input_images, enhance, seed, randomize_seed, aspect_ratio],
489
+ outputs=[final_prompt_box, rewritten_prompt_output, seed, aspect_ratio],
490
  ).then(
491
  fn=generate_image,
492
  inputs=[
493
+ final_prompt_box,
494
  input_images,
495
  negative_prompt,
496
  true_cfg_scale,
 
500
  aspect_ratio,
501
  ],
502
  outputs=[result],
503
+ api_name="generate",
504
  )
505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
 
507
  demo.queue(default_concurrency_limit=1, max_size=20)
508