theoracle commited on
Commit
a1c101c
Β·
1 Parent(s): b43fb22

Fix step 2 error handling and wire up error_box

Browse files
Files changed (1) hide show
  1. app.py +36 -26
app.py CHANGED
@@ -1,37 +1,43 @@
1
-
2
  import gradio as gr
3
  from inference import generate_with_lora
4
  from background_edit import run_background_removal_and_inpaint
5
  import traceback, torch, gc
6
 
7
  # ───────────────────── Helpers ─────────────────────
8
- def _print_trace(): traceback.print_exc()
 
9
 
10
  def safe_generate_with_lora(*a, **kw):
11
- try: return generate_with_lora(*a, **kw)
12
- except gr.Error: _print_trace(); raise
 
 
 
13
  except Exception as e:
14
- _print_trace(); raise gr.Error(f"Image generation failed: {e}")
 
15
 
16
- def unload_models(): torch.cuda.empty_cache(); gc.collect()
 
 
17
 
18
  def safe_run_background(*args, **kwargs):
19
  try:
20
- unload_models() # free VRAM before running background edit
21
  return run_background_removal_and_inpaint(*args, **kwargs)
22
  except Exception as e:
23
  _print_trace()
24
- raise gr.Error(f"[Step 2] Background replacement failed: {type(e).__name__} - {e}")
25
-
26
 
27
  # ───────────────────── UI ─────────────────────
28
- shared_output = gr.State()
29
- original_input = gr.State()
30
 
31
  with gr.Blocks() as demo:
32
- demo.queue()
33
 
34
- # ─────────── STEPβ€―1: Headshot Refinement ───────────
35
  with gr.Tab("Step 1: Headshot Refinement"):
36
  with gr.Row():
37
  input_image = gr.Image(type="pil", label="Upload Headshot")
@@ -56,7 +62,7 @@ with gr.Blocks() as demo:
56
  def _save_to_state(img):
57
  return {"step1": img} if img is not None else gr.skip()
58
 
59
- # Build the *single* click chain and keep the handle in `event`
60
  event = (
61
  run_btn.click(
62
  fn=safe_generate_with_lora,
@@ -67,14 +73,15 @@ with gr.Blocks() as demo:
67
  .then(lambda x: x, input_image, original_input)
68
  )
69
 
70
- # ─────────── STEPβ€―2: Background Replacement ───────────
71
  with gr.Tab("Step 2: Replace Background"):
72
- # … your prompts and inpaint_result …
73
  error_box = gr.Textbox(label="Error", interactive=False, lines=2)
 
74
  with gr.Row():
75
  inpaint_prompt = gr.Textbox(
76
  label="New Background Prompt",
77
- value="modern open‑plan startup office background, natural lighting, glass walls, clean design, minimalistic decor"
78
  )
79
  inpaint_negative = gr.Textbox(
80
  label="Negative Prompt",
@@ -88,23 +95,26 @@ with gr.Blocks() as demo:
88
  inpaint_btn = gr.Button("Remove Background & Inpaint", interactive=False)
89
 
90
  def guarded_inpaint(img, prompt_bg, neg_bg):
 
 
 
91
  try:
92
- if img is None:
93
- raise ValueError("No image to inpaintβ€”run Step 1 first.")
94
- out = safe_run_background(img, prompt_bg, neg_bg)
95
- return out, "" # success
96
  except Exception as e:
97
- # logs to console for debugging
98
  print(f"[Step 2 ERROR] {type(e).__name__}: {e}", flush=True)
99
- return None, f"{type(e).__name__}: {e}" # image=None, show error
100
 
101
  inpaint_btn.click(
102
  fn=guarded_inpaint,
103
  inputs=[shared_output, inpaint_prompt, inpaint_negative],
104
- outputs=[inpaint_result, error_box],
105
  )
106
 
107
- # Enable the Stepβ€―2 button once Stepβ€―1 finishes
108
  event.then(lambda: gr.update(interactive=True), None, inpaint_btn)
109
 
110
- demo.launch(debug=True)
 
 
 
1
  import gradio as gr
2
  from inference import generate_with_lora
3
  from background_edit import run_background_removal_and_inpaint
4
  import traceback, torch, gc
5
 
6
  # ───────────────────── Helpers ─────────────────────
7
+ def _print_trace():
8
+ traceback.print_exc()
9
 
10
  def safe_generate_with_lora(*a, **kw):
11
+ try:
12
+ return generate_with_lora(*a, **kw)
13
+ except gr.Error:
14
+ _print_trace()
15
+ raise
16
  except Exception as e:
17
+ _print_trace()
18
+ raise gr.Error(f"Image generation failed: {e}")
19
 
20
+ def unload_models():
21
+ torch.cuda.empty_cache()
22
+ gc.collect()
23
 
24
  def safe_run_background(*args, **kwargs):
25
  try:
26
+ unload_models() # free VRAM before loading the inpainting model
27
  return run_background_removal_and_inpaint(*args, **kwargs)
28
  except Exception as e:
29
  _print_trace()
30
+ # We still raise gr.Error so the wrapper will catch & log
31
+ raise gr.Error(f"[Step 2] Background replacement failed: {type(e).__name__}: {e}")
32
 
33
  # ───────────────────── UI ─────────────────────
34
+ shared_output = gr.State() # holds the Step 1 output image
35
+ original_input = gr.State() # holds the original upload (optional)
36
 
37
  with gr.Blocks() as demo:
38
+ demo.queue() # enable batching / concurrency
39
 
40
+ # ─────────── STEP 1: Headshot Refinement ───────────
41
  with gr.Tab("Step 1: Headshot Refinement"):
42
  with gr.Row():
43
  input_image = gr.Image(type="pil", label="Upload Headshot")
 
62
  def _save_to_state(img):
63
  return {"step1": img} if img is not None else gr.skip()
64
 
65
+ # Build the click-chain and store it in `event`
66
  event = (
67
  run_btn.click(
68
  fn=safe_generate_with_lora,
 
73
  .then(lambda x: x, input_image, original_input)
74
  )
75
 
76
+ # ─────────── STEP 2: Background Replacement ───────────
77
  with gr.Tab("Step 2: Replace Background"):
78
+ # This textbox will show any error messages from Step 2
79
  error_box = gr.Textbox(label="Error", interactive=False, lines=2)
80
+
81
  with gr.Row():
82
  inpaint_prompt = gr.Textbox(
83
  label="New Background Prompt",
84
+ value="modern open-plan startup office background, natural lighting, glass walls, clean design, minimalistic decor"
85
  )
86
  inpaint_negative = gr.Textbox(
87
  label="Negative Prompt",
 
95
  inpaint_btn = gr.Button("Remove Background & Inpaint", interactive=False)
96
 
97
  def guarded_inpaint(img, prompt_bg, neg_bg):
98
+ # If no image is in state, return an error immediately
99
+ if img is None:
100
+ return None, "Error: No headshot foundβ€”please run Step 1 first."
101
  try:
102
+ print("[DEBUG] Starting background removal and inpainting…", flush=True)
103
+ result = safe_run_background(img, prompt_bg, neg_bg)
104
+ return result, "" # success: show result, clear error
 
105
  except Exception as e:
106
+ # Log to console/Space logs
107
  print(f"[Step 2 ERROR] {type(e).__name__}: {e}", flush=True)
108
+ return None, f"{type(e).__name__}: {e}"
109
 
110
  inpaint_btn.click(
111
  fn=guarded_inpaint,
112
  inputs=[shared_output, inpaint_prompt, inpaint_negative],
113
+ outputs=[inpaint_result, error_box], # wire both outputs!
114
  )
115
 
116
+ # Enable the Step 2 button once Step 1’s chain finishes
117
  event.then(lambda: gr.update(interactive=True), None, inpaint_btn)
118
 
119
+ # Launch in debug mode so exceptions & prints go to your terminal/logs
120
+ demo.launch(debug=True)