VINU NAYAK commited on
Commit
4355c43
·
verified ·
1 Parent(s): 6fb38c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -23
app.py CHANGED
@@ -1,23 +1,69 @@
1
- import gradio as gr
2
- from rembg import remove
3
- from PIL import Image
4
- import io
5
-
6
- def remove_background(input_image):
7
- if isinstance(input_image, str):
8
- input_image = Image.open(input_image)
9
- output_image = remove(input_image)
10
- return output_image
11
-
12
- demo = gr.Interface(
13
- fn=remove_background,
14
- inputs=gr.Image(type="pil"),
15
- outputs=gr.Image(type="pil"),
16
- title="Background Remover",
17
- description="Upload an image to remove its background",
18
- examples=[],
19
- theme=gr.themes.Soft()
20
- )
21
-
22
- if __name__ == "__main__":
23
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, send_file, jsonify
2
+ from gradio_client import Client, handle_file
3
+ import tempfile
4
+ import os
5
+ from werkzeug.utils import secure_filename
6
+
7
+ app = Flask(__name__)
8
+
9
+ # Allowed file extensions
10
+ ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
11
+ MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
12
+
13
+ def allowed_file(filename):
14
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
15
+
16
+ @app.route('/remove-background', methods=['POST'])
17
+ def remove_background():
18
+ if 'file' not in request.files:
19
+ return jsonify({"error": "No file provided"}), 400
20
+
21
+ file = request.files['file']
22
+
23
+ if file.filename == '':
24
+ return jsonify({"error": "No selected file"}), 400
25
+
26
+ if not allowed_file(file.filename):
27
+ return jsonify({"error": "Invalid file type"}), 400
28
+
29
+ # Check file size
30
+ file.seek(0, os.SEEK_END)
31
+ file_length = file.tell()
32
+ file.seek(0)
33
+
34
+ if file_length > MAX_FILE_SIZE:
35
+ return jsonify({"error": "File too large (max 5MB)"}), 400
36
+
37
+ try:
38
+ # Save the uploaded file temporarily
39
+ temp_input = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
40
+ file.save(temp_input.name)
41
+ temp_input.close()
42
+
43
+ # Call Hugging Face API
44
+ client = Client("vinaynayak/RemBG_API")
45
+ result_path = client.predict(
46
+ input_image=handle_file(temp_input.name),
47
+ api_name="/predict"
48
+ )
49
+
50
+ # Send the result back
51
+ return send_file(
52
+ result_path,
53
+ mimetype='image/png',
54
+ as_attachment=True,
55
+ download_name='background_removed.png'
56
+ )
57
+
58
+ except Exception as e:
59
+ return jsonify({"error": str(e)}), 500
60
+
61
+ finally:
62
+ # Clean up temporary files
63
+ if 'temp_input' in locals() and os.path.exists(temp_input.name):
64
+ os.unlink(temp_input.name)
65
+ if 'result_path' in locals() and os.path.exists(result_path):
66
+ os.unlink(result_path)
67
+
68
+ if __name__ == '__main__':
69
+ app.run(host='0.0.0.0', port=5000, debug=True)