Janeka commited on
Commit
fce5049
·
verified ·
1 Parent(s): 2090f0f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -17
app.py CHANGED
@@ -5,25 +5,26 @@ import io
5
  import numpy as np
6
 
7
  def remove_bg(image):
8
- # Convert PIL Image to bytes for rembg
 
 
 
 
 
 
9
  img_byte_arr = io.BytesIO()
10
  image.save(img_byte_arr, format='PNG')
11
- img_bytes = img_byte_arr.getvalue()
12
-
13
- # Process with rembg and return as PIL Image
14
- output_bytes = remove(img_bytes)
15
  return Image.open(io.BytesIO(output_bytes))
16
 
17
- with gr.Blocks() as demo:
18
- gr.Markdown("## U²Net Background Remover API")
19
- with gr.Row():
20
- inp = gr.Image(type="pil", label="Input Image")
21
- out = gr.Image(label="Output (Background Removed)")
22
- submit = gr.Button("Remove Background")
23
- submit.click(remove_bg, inputs=inp, outputs=out)
 
24
 
25
- # Key changes for API support:
26
- # 1. api_name="predict" enables the API endpoint
27
- # 2. Added proper image type conversion
28
- # 3. Better error handling
29
- demo.launch(api_name="predict") # ← This is critical for API access
 
5
  import numpy as np
6
 
7
  def remove_bg(image):
8
+ # Convert input (could be numpy array from Gradio or file path from API)
9
+ if isinstance(image, np.ndarray):
10
+ image = Image.fromarray(image)
11
+ elif isinstance(image, str):
12
+ image = Image.open(image)
13
+
14
+ # Convert to bytes for rembg
15
  img_byte_arr = io.BytesIO()
16
  image.save(img_byte_arr, format='PNG')
17
+ output_bytes = remove(img_byte_arr.getvalue())
 
 
 
18
  return Image.open(io.BytesIO(output_bytes))
19
 
20
+ # Create interface - this works better for APIs than Blocks
21
+ iface = gr.Interface(
22
+ fn=remove_bg,
23
+ inputs=gr.Image(type="filepath", label="Input Image"),
24
+ outputs=gr.Image(label="Output"),
25
+ title="U²Net Background Remover API",
26
+ description="Upload an image to remove the background"
27
+ )
28
 
29
+ # For Hugging Face Spaces, use this launch configuration
30
+ iface.launch(server_name="0.0.0.0", server_port=7860)