Spaces:
Running
Running
File size: 1,732 Bytes
b2c4dfa bb22c21 b2c4dfa abe7339 b2c4dfa 96b1041 9aa7575 b2c4dfa abe7339 9aa7575 b2c4dfa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | from flask import Flask, request, send_file, jsonify
from flask_cors import CORS
from rembg import remove
from PIL import Image
import io
import os
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route('/')
def index():
return jsonify({"message": "Background removal server is running!"})
@app.route('/api/remove-background', methods=['POST'])
def remove_background_api():
if 'file' not in request.files:
return jsonify({"error": "No file part in the request"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No file selected for uploading"}), 400
input_bytes = file.read()
try:
input_image = Image.open(io.BytesIO(input_bytes)).convert("RGBA")
output_image = remove(
input_image,
model='u2net', # ודא שאנחנו עדיין משתמשים במודל האיכותי
alpha_matting=True,
alpha_matting_foreground_threshold=240,
alpha_matting_background_threshold=10,
alpha_matting_erode_size=10
)
output_bytes_stream = io.BytesIO()
output_image.save(output_bytes_stream, format="PNG")
output_bytes = output_bytes_stream.getvalue()
return send_file(
io.BytesIO(output_bytes),
mimetype='image/png',
as_attachment=False,
download_name='processed.png'
)
except Exception as e:
print(f"Error processing image: {e}")
return jsonify({"error": f"Failed to process image: {str(e)}"}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port) |