File size: 11,961 Bytes
8af3d5d
 
 
 
 
7f206ba
8af3d5d
5bcd6fb
 
002f18d
 
8af3d5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f206ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bcd6fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c52f854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
002f18d
 
 
1d96340
002f18d
 
 
 
1d96340
002f18d
 
 
 
 
 
 
1d96340
002f18d
c52f854
 
 
 
 
 
 
 
002f18d
1d96340
002f18d
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# app.py

import os
from flask import Flask, request, send_file, jsonify
from rembg import remove
from PIL import Image, ImageEnhance, ImageFilter
import io
import cv2
import numpy as np
from diffusers import DiffusionPipeline
import torch

# --- 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

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

@app.route('/auto-enhance-image', methods=['POST'])
def auto_enhance_image_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. --- File Check ---
    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. --- Professional Image Enhancement with OpenCV ---
    if file:
        try:
            # Image ko bytes se parh kar ek NumPy array mein convert karna
            filestr = file.read()
            npimg = np.frombuffer(filestr, np.uint8)
            img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)

            # --- Enhancement Step 1: CLAHE for Perfect Contrast ---
            # Image ko LAB color space mein convert karna
            lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
            l, a, b = cv2.split(lab)
            # Lightness (L) channel per CLAHE apply karna
            clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
            cl = clahe.apply(l)
            # Channels ko wapas milana
            limg = cv2.merge((cl, a, b))
            # Image ko wapas BGR color space mein convert karna
            img_clahe = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

            # --- Enhancement Step 2: Unsharp Masking for Natural Sharpness ---
            # Image ko thoda blur karna
            gaussian_blur = cv2.GaussianBlur(img_clahe, (0, 0), 3.0)
            # Original image mein sharpness add karna
            # Is se details bohot behtar ho jaati hain
            img_enhanced = cv2.addWeighted(img_clahe, 1.5, gaussian_blur, -0.5, 0)

            # --- Final Result ---
            # Processed image (NumPy array) ko wapas PNG bytes mein convert karna
            is_success, buffer = cv2.imencode(".png", img_enhanced)
            if not is_success:
                raise Exception("Could not encode enhanced image.")
            
            output_image_bytes = buffer.tobytes()

            # 4. --- Send the Response ---
            return send_file(
                io.BytesIO(output_image_bytes),
                mimetype='image/png',
                as_attachment=True,
                download_name='auto_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

# --- AI IMAGE GENERATOR (TEXT-TO-IMAGE) API ENDPOINT (FINAL, GUARANTEED LAZY LOADING) ---

# Hum model ke liye ek global "box" (variable) banayenge, lekin usko start mein khali rakhenge.
pipe = None

def get_pipeline():
    """
    Yeh ek helper function hai jo model ko sirf ek baar load karega.
    """
    global pipe
    if pipe is None:
        print("Model not loaded. Loading Tiny Stable Diffusion model for the first time...")
        # Note: Secrets (like HUGGING_FACE_HUB_CACHE) will be available here.
        pipe = DiffusionPipeline.from_pretrained(
            "hf-internal-testing/tiny-stable-diffusion-torch"
        )
        print("Model loaded successfully into memory.")
    return pipe

@app.route('/generate-image', methods=['POST'])
def generate_image_api():
    # 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

    # User ka Text Prompt Haasil Karna
    if not request.is_json:
        return jsonify({"error": "Invalid request: JSON expected"}), 400
    data = request.get_json()
    prompt = data.get('prompt', '')
    if not prompt:
        return jsonify({"error": "Prompt is required"}), 400

    # AI Model se Image Generate Karna
    try:
        # Har request per, hum helper function ko call karke model haasil karenge.
        # Agar model pehle se loaded hai, to woh foran mil jayega.
        # Agar nahi, to woh ab load hoga.
        pipeline = get_pipeline()
        
        print(f"Generating image for prompt: {prompt}")
        image = pipeline(prompt, num_inference_steps=10).images[0]
        print("Image generated.")
        
        output_buffer = io.BytesIO()
        image.save(output_buffer, format='PNG')
        output_image_bytes = output_buffer.getvalue()

        return send_file(
            io.BytesIO(output_image_bytes),
            mimetype='image/png',
            as_attachment=True,
            download_name='generated_image.png'
        )
    except Exception as e:
        return jsonify({"error": "Failed to generate image", "details": str(e)}), 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)