VINU NAYAK commited on
Commit
8d4ca27
·
verified ·
1 Parent(s): 4355c43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -69
app.py CHANGED
@@ -1,69 +1,22 @@
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)
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.responses import StreamingResponse
3
+ from rembg import remove
4
+ from PIL import Image
5
+ import io
6
+
7
+ app = FastAPI()
8
+
9
+ @app.post("/remove-bg")
10
+ async def remove_bg(file: UploadFile = File(...)):
11
+ input_bytes = await file.read()
12
+ input_image = Image.open(io.BytesIO(input_bytes)).convert("RGBA")
13
+
14
+ # Remove background
15
+ output_image = remove(input_image)
16
+
17
+ # Convert output to byte stream
18
+ img_byte_arr = io.BytesIO()
19
+ output_image.save(img_byte_arr, format='PNG')
20
+ img_byte_arr.seek(0)
21
+
22
+ return StreamingResponse(img_byte_arr, media_type="image/png")