File size: 6,989 Bytes
8af3d5d
 
 
 
 
7f206ba
8af3d5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f206ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af3d5d
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# app.py

import os
from flask import Flask, request, send_file, jsonify
from rembg import remove
from PIL import Image, ImageEnhance, ImageFilter
import io

# --- Create the Flask App ---
app = Flask(__name__)

# --- Configuration ---
# Get the API Key from an environment variable for security.
API_KEY = os.environ.get("BG_REMOVER_API_KEY") 

# --- API Endpoints ---

# A simple root endpoint to check if the server is running.
@app.route('/')
def index():
    return "Background Remover API is running!"

# The main endpoint for removing the background.
@app.route('/remove-bg', methods=['POST'])
def remove_background_api():
    # 1. --- API Key Authentication ---
    api_key_header = request.headers.get('x-api-key')
    if not api_key_header or api_key_header != API_KEY:
        return jsonify({"error": "Unauthorized. Invalid or missing API Key."}), 401

    # 2. --- Image Validation ---
    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 selected file"}), 400

    # 3. --- Image Processing ---
    if file:
        try:
            input_image_bytes = file.read()
            output_image_bytes = remove(input_image_bytes)
            
            # 4. --- Send the Response ---
            return send_file(
                io.BytesIO(output_image_bytes),
                mimetype='image/png',
                as_attachment=True,
                download_name='background_removed.png'
            )
        except Exception as e:
            return jsonify({"error": "Failed to process image", "details": str(e)}), 500

    return jsonify({"error": "An unknown error occurred"}), 500

# --- IMAGE COMPRESSOR API ENDPOINT ---

@app.route('/compress-image', methods=['POST'])
def compress_image_api():
    # 1. --- API Key Authentication (Bilkul pehle jaisa) ---
    api_key_header = request.headers.get('x-api-key')
    if not api_key_header or api_key_header != API_KEY:
        return jsonify({"error": "Unauthorized. Invalid or missing API Key."}), 401

    # 2. --- File aur Quality Level ko Check Karna ---
    if 'file' not in request.files:
        return jsonify({"error": "No file part in the request"}), 400

    file = request.files['file']
    
    # User se quality level haasil karna (default 85)
    # request.form se text data liya jaata hai
    quality = int(request.form.get('quality', 85))

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 3. --- Image Processing (Pillow Library ka istemal) ---
    if file:
        try:
            # File ko memory mein bytes ki tarah parhna
            input_image_bytes = file.read()
            
            # Pillow ka istemal karke image ko kholna
            img = Image.open(io.BytesIO(input_image_bytes))
            
            # Ek khali "in-memory" file banana jahan hum compressed image save karenge
            output_buffer = io.BytesIO()

            # Image ko 'RGB' mode mein convert karna (JPG ke liye zaroori)
            if img.mode in ("RGBA", "P"):
                img = img.convert("RGB")

            # Image ko buffer mein save karna, lekin is baar quality ke saath
            # quality parameter 1 se 95 tak hota hai (95 best quality)
            img.save(output_buffer, format='JPEG', quality=quality)
            
            # Compressed image ke bytes haasil karna
            output_image_bytes = output_buffer.getvalue()

            # 4. --- Send the Response ---
            # Compressed image ko user ko wapas bhejna
            return send_file(
                io.BytesIO(output_image_bytes),
                mimetype='image/jpeg',
                as_attachment=True,
                download_name=f'compressed_quality_{quality}.jpg'
            )
        except Exception as e:
            return jsonify({"error": "Failed to process image", "details": str(e)}), 500

    return jsonify({"error": "An unknown error occurred"}), 500

# --- AI IMAGE ENHANCER API ENDPOINT ---

@app.route('/enhance-image', methods=['POST'])
def enhance_image_api():
    # 1. --- API Key Authentication (Bilkul pehle jaisa) ---
    api_key_header = request.headers.get('x-api-key')
    if not api_key_header or api_key_header != API_KEY:
        return jsonify({"error": "Unauthorized. Invalid or missing API Key."}), 401

    # 2. --- File Check Karna ---
    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 selected file"}), 400

    # 3. --- Image Processing (Pillow Library ka Jadoo) ---
    if file:
        try:
            # File ko memory mein bytes ki tarah parhna
            input_image_bytes = file.read()
            
            # Pillow ka istemal karke image ko kholna
            img = Image.open(io.BytesIO(input_image_bytes))
            
            # Enhancement Step 1: Contrast ko behtar karna
            # 1.0 original contrast hai. 1.2 ka matlab hai 20% zyada contrast.
            enhancer_contrast = ImageEnhance.Contrast(img)
            img = enhancer_contrast.enhance(1.2)
            
            # Enhancement Step 2: Sharpness ko behtar karna
            # 1.0 original sharpness hai. 1.4 ka matlab hai 40% zyada sharp.
            enhancer_sharpness = ImageEnhance.Sharpness(img)
            img = enhancer_sharpness.enhance(1.4)
            
            # Ek khali "in-memory" file banana
            output_buffer = io.BytesIO()
            
            # Enhanced image ko buffer mein save karna
            # PNG format mein save karein taake transparency (agar ho) barqarar rahe
            img.save(output_buffer, format='PNG')
            
            # Enhanced image ke bytes haasil karna
            output_image_bytes = output_buffer.getvalue()

            # 4. --- Send the Response ---
            # Enhanced image ko user ko wapas bhejna
            return send_file(
                io.BytesIO(output_image_bytes),
                mimetype='image/png',
                as_attachment=True,
                download_name='enhanced_image.png'
            )
        except Exception as e:
            return jsonify({"error": "Failed to enhance image", "details": str(e)}), 500

    return jsonify({"error": "An unknown error occurred"}), 500

# --- Run the App ---
if __name__ == '__main__':
    # For local testing, ensure the environment variable is set.
    if not API_KEY:
        # If you're using the temporary hard-coded key method, you can ignore this error.
        # Otherwise, this reminds you to set the variable.
        print("WARNING: BG_REMOVER_API_KEY is not set. The API will not be secured.")
        print("For local testing, run 'set BG_REMOVER_API_KEY=your-key' (Windows) or 'export BG_REMOVER_API_KEY=your-key' (Mac/Linux) first.")
    
    app.run(debug=True, port=5000)