Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,67 +1,126 @@
|
|
1 |
-
# app.py
|
2 |
-
|
3 |
-
import os
|
4 |
-
from flask import Flask, request, send_file, jsonify
|
5 |
-
from rembg import remove
|
6 |
-
from PIL import Image
|
7 |
-
import io
|
8 |
-
|
9 |
-
# --- Create the Flask App ---
|
10 |
-
app = Flask(__name__)
|
11 |
-
|
12 |
-
# --- Configuration ---
|
13 |
-
# Get the API Key from an environment variable for security.
|
14 |
-
API_KEY = os.environ.get("BG_REMOVER_API_KEY")
|
15 |
-
|
16 |
-
# --- API Endpoints ---
|
17 |
-
|
18 |
-
# A simple root endpoint to check if the server is running.
|
19 |
-
@app.route('/')
|
20 |
-
def index():
|
21 |
-
return "Background Remover API is running!"
|
22 |
-
|
23 |
-
# The main endpoint for removing the background.
|
24 |
-
@app.route('/remove-bg', methods=['POST'])
|
25 |
-
def remove_background_api():
|
26 |
-
# 1. --- API Key Authentication ---
|
27 |
-
api_key_header = request.headers.get('x-api-key')
|
28 |
-
if not api_key_header or api_key_header != API_KEY:
|
29 |
-
return jsonify({"error": "Unauthorized. Invalid or missing API Key."}), 401
|
30 |
-
|
31 |
-
# 2. --- Image Validation ---
|
32 |
-
if 'file' not in request.files:
|
33 |
-
return jsonify({"error": "No file part in the request"}), 400
|
34 |
-
|
35 |
-
file = request.files['file']
|
36 |
-
|
37 |
-
if file.filename == '':
|
38 |
-
return jsonify({"error": "No selected file"}), 400
|
39 |
-
|
40 |
-
# 3. --- Image Processing ---
|
41 |
-
if file:
|
42 |
-
try:
|
43 |
-
input_image_bytes = file.read()
|
44 |
-
output_image_bytes = remove(input_image_bytes)
|
45 |
-
|
46 |
-
# 4. --- Send the Response ---
|
47 |
-
return send_file(
|
48 |
-
io.BytesIO(output_image_bytes),
|
49 |
-
mimetype='image/png',
|
50 |
-
as_attachment=True,
|
51 |
-
download_name='background_removed.png'
|
52 |
-
)
|
53 |
-
except Exception as e:
|
54 |
-
return jsonify({"error": "Failed to process image", "details": str(e)}), 500
|
55 |
-
|
56 |
-
return jsonify({"error": "An unknown error occurred"}), 500
|
57 |
-
|
58 |
-
# ---
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
|
3 |
+
import os
|
4 |
+
from flask import Flask, request, send_file, jsonify
|
5 |
+
from rembg import remove
|
6 |
+
from PIL import Image
|
7 |
+
import io
|
8 |
+
|
9 |
+
# --- Create the Flask App ---
|
10 |
+
app = Flask(__name__)
|
11 |
+
|
12 |
+
# --- Configuration ---
|
13 |
+
# Get the API Key from an environment variable for security.
|
14 |
+
API_KEY = os.environ.get("BG_REMOVER_API_KEY")
|
15 |
+
|
16 |
+
# --- API Endpoints ---
|
17 |
+
|
18 |
+
# A simple root endpoint to check if the server is running.
|
19 |
+
@app.route('/')
|
20 |
+
def index():
|
21 |
+
return "Background Remover API is running!"
|
22 |
+
|
23 |
+
# The main endpoint for removing the background.
|
24 |
+
@app.route('/remove-bg', methods=['POST'])
|
25 |
+
def remove_background_api():
|
26 |
+
# 1. --- API Key Authentication ---
|
27 |
+
api_key_header = request.headers.get('x-api-key')
|
28 |
+
if not api_key_header or api_key_header != API_KEY:
|
29 |
+
return jsonify({"error": "Unauthorized. Invalid or missing API Key."}), 401
|
30 |
+
|
31 |
+
# 2. --- Image Validation ---
|
32 |
+
if 'file' not in request.files:
|
33 |
+
return jsonify({"error": "No file part in the request"}), 400
|
34 |
+
|
35 |
+
file = request.files['file']
|
36 |
+
|
37 |
+
if file.filename == '':
|
38 |
+
return jsonify({"error": "No selected file"}), 400
|
39 |
+
|
40 |
+
# 3. --- Image Processing ---
|
41 |
+
if file:
|
42 |
+
try:
|
43 |
+
input_image_bytes = file.read()
|
44 |
+
output_image_bytes = remove(input_image_bytes)
|
45 |
+
|
46 |
+
# 4. --- Send the Response ---
|
47 |
+
return send_file(
|
48 |
+
io.BytesIO(output_image_bytes),
|
49 |
+
mimetype='image/png',
|
50 |
+
as_attachment=True,
|
51 |
+
download_name='background_removed.png'
|
52 |
+
)
|
53 |
+
except Exception as e:
|
54 |
+
return jsonify({"error": "Failed to process image", "details": str(e)}), 500
|
55 |
+
|
56 |
+
return jsonify({"error": "An unknown error occurred"}), 500
|
57 |
+
|
58 |
+
# --- IMAGE COMPRESSOR API ENDPOINT ---
|
59 |
+
|
60 |
+
@app.route('/compress-image', methods=['POST'])
|
61 |
+
def compress_image_api():
|
62 |
+
# 1. --- API Key Authentication (Bilkul pehle jaisa) ---
|
63 |
+
api_key_header = request.headers.get('x-api-key')
|
64 |
+
if not api_key_header or api_key_header != API_KEY:
|
65 |
+
return jsonify({"error": "Unauthorized. Invalid or missing API Key."}), 401
|
66 |
+
|
67 |
+
# 2. --- File aur Quality Level ko Check Karna ---
|
68 |
+
if 'file' not in request.files:
|
69 |
+
return jsonify({"error": "No file part in the request"}), 400
|
70 |
+
|
71 |
+
file = request.files['file']
|
72 |
+
|
73 |
+
# User se quality level haasil karna (default 85)
|
74 |
+
# request.form se text data liya jaata hai
|
75 |
+
quality = int(request.form.get('quality', 85))
|
76 |
+
|
77 |
+
if file.filename == '':
|
78 |
+
return jsonify({"error": "No selected file"}), 400
|
79 |
+
|
80 |
+
# 3. --- Image Processing (Pillow Library ka istemal) ---
|
81 |
+
if file:
|
82 |
+
try:
|
83 |
+
# File ko memory mein bytes ki tarah parhna
|
84 |
+
input_image_bytes = file.read()
|
85 |
+
|
86 |
+
# Pillow ka istemal karke image ko kholna
|
87 |
+
img = Image.open(io.BytesIO(input_image_bytes))
|
88 |
+
|
89 |
+
# Ek khali "in-memory" file banana jahan hum compressed image save karenge
|
90 |
+
output_buffer = io.BytesIO()
|
91 |
+
|
92 |
+
# Image ko 'RGB' mode mein convert karna (JPG ke liye zaroori)
|
93 |
+
if img.mode in ("RGBA", "P"):
|
94 |
+
img = img.convert("RGB")
|
95 |
+
|
96 |
+
# Image ko buffer mein save karna, lekin is baar quality ke saath
|
97 |
+
# quality parameter 1 se 95 tak hota hai (95 best quality)
|
98 |
+
img.save(output_buffer, format='JPEG', quality=quality)
|
99 |
+
|
100 |
+
# Compressed image ke bytes haasil karna
|
101 |
+
output_image_bytes = output_buffer.getvalue()
|
102 |
+
|
103 |
+
# 4. --- Send the Response ---
|
104 |
+
# Compressed image ko user ko wapas bhejna
|
105 |
+
return send_file(
|
106 |
+
io.BytesIO(output_image_bytes),
|
107 |
+
mimetype='image/jpeg',
|
108 |
+
as_attachment=True,
|
109 |
+
download_name=f'compressed_quality_{quality}.jpg'
|
110 |
+
)
|
111 |
+
except Exception as e:
|
112 |
+
return jsonify({"error": "Failed to process image", "details": str(e)}), 500
|
113 |
+
|
114 |
+
return jsonify({"error": "An unknown error occurred"}), 500
|
115 |
+
|
116 |
+
# --- Run the App ---
|
117 |
+
if __name__ == '__main__':
|
118 |
+
# For local testing, ensure the environment variable is set.
|
119 |
+
if not API_KEY:
|
120 |
+
# If you're using the temporary hard-coded key method, you can ignore this error.
|
121 |
+
# Otherwise, this reminds you to set the variable.
|
122 |
+
print("WARNING: BG_REMOVER_API_KEY is not set. The API will not be secured.")
|
123 |
+
print("For local testing, run 'set BG_REMOVER_API_KEY=your-key' (Windows) or 'export BG_REMOVER_API_KEY=your-key' (Mac/Linux) first.")
|
124 |
+
|
125 |
+
app.run(debug=True, port=5000)
|
126 |
+
|