File size: 14,764 Bytes
1fb00de
 
 
 
 
 
 
60493a2
1fb00de
5754201
 
1fb00de
 
 
 
 
 
 
 
5754201
f6f8006
7956aa1
1fb00de
 
 
 
 
 
f6f8006
 
5754201
f6f8006
1fb00de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3eefc8f
 
692f363
1fb00de
692f363
 
 
3eefc8f
692f363
3eefc8f
692f363
1fb00de
692f363
 
 
 
 
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
692f363
 
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
 
692f363
 
 
 
 
 
1fb00de
 
692f363
 
1fb00de
3eefc8f
 
 
 
1fb00de
 
 
3eefc8f
692f363
 
1fb00de
 
 
 
3eefc8f
 
692f363
1fb00de
692f363
 
 
3eefc8f
692f363
3eefc8f
692f363
1fb00de
692f363
 
 
 
 
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
692f363
 
 
 
 
 
 
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
 
692f363
 
 
 
 
 
1fb00de
 
692f363
 
1fb00de
3eefc8f
 
 
 
1fb00de
 
 
3eefc8f
692f363
 
1fb00de
 
 
 
3eefc8f
 
692f363
1fb00de
 
692f363
3eefc8f
692f363
 
 
3eefc8f
692f363
 
1fb00de
692f363
 
1fb00de
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
692f363
1fb00de
 
 
692f363
 
3eefc8f
 
 
 
 
692f363
1fb00de
692f363
1fb00de
 
692f363
 
1fb00de
692f363
1fb00de
3eefc8f
692f363
 
1fb00de
 
 
5754201
3eefc8f
 
692f363
1fb00de
692f363
 
 
 
 
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
692f363
 
 
 
 
3eefc8f
692f363
3eefc8f
692f363
 
1fb00de
 
692f363
 
 
 
1fb00de
692f363
1fb00de
3eefc8f
 
 
 
 
692f363
 
 
 
 
1fb00de
3eefc8f
692f363
 
5754201
 
 
692f363
 
5754201
3eefc8f
 
692f363
5754201
692f363
 
 
 
3eefc8f
692f363
3eefc8f
692f363
 
5754201
692f363
 
 
3eefc8f
692f363
3eefc8f
692f363
 
5754201
 
692f363
 
 
 
5754201
692f363
5754201
3eefc8f
 
 
 
 
692f363
 
 
 
 
5754201
3eefc8f
692f363
 
f6f8006
 
 
 
3eefc8f
 
60493a2
692f363
f6f8006
692f363
 
3eefc8f
692f363
3eefc8f
692f363
 
60493a2
692f363
 
60493a2
 
3eefc8f
692f363
3eefc8f
692f363
 
 
 
 
 
60493a2
3eefc8f
 
 
 
 
692f363
60493a2
 
 
692f363
 
f6f8006
3eefc8f
692f363
 
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
"""
project @ NTO-TCP-HF
created @ 2024-10-28
author  @ github.com/ishworrsubedii
"""
import base64
import os
import time
from io import BytesIO

import cv2
import numpy as np
import replicate
import requests
from PIL import Image
from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse

from src.components.auto_crop import crop_transparent_image
from src.components.color_extraction import ColorExtractionRMBG
from src.components.title_des_gen import NecklaceProductListing
from src.utils.logger import logger

preprocessing_router = APIRouter()

rmbg: str = os.getenv("RMBG")

enhancer: str = os.getenv("ENHANCER")
prod_listing_api_key: str = os.getenv("PROD_LISTING_API_KEY")

color_extraction_rmbg = ColorExtractionRMBG()
product_listing_obj = NecklaceProductListing(prod_listing_api_key)


def replicate_bg(input):
    output = replicate.run(
        rmbg,
        input=input
    )
    return output


def replicate_enhancer(input):
    output = replicate.run(
        enhancer,
        input=input
    )
    return output


@preprocessing_router.post("/rem_bg")
async def remove_background(image: UploadFile = File(...)):
    logger.info("-" * 50)
    logger.info(">>> REMOVE BACKGROUND STARTED <<<")
    start_time = time.time()

    try:
        image_bytes = await image.read()
        image = Image.open(BytesIO(image_bytes)).convert("RGB")
        logger.info(">>> IMAGE LOADED SUCCESSFULLY <<<")
    except Exception as e:
        logger.error(f">>> IMAGE LOADING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500, content={"error": f"Error reading image: {str(e)}", "code": 500})

    try:
        act_img_base_64 = BytesIO()
        image.save(act_img_base_64, format="WEBP")
        image_bytes_ = base64.b64encode(act_img_base_64.getvalue()).decode("utf-8")
        image_data_uri = f"data:image/WEBP;base64,{image_bytes_}"
        logger.info(">>> IMAGE ENCODING COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> IMAGE ENCODING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error converting image to base64: {str(e)}", "code": 500})

    try:
        output = replicate_bg({"image": image_data_uri})
        logger.info(">>> BACKGROUND REMOVAL COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> BACKGROUND REMOVAL ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error running background removal: {str(e)}", "code": 500})

    try:
        response = requests.get(output)
        base_64 = base64.b64encode(response.content).decode('utf-8')
        base64_prefix = "data:image/WEBP;base64,"

        total_inference_time = round((time.time() - start_time), 2)

        response = {
            "output": f"{base64_prefix}{base_64}",
            "inference_time": total_inference_time,
            "code": 200
        }
        logger.info(">>> RESPONSE PREPARATION COMPLETED <<<")
        logger.info(f">>> TOTAL INFERENCE TIME: {total_inference_time}s <<<")
        logger.info(">>> REQUEST COMPLETED SUCCESSFULLY <<<")
        logger.info("-" * 50)
        return JSONResponse(content=response, status_code=200)

    except Exception as e:
        logger.error(f">>> RESPONSE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error processing response: {str(e)}", "code": 500})


@preprocessing_router.post("/upscale_image")
async def upscale_image(image: UploadFile = File(...), scale: int = 1):
    logger.info("-" * 50)
    logger.info(">>> IMAGE UPSCALING STARTED <<<")
    start_time = time.time()

    try:
        image_bytes = await image.read()
        image = Image.open(BytesIO(image_bytes)).convert("RGBA")
        logger.info(">>> IMAGE LOADED SUCCESSFULLY <<<")
    except Exception as e:
        logger.error(f">>> IMAGE LOADING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500, content={"error": f"Error reading image: {str(e)}", "code": 500})

    try:
        act_img_base_64 = BytesIO()
        image.save(act_img_base_64, format="PNG")
        image_bytes_ = base64.b64encode(act_img_base_64.getvalue()).decode("utf-8")
        image_data_uri = f"data:image/png;base64,{image_bytes_}"
        logger.info(">>> IMAGE ENCODING COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> IMAGE ENCODING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error converting image to base64: {str(e)}", "code": 500})

    try:
        input = {
            "image": image_data_uri,
            "scale": scale,
            "face_enhance": False
        }
        output = replicate_enhancer(input)
        logger.info(">>> IMAGE ENHANCEMENT COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> IMAGE ENHANCEMENT ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error running image enhancement: {str(e)}", "code": 500})

    try:
        response = requests.get(output)
        base_64 = base64.b64encode(response.content).decode('utf-8')
        base64_prefix = image_data_uri.split(",")[0] + ","

        total_inference_time = round((time.time() - start_time), 2)

        response = {
            "output": f"{base64_prefix}{base_64}",
            "inference_time": total_inference_time,
            "code": 200
        }
        logger.info(">>> RESPONSE PREPARATION COMPLETED <<<")
        logger.info(f">>> TOTAL INFERENCE TIME: {total_inference_time}s <<<")
        logger.info(">>> REQUEST COMPLETED SUCCESSFULLY <<<")
        logger.info("-" * 50)
        return JSONResponse(content=response, status_code=200)

    except Exception as e:
        logger.error(f">>> RESPONSE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error processing response: {str(e)}", "code": 500})


@preprocessing_router.post("/crop_transparent")
async def crop_transparent(image: UploadFile):
    logger.info("-" * 50)
    logger.info(">>> CROP TRANSPARENT STARTED <<<")
    start_time = time.time()

    try:
        if not image.content_type == "image/png":
            logger.error(">>> INVALID FILE TYPE: NOT PNG <<<")
            return JSONResponse(status_code=400,
                                content={"error": "Only PNG files are supported", "code": 400})
    except Exception as e:
        logger.error(f">>> FILE TYPE CHECK ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error checking file type: {str(e)}", "code": 500})

    try:
        contents = await image.read()
        cropped_image_bytes, metadata = crop_transparent_image(contents)
        logger.info(">>> IMAGE CROPPING COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> IMAGE CROPPING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error cropping image: {str(e)}", "code": 500})

    try:
        base64_image = base64.b64encode(cropped_image_bytes).decode('utf-8')
        base64_prefix = "data:image/png;base64,"

        total_inference_time = round((time.time() - start_time), 2)

        logger.info(">>> RESPONSE PREPARATION COMPLETED <<<")
        logger.info(f">>> TOTAL INFERENCE TIME: {total_inference_time}s <<<")
        logger.info(">>> REQUEST COMPLETED SUCCESSFULLY <<<")
        logger.info("-" * 50)

        return JSONResponse(content={
            "status": "success",
            "code": 200,
            "data": {
                "image": f"{base64_prefix}{base64_image}",
                "metadata": metadata,
                "inference_time": total_inference_time
            }
        }, status_code=200)
    except Exception as e:
        logger.error(f">>> RESPONSE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error processing response: {str(e)}", "code": 500})


@preprocessing_router.post("/background_replace")
async def bg_replace(image: UploadFile = File(...), bg_image: UploadFile = File(...)):
    logger.info("-" * 50)
    logger.info(">>> BACKGROUND REPLACE STARTED <<<")
    start_time = time.time()

    try:
        image_bytes = await image.read()
        bg_bytes = await bg_image.read()
        image = Image.open(BytesIO(image_bytes)).convert("RGBA")
        bg_image = Image.open(BytesIO(bg_bytes)).convert("RGB")
        logger.info(">>> IMAGES LOADED SUCCESSFULLY <<<")
    except Exception as e:
        logger.error(f">>> IMAGE LOADING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error reading images: {str(e)}", "code": 500})

    try:
        width, height = bg_image.size
        background = Image.fromarray(np.array(bg_image)).resize((width, height))
        orig_img = Image.fromarray(np.array(image)).resize((width, height))
        background.paste(orig_img, (0, 0), mask=orig_img)
        logger.info(">>> IMAGE PROCESSING COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> IMAGE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error processing images: {str(e)}", "code": 500})

    try:
        act_img_base_64 = BytesIO()
        background.save(act_img_base_64, format="WEBP")
        image_bytes_ = base64.b64encode(act_img_base_64.getvalue()).decode("utf-8")
        image_data_uri = f"data:image/webp;base64,{image_bytes_}"

        total_inference_time = round((time.time() - start_time), 2)

        logger.info(">>> RESPONSE PREPARATION COMPLETED <<<")
        logger.info(f">>> TOTAL INFERENCE TIME: {total_inference_time}s <<<")
        logger.info(">>> REQUEST COMPLETED SUCCESSFULLY <<<")
        logger.info("-" * 50)

        return JSONResponse(content={
            "output": image_data_uri,
            "code": 200,
            "inference_time": total_inference_time
        }, status_code=200)
    except Exception as e:
        logger.error(f">>> RESPONSE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error creating response: {str(e)}", "code": 500})


@preprocessing_router.post("/rem_bg_color_extraction")
async def remove_background_color_extraction(image: UploadFile = File(...),
                                             hex_color: str = "#FFFFFF",
                                             threshold: int = 30):
    logger.info("-" * 50)
    logger.info(">>> COLOR EXTRACTION STARTED <<<")
    start_time = time.time()

    try:
        image_bytes = await image.read()
        image = Image.open(BytesIO(image_bytes)).convert("RGBA")
        image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
        logger.info(">>> IMAGE LOADED SUCCESSFULLY <<<")
    except Exception as e:
        logger.error(f">>> IMAGE LOADING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error reading image: {str(e)}", "code": 500})

    try:
        result = color_extraction_rmbg.extract_color(image, hex_color, threshold)
        result = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_RGB2BGRA)).convert("RGBA")
        logger.info(">>> COLOR EXTRACTION COMPLETED <<<")
    except Exception as e:
        logger.error(f">>> COLOR EXTRACTION ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error extracting colors: {str(e)}", "code": 500})

    try:
        act_img_base_64 = BytesIO()
        result.save(act_img_base_64, format="PNG")
        image_bytes_ = base64.b64encode(act_img_base_64.getvalue()).decode("utf-8")
        image_data_uri = f"data:image/png;base64,{image_bytes_}"

        total_inference_time = round((time.time() - start_time), 2)

        logger.info(">>> RESPONSE PREPARATION COMPLETED <<<")
        logger.info(f">>> TOTAL INFERENCE TIME: {total_inference_time}s <<<")
        logger.info(">>> REQUEST COMPLETED SUCCESSFULLY <<<")
        logger.info("-" * 50)

        return JSONResponse(content={
            "output": image_data_uri,
            "code": 200,
            "inference_time": total_inference_time
        }, status_code=200)
    except Exception as e:
        logger.error(f">>> RESPONSE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error creating response: {str(e)}", "code": 500})


@preprocessing_router.post("/title_description_generator")
async def product_title_description_generator(image: UploadFile = File(...)):
    logger.info("-" * 50)
    logger.info(">>> TITLE DESCRIPTION GENERATION STARTED <<<")
    start_time = time.time()

    try:
        image_bytes = await image.read()
        image = Image.open(BytesIO(image_bytes)).convert("RGB")
        logger.info(">>> IMAGE LOADED SUCCESSFULLY <<<")
    except Exception as e:
        logger.error(f">>> IMAGE LOADING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error reading image: {str(e)}", "code": 500})

    try:
        result = product_listing_obj.gen_title_desc(image=image)
        title = result.split("Title:")[1].split("Description:")[0]
        description = result.split("Description:")[1]
        logger.info(">>> TITLE AND DESCRIPTION GENERATION COMPLETED <<<")
    except Exception as e:
        logger.error(">>> TITLE DESCRIPTION GENERATION ERROR <<<")
        return JSONResponse(status_code=500,
                            content={"error": "Please make sure the image is clear and necklaces are visible",
                                     "code": 500})

    try:
        total_inference_time = round((time.time() - start_time), 2)

        logger.info(">>> RESPONSE PREPARATION COMPLETED <<<")
        logger.info(f">>> TOTAL INFERENCE TIME: {total_inference_time}s <<<")
        logger.info(">>> REQUEST COMPLETED SUCCESSFULLY <<<")
        logger.info("-" * 50)

        return JSONResponse(content={
            "code": 200,
            "title": title,
            "description": description,
            "inference_time": total_inference_time
        }, status_code=200)
    except Exception as e:
        logger.error(f">>> RESPONSE PROCESSING ERROR: {str(e)} <<<")
        return JSONResponse(status_code=500,
                            content={"error": f"Error creating response: {str(e)}", "code": 500})