File size: 19,664 Bytes
e5cd884
 
2084241
e5cd884
e595815
e5cd884
cbb8fb9
2084241
e5cd884
 
 
 
 
 
 
375118a
 
2084241
 
7984e65
73008db
e5cd884
 
2084241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5cd884
2084241
73008db
 
 
2084241
 
 
 
 
292b6e8
cbb8fb9
e5cd884
 
 
 
 
 
 
2084241
e5cd884
2084241
e5cd884
 
 
 
 
 
 
 
2084241
 
 
 
cbb8fb9
2084241
 
 
 
 
 
 
 
 
 
 
 
e5cd884
 
 
 
 
 
 
 
e2c6448
 
 
 
 
 
 
 
 
 
 
 
 
 
fcf34e8
 
 
 
 
 
 
 
e2c6448
 
 
7984e65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5cd884
 
 
972563b
 
 
 
 
375118a
a9c5030
 
 
 
 
92a5960
 
a9c5030
 
 
 
92a5960
 
 
a9c5030
 
 
 
 
 
 
 
 
 
92a5960
a9c5030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a5960
a9c5030
92a5960
 
 
a9c5030
 
 
 
 
 
 
 
 
92a5960
e595815
92a5960
 
 
 
 
1c6fc8d
92a5960
 
1c6fc8d
d6c9bc8
92a5960
 
1c6fc8d
d6c9bc8
 
 
92a5960
1c6fc8d
92a5960
1c6fc8d
e595815
 
 
 
1c6fc8d
 
 
 
 
 
e595815
 
 
 
1c6fc8d
 
 
 
 
 
 
 
 
 
 
e595815
 
 
fcf34e8
b22b681
c41d228
31e6847
 
 
 
 
 
 
b22b681
 
 
 
 
 
c41d228
b22b681
 
c41d228
b22b681
 
 
 
 
c41d228
b22b681
 
c41d228
b22b681
 
 
 
 
31e6847
b22b681
 
31e6847
b22b681
31e6847
 
b22b681
 
 
 
 
 
 
31e6847
 
c41d228
1c6fc8d
 
 
92a5960
d6c9bc8
92a5960
 
 
d6c9bc8
92a5960
1c6fc8d
 
 
92a5960
 
1c6fc8d
 
92a5960
 
d6c9bc8
92a5960
d6c9bc8
 
 
 
 
 
92a5960
 
d6c9bc8
92a5960
 
1c6fc8d
92a5960
 
 
 
 
a9c5030
 
2eb209a
a9c5030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a5960
a9c5030
92a5960
 
 
a9c5030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7984e65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9c5030
 
 
92a5960
 
 
a9c5030
 
92a5960
a9c5030
 
 
 
92a5960
 
a9c5030
 
 
 
 
7984e65
 
 
 
a9c5030
92a5960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9c5030
2084241
73008db
e5cd884
3702fa6
 
e5cd884
 
 
 
 
 
 
 
 
 
 
 
 
3702fa6
 
 
 
 
 
cbb8fb9
73008db
 
 
 
 
 
cbb8fb9
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import os
import io
import json
import traceback
from datetime import datetime,timedelta
from typing import Optional
import time
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request, Depends
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from pymongo import MongoClient
import gridfs
from bson.objectid import ObjectId
from PIL import Image
from fastapi.concurrency import run_in_threadpool
import shutil
import firebase_admin
from firebase_admin import credentials, auth
from PIL import Image
from huggingface_hub import InferenceClient

# ---------------------------------------------------------------------
# Load Firebase Config from env (stringified JSON)
# ---------------------------------------------------------------------
firebase_config_json = os.getenv("firebase_config")
if not firebase_config_json:
    raise RuntimeError("❌ Missing Firebase config in environment variable 'firebase_config'")

try:
    firebase_creds_dict = json.loads(firebase_config_json)
    cred = credentials.Certificate(firebase_creds_dict)
    firebase_admin.initialize_app(cred)
except Exception as e:
    raise RuntimeError(f"Failed to initialize Firebase Admin SDK: {e}")

# ---------------------------------------------------------------------
# Hugging Face setup
# ---------------------------------------------------------------------
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
    raise RuntimeError("HF_TOKEN not set in environment variables")

hf_client = InferenceClient(token=HF_TOKEN)

# ---------------------------------------------------------------------
# MongoDB setup
# ---------------------------------------------------------------------
MONGODB_URI=os.getenv("MONGODB_URI")
DB_NAME = "polaroid_db"

mongo = MongoClient(MONGODB_URI)
db = mongo[DB_NAME]
fs = gridfs.GridFS(db)
logs_collection = db["logs"]

# ---------------------------------------------------------------------
# FastAPI app setup
# ---------------------------------------------------------------------
app = FastAPI(title="Qwen Image Edit API with Firebase Auth")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ---------------------------------------------------------------------
# Auth dependency
# ---------------------------------------------------------------------
async def verify_firebase_token(request: Request):
    """Middleware-like dependency to verify Firebase JWT from Authorization header."""
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")

    id_token = auth_header.split("Bearer ")[1]
    try:
        decoded_token = auth.verify_id_token(id_token)
        request.state.user = decoded_token
        return decoded_token
    except Exception as e:
        raise HTTPException(status_code=401, detail=f"Invalid or expired Firebase token: {e}")

# ---------------------------------------------------------------------
# Models
# ---------------------------------------------------------------------
class HealthResponse(BaseModel):
    status: str
    db: str
    model: str

# --------------------- UTILS ---------------------
def resize_image_if_needed(img: Image.Image, max_size=(1024, 1024)) -> Image.Image:
    """
    Resize image to fit within max_size while keeping aspect ratio.
    """
    if img.width > max_size[0] or img.height > max_size[1]:
        img.thumbnail(max_size, Image.ANTIALIAS)
    return img

def prepare_image(file_bytes: bytes) -> Image.Image:
    """
    Open image and resize if larger than 1024x1024
    """
    img = Image.open(io.BytesIO(file_bytes)).convert("RGB")

    # βœ… MIN SIZE CHECK
    if img.width < 200 or img.height < 200:
        raise HTTPException(
            status_code=400,
            detail="Image size is below 200x200 pixels. Please upload a larger image."
        )
    img = Image.open(io.BytesIO(file_bytes)).convert("RGB")
    img = resize_image_if_needed(img, max_size=(1024, 1024))
    return img
    
MAX_COMPRESSED_SIZE = 2 * 1024 * 1024  # 2 MB
def compress_pil_image_to_2mb(
    pil_img: Image.Image,
    max_dim: int = 1280
) -> bytes:
    """
    Resize + compress PIL image to <= 2MB.
    Returns JPEG bytes.
    """
    img = pil_img.convert("RGB")

    # Resize (maintain aspect ratio)
    img.thumbnail((max_dim, max_dim), Image.LANCZOS)

    quality = 85
    buffer = io.BytesIO()

    while quality >= 40:
        buffer.seek(0)
        buffer.truncate()

        img.save(
            buffer,
            format="JPEG",
            quality=quality,
            optimize=True,
            progressive=True
        )

        if buffer.tell() <= MAX_COMPRESSED_SIZE:
            break

        quality -= 5

    return buffer.getvalue()
# ---------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------
@app.get("/health", response_model=HealthResponse)
def health():
    """Public health check"""
    mongo.admin.command("ping")
    return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")

@app.post("/generate")
async def generate(
    prompt: str = Form(...),
    image1: UploadFile = File(...),
    image2: Optional[UploadFile] = File(None),
    user_id: Optional[str] = Form(None),
    category_id: Optional[str] = Form(None),
    user=Depends(verify_firebase_token)
):
    start_time = time.time()

    # -------------------------
    # 1. VALIDATE & READ IMAGES
    # -------------------------
    try:
        img1_bytes = await image1.read()
        pil_img1 = prepare_image(img1_bytes)
        input1_id = fs.put(
            img1_bytes,
            filename=image1.filename,
            contentType=image1.content_type,
            metadata={"role": "input"}
        )
    except Exception as e:
        raise HTTPException(400, f"Failed to read first image: {e}")

    img2_bytes = None
    input2_id = None
    pil_img2 = None

    if image2:
        try:
            img2_bytes = await image2.read()
            pil_img2 = prepare_image(img2_bytes)
            input2_id = fs.put(
                img2_bytes,
                filename=image2.filename,
                contentType=image2.content_type,
                metadata={"role": "input"}
            )
        except Exception as e:
            raise HTTPException(400, f"Failed to read second image: {e}")

    # -------------------------
    # 2. COMBINE IF NEEDED
    # -------------------------
    if pil_img2:
        total_width = pil_img1.width + pil_img2.width
        max_height = max(pil_img1.height, pil_img2.height)
        combined_img = Image.new("RGB", (total_width, max_height))
        combined_img.paste(pil_img1, (0, 0))
        combined_img.paste(pil_img2, (pil_img1.width, 0))
    else:
        combined_img = pil_img1

    # -------------------------
    # 3. CATEGORY CLICK LOGIC
    # -------------------------
    if user_id and category_id:
        try:
            admin_client = MongoClient(os.getenv("ADMIN_MONGODB_URI"))
            admin_db = admin_client["adminPanel"]
    
            categories_col = admin_db.categories
            media_clicks_col = admin_db.media_clicks
    
            # Validate user_oid & category_oid
            user_oid = ObjectId(user_id)
            category_oid = ObjectId(category_id)
    
            # Check category exists
            category_doc = categories_col.find_one({"_id": category_oid})
            if not category_doc:
                raise HTTPException(400, f"Invalid category_id: {category_id}")
    
            now = datetime.utcnow()
    
            # Normalize dates (UTC midnight)
            today_date = datetime(now.year, now.month, now.day)
            yesterday_date = today_date - timedelta(days=1)
    
            # --------------------------------------------------
            # AI EDIT USAGE TRACKING (GLOBAL PER USER)
            # --------------------------------------------------
            media_clicks_col.update_one(
                {"userId": user_oid},
                {
                    "$setOnInsert": {
                        "createdAt": now,
                        "ai_edit_daily_count": []
                    },
                    "$set": {
                        "ai_edit_last_date": now,
                        "updatedAt": now
                    },
                    "$inc": {
                        "ai_edit_complete": 1
                    }
                },
                upsert=True
            )
    
            # --------------------------------------------------
            # DAILY COUNT LOGIC
            # --------------------------------------------------
            now = datetime.utcnow()
            today_date = datetime(now.year, now.month, now.day)
            
            doc = media_clicks_col.find_one(
                {"userId": user_oid},
                {"ai_edit_daily_count": 1}
            )
            
            daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
            
            # Build UNIQUE date -> count map
            daily_map = {}
            for entry in daily_entries:
                d = entry["date"]
                d = datetime(d.year, d.month, d.day) if isinstance(d, datetime) else d
                daily_map[d] = entry["count"]  # overwrite = no duplicates
            
            # Find last known date
            last_date = max(daily_map.keys()) if daily_map else today_date
            
            # Fill ALL missing days with 0
            next_day = last_date + timedelta(days=1)
            while next_day < today_date:
                daily_map.setdefault(next_day, 0)
                next_day += timedelta(days=1)
            
            # Mark today as used (binary)
            daily_map[today_date] = 1
            
            # Rebuild list (OLD β†’ NEW)
            final_daily_entries = [
                {"date": d, "count": daily_map[d]}
                for d in sorted(daily_map.keys())
            ]
            
            # Keep last 32 days only
            final_daily_entries = final_daily_entries[-32:]
            
            # ATOMIC REPLACE (NO PUSH)
            media_clicks_col.update_one(
                {"userId": user_oid},
                {
                    "$set": {
                        "ai_edit_daily_count": final_daily_entries,
                        "ai_edit_last_date": now,
                        "updatedAt": now
                    }
                }
            )


            # --------------------------------------------------
            # CATEGORY CLICK LOGIC
            # --------------------------------------------------
            update_res = media_clicks_col.update_one(
                {"userId": user_oid, "categories.categoryId": category_oid},
                {
                    "$set": {
                        "updatedAt": now,
                        "categories.$.lastClickedAt": now
                    },
                    "$inc": {
                        "categories.$.click_count": 1
                    }
                }
            )
    
            # If category does not exist β†’ push new
            if update_res.matched_count == 0:
                media_clicks_col.update_one(
                    {"userId": user_oid},
                    {
                        "$set": {"updatedAt": now},
                        "$push": {
                            "categories": {
                                "categoryId": category_oid,
                                "click_count": 1,
                                "lastClickedAt": now
                            }
                        }
                    },
                    upsert=True
                )
    
        except Exception as e:
            print("CATEGORY_LOG_ERROR:", e)
    # -------------------------
    # 4. HF INFERENCE
    # -------------------------
    try:
        pil_output = hf_client.image_to_image(
            image=combined_img,
            prompt=prompt,
            model="Qwen/Qwen-Image-Edit"
        )
    except Exception as e:
        response_time_ms = round((time.time() - start_time) * 1000)
        logs_collection.insert_one({
            "timestamp": datetime.utcnow(),
            "status": "failure",
            "input1_id": str(input1_id),
            "input2_id": str(input2_id) if input2_id else None,
            "prompt": prompt,
            "user_email": user.get("email"),
            "error": str(e),
            "response_time_ms": response_time_ms
        })
        raise HTTPException(500, f"Inference failed: {e}")

    # -------------------------
    # 5. SAVE OUTPUT IMAGE
    # -------------------------
    out_buf = io.BytesIO()
    pil_output.save(out_buf, format="PNG")
    out_bytes = out_buf.getvalue()

    out_id = fs.put(
        out_bytes,
        filename=f"result_{input1_id}.png",
        contentType="image/png",
        metadata={
            "role": "output",
            "prompt": prompt,
            "input1_id": str(input1_id),
            "input2_id": str(input2_id) if input2_id else None,
            "user_email": user.get("email"),
        }
    )
    # -------------------------
    # 5b. SAVE COMPRESSED IMAGE
    # -------------------------
    compressed_bytes = compress_pil_image_to_2mb(
        pil_output,
        max_dim=1280
    )
    
    compressed_id = fs.put(
        compressed_bytes,
        filename=f"result_{input1_id}_compressed.jpg",
        contentType="image/jpeg",
        metadata={
            "role": "output_compressed",
            "original_output_id": str(out_id),
            "prompt": prompt,
            "user_email": user.get("email")
        }
    )


    response_time_ms = round((time.time() - start_time) * 1000)

    # -------------------------
    # 6. LOG SUCCESS
    # -------------------------
    logs_collection.insert_one({
        "timestamp": datetime.utcnow(),
        "status": "success",
        "input1_id": str(input1_id),
        "input2_id": str(input2_id) if input2_id else None,
        "output_id": str(out_id),
        "prompt": prompt,
        "user_email": user.get("email"),
        "response_time_ms": response_time_ms
    })

    return JSONResponse({
        "output_image_id": str(out_id),
        "user": user.get("email"),
        "response_time_ms": response_time_ms,
        "Compressed_Image_URL": (
            f"https://logicgoinfotechspaces-polaroidimage.hf.space/image/{compressed_id}"
        )
    })
####################---------------------------------------------------------------------------------------------------###
###-----OLD CODE--------------####
# @app.post("/generate")
# async def generate(
#     prompt: str = Form(...),
#     image1: UploadFile = File(...),
#     image2: Optional[UploadFile] = File(None),
#     user=Depends(verify_firebase_token)
# ):
#     start_time = time.time()

#     # PREPARE IMAGE(S)
#     try:
#         img1_bytes = await image1.read()
#         pil_img1 = prepare_image(img1_bytes)
#         input1_id = fs.put(
#             img1_bytes,
#             filename=image1.filename,
#             contentType=image1.content_type,
#             metadata={"role": "input"}
#         )
#     except Exception as e:
#         raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")

#     img2_bytes = None
#     input2_id = None
#     pil_img2 = None

#     if image2:
#         try:
#             img2_bytes = await image2.read()
#             pil_img2 = prepare_image(img2_bytes)
#             input2_id = fs.put(
#                 img2_bytes,
#                 filename=image2.filename,
#                 contentType=image2.content_type,
#                 metadata={"role": "input"}
#             )
#         except Exception as e:
#             raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")

#     # COMBINE IF NEEDED
#     if pil_img2:
#         total_width = pil_img1.width + pil_img2.width
#         max_height = max(pil_img1.height, pil_img2.height)
#         combined_img = Image.new("RGB", (total_width, max_height))
#         combined_img.paste(pil_img1, (0, 0))
#         combined_img.paste(pil_img2, (pil_img1.width, 0))
#     else:
#         combined_img = pil_img1

#     # INFERENCE
#     try:
#         pil_output = hf_client.image_to_image(
#             image=combined_img,
#             prompt=prompt,
#             model="Qwen/Qwen-Image-Edit"
#         )
#     except Exception as e:
#         # LOG FAILURE
#         response_time_ms = round((time.time() - start_time) * 1000)
#         logs_collection.insert_one({
#             "timestamp": datetime.utcnow(),
#             "status": "failure",
#             "input1_id": str(input1_id),
#             "input2_id": str(input2_id) if input2_id else None,
#             "prompt": prompt,
#             "user_email": user.get("email"),
#             "error": str(e),
#             "response_time_ms": response_time_ms
#         })
#         raise HTTPException(status_code=500, detail=f"Inference failed: {e}")

#     # SAVE OUTPUT IMAGE
#     out_buf = io.BytesIO()
#     pil_output.save(out_buf, format="PNG")
#     out_bytes = out_buf.getvalue()

#     out_id = fs.put(
#         out_bytes,
#         filename=f"result_{input1_id}.png",
#         contentType="image/png",
#         metadata={
#             "role": "output",
#             "prompt": prompt,
#             "input1_id": str(input1_id),
#             "input2_id": str(input2_id) if input2_id else None,
#             "user_email": user.get("email"),
#         }
#     )

#     # FINAL RESPONSE TIME
#     response_time_ms = round((time.time() - start_time) * 1000)

#     # LOG SUCCESS - THIS WAS MISSING THE STATUS AND RESPONSE_TIME_MS FIELDS!
#     logs_collection.insert_one({
#         "timestamp": datetime.utcnow(),
#         "status": "success",  # βœ… FIXED: Added status field
#         "input1_id": str(input1_id),
#         "input2_id": str(input2_id) if input2_id else None,
#         "output_id": str(out_id),
#         "prompt": prompt,
#         "user_email": user.get("email"),  # βœ… FIXED: Changed from "user" to "user_email"
#         "response_time_ms": response_time_ms  # βœ… FIXED: Added response_time_ms field
#     })

#     return JSONResponse({
#         "output_image_id": str(out_id),
#         "user": user.get("email"),
#         "response_time_ms": response_time_ms
#     })



@app.get("/image/{image_id}")
def get_image(image_id: str, download: Optional[bool] = False):
    """Retrieve stored image by ID (no authentication required)."""
    try:
        oid = ObjectId(image_id)
        grid_out = fs.get(oid)
    except Exception:
        raise HTTPException(status_code=404, detail="Image not found")

    def iterfile():
        yield grid_out.read()

    headers = {}
    if download:
        headers["Content-Disposition"] = f'attachment; filename="{grid_out.filename}"'

    return StreamingResponse(
        iterfile(),
        media_type=grid_out.content_type or "application/octet-stream",
        headers=headers
    )


# ---------------------------------------------------------------------
# Run locally
# ---------------------------------------------------------------------
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)