clockclock commited on
Commit
aa271fe
·
verified ·
1 Parent(s): 4bdb54f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -24
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py (Final Corrected Version)
2
 
3
  import gradio as gr
4
  import torch
@@ -6,64 +6,95 @@ from diffusers import AutoPipelineForInpainting
6
  from PIL import Image
7
  import time
8
 
9
- # --- Model Loading ---
10
- print("Loading model for low-RAM CPU environment...")
11
- model_id = "runwayml/stable-diffusion-inpainting"
 
 
 
12
  try:
13
- pipe = AutoPipelineForInpainting.from_pretrained(model_id, torch_dtype=torch.float32)
 
 
 
 
 
 
14
  pipe.enable_model_cpu_offload()
15
- print("Model loaded successfully with CPU offloading enabled.")
 
 
16
  except Exception as e:
17
- print(f"An error occurred during model loading: {e}")
 
 
 
 
18
  raise e
19
 
20
- # --- Prompts ---
21
- DEFAULT_PROMPT = "photorealistic, 4k, ultra high quality, sharp focus, masterpiece, high detail"
22
- DEFAULT_NEGATIVE_PROMPT = "blurry, pixelated, distorted, deformed, ugly, disfigured, cartoon, watermark"
23
 
24
- # --- Inpainting Function (Correct Signature) ---
 
 
 
 
 
25
  def inpaint_image(image_and_mask, user_prompt, guidance_scale, num_steps, progress=gr.Progress(track_tqdm=True)):
26
- # The input is now a dictionary with 'image' and 'mask' keys
27
- image = image_and_mask["image"].convert("RGB")
28
- mask = image_and_mask["mask"].convert("RGB")
29
 
30
- if image is None or mask is None:
31
  raise gr.Error("Please upload an image and draw a mask on it first!")
32
 
 
 
 
 
33
  if user_prompt and user_prompt.strip():
34
  prompt = user_prompt
35
  negative_prompt = DEFAULT_NEGATIVE_PROMPT
 
36
  else:
37
  prompt = DEFAULT_PROMPT
38
  negative_prompt = DEFAULT_NEGATIVE_PROMPT
 
 
 
 
39
 
40
- print(f"Starting inpainting on CPU...")
41
  result_image = pipe(
42
- prompt=prompt, image=image, mask_image=mask, negative_prompt=negative_prompt,
43
- guidance_scale=guidance_scale, num_inference_steps=int(num_steps)
 
 
 
 
44
  ).images[0]
45
 
 
 
46
  return result_image
47
 
48
- # --- UI ---
 
49
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
50
- gr.Markdown("# 🎨 AI Image Fixer (Stable Version)")
51
- gr.Warning("‼️ PATIENCE REQUIRED! Generation can take 15-30 minutes on free hardware.")
 
 
 
 
52
 
53
  with gr.Row():
54
  with gr.Column(scale=2):
55
- # This component returns a dictionary when tool='brush'
56
  input_image = gr.Image(label="1. Upload & Mask Image", source="upload", tool="brush", type="pil")
57
  prompt_textbox = gr.Textbox(label="2. Describe Your Fix (Optional)", placeholder="Leave empty for a general fix")
58
  with gr.Accordion("Advanced Settings", open=False):
59
  guidance_scale = gr.Slider(minimum=0, maximum=20, value=8.0, label="Guidance Scale")
60
- num_steps = gr.Slider(minimum=10, maximum=50, step=1, value=20, label="Inference Steps")
61
  with gr.Column(scale=1):
62
  output_image = gr.Image(label="Result", type="pil")
63
 
64
  submit_button = gr.Button("Fix It!", variant="primary")
65
 
66
- # The `inputs` list is simple. The function signature must match what Gradio provides.
67
  submit_button.click(
68
  fn=inpaint_image,
69
  inputs=[input_image, prompt_textbox, guidance_scale, num_steps],
 
1
+ # app.py
2
 
3
  import gradio as gr
4
  import torch
 
6
  from PIL import Image
7
  import time
8
 
9
+ # --- Model Loading (Final, Most Stable Version) ---
10
+ print("Loading the definitive model for low-RAM CPU environment...")
11
+ # We are using the more modern and reliable SD 2.0 Inpainting model.
12
+ # This model is better packaged and less prone to loading errors.
13
+ model_id = "stabilityai/stable-diffusion-2-inpainting"
14
+
15
  try:
16
+ pipe = AutoPipelineForInpainting.from_pretrained(
17
+ model_id,
18
+ torch_dtype=torch.float32, # Use float32 for CPU compatibility
19
+ safety_checker=None # Proactively disable the safety checker to save memory
20
+ )
21
+
22
+ # Enable CPU offloading to prevent memory crashes. This is essential.
23
  pipe.enable_model_cpu_offload()
24
+
25
+ print("Model loaded successfully. The application is ready.")
26
+
27
  except Exception as e:
28
+ print("="*80)
29
+ print("A FATAL ERROR OCCURRED DURING MODEL LOADING. The app cannot start.")
30
+ print(f"Error: {e}")
31
+ print("This is likely due to the free hardware tier not having enough resources.")
32
+ print("="*80)
33
  raise e
34
 
 
 
 
35
 
36
+ # --- Default "Magic" Prompts ---
37
+ DEFAULT_PROMPT = "photorealistic, 4k, ultra high quality, sharp focus, masterpiece, high detail, professional photo"
38
+ DEFAULT_NEGATIVE_PROMPT = "blurry, pixelated, distorted, deformed, ugly, disfigured, cartoon, anime, low quality, watermark, text"
39
+
40
+ # --- The Inpainting Function ---
41
+ # This function signature is correct for how Gradio's Image tool works.
42
  def inpaint_image(image_and_mask, user_prompt, guidance_scale, num_steps, progress=gr.Progress(track_tqdm=True)):
 
 
 
43
 
44
+ if image_and_mask is None or "image" not in image_and_mask or "mask" not in image_and_mask:
45
  raise gr.Error("Please upload an image and draw a mask on it first!")
46
 
47
+ # The input is a dictionary with 'image' and 'mask' keys
48
+ image = image_and_mask["image"].convert("RGB")
49
+ mask = image_and_mask["mask"].convert("RGB")
50
+
51
  if user_prompt and user_prompt.strip():
52
  prompt = user_prompt
53
  negative_prompt = DEFAULT_NEGATIVE_PROMPT
54
+ print(f"Using custom prompt: '{prompt}'")
55
  else:
56
  prompt = DEFAULT_PROMPT
57
  negative_prompt = DEFAULT_NEGATIVE_PROMPT
58
+ print(f"User prompt is empty. Using default 'General Fix' prompt.")
59
+
60
+ print(f"Starting inpainting on CPU (with offloading)... This will be very slow.")
61
+ start_time = time.time()
62
 
 
63
  result_image = pipe(
64
+ prompt=prompt,
65
+ image=image,
66
+ mask_image=mask,
67
+ negative_prompt=negative_prompt,
68
+ guidance_scale=guidance_scale,
69
+ num_inference_steps=int(num_steps),
70
  ).images[0]
71
 
72
+ end_time = time.time()
73
+ print(f"Inpainting finished in {end_time - start_time:.2f} seconds.")
74
  return result_image
75
 
76
+
77
+ # --- Gradio User Interface ---
78
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
79
+ gr.Markdown("# 🎨 AI Image Fixer (Definitive Version)")
80
+ gr.Warning(
81
+ "‼️ **PATIENCE REQUIRED!** This app is running on a free CPU. "
82
+ "Generation will be **extremely slow (potentially 20-40 minutes)** due to memory-saving measures. "
83
+ "This is necessary to prevent crashes. The progress bar will appear after you click the button."
84
+ )
85
 
86
  with gr.Row():
87
  with gr.Column(scale=2):
 
88
  input_image = gr.Image(label="1. Upload & Mask Image", source="upload", tool="brush", type="pil")
89
  prompt_textbox = gr.Textbox(label="2. Describe Your Fix (Optional)", placeholder="Leave empty for a general fix")
90
  with gr.Accordion("Advanced Settings", open=False):
91
  guidance_scale = gr.Slider(minimum=0, maximum=20, value=8.0, label="Guidance Scale")
92
+ num_steps = gr.Slider(minimum=10, maximum=50, step=1, value=20, label="Inference Steps (Fewer is faster)")
93
  with gr.Column(scale=1):
94
  output_image = gr.Image(label="Result", type="pil")
95
 
96
  submit_button = gr.Button("Fix It!", variant="primary")
97
 
 
98
  submit_button.click(
99
  fn=inpaint_image,
100
  inputs=[input_image, prompt_textbox, guidance_scale, num_steps],