LogicGoInfotechSpaces commited on
Commit
a9c5030
·
verified ·
1 Parent(s): 65a53f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -189
app.py CHANGED
@@ -117,192 +117,20 @@ def health():
117
  mongo.admin.command("ping")
118
  return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
119
 
120
- @app.post("/generate")
121
- async def generate(
122
- prompt: str = Form(...),
123
- image1: UploadFile = File(...),
124
- image2: Optional[UploadFile] = File(None),
125
- user_id: Optional[str] = Form(None),
126
- category_id: Optional[str] = Form(None),
127
- user=Depends(verify_firebase_token)
128
- ):
129
- start_time = time.time()
130
-
131
- # -------------------------
132
- # 1. VALIDATE & READ IMAGES
133
- # -------------------------
134
- try:
135
- img1_bytes = await image1.read()
136
- pil_img1 = prepare_image(img1_bytes)
137
- input1_id = fs.put(
138
- img1_bytes,
139
- filename=image1.filename,
140
- contentType=image1.content_type,
141
- metadata={"role": "input"}
142
- )
143
- except Exception as e:
144
- raise HTTPException(400, f"Failed to read first image: {e}")
145
-
146
- img2_bytes = None
147
- input2_id = None
148
- pil_img2 = None
149
-
150
- if image2:
151
- try:
152
- img2_bytes = await image2.read()
153
- pil_img2 = prepare_image(img2_bytes)
154
- input2_id = fs.put(
155
- img2_bytes,
156
- filename=image2.filename,
157
- contentType=image2.content_type,
158
- metadata={"role": "input"}
159
- )
160
- except Exception as e:
161
- raise HTTPException(400, f"Failed to read second image: {e}")
162
-
163
- # -------------------------
164
- # 2. COMBINE IF NEEDED
165
- # -------------------------
166
- if pil_img2:
167
- total_width = pil_img1.width + pil_img2.width
168
- max_height = max(pil_img1.height, pil_img2.height)
169
- combined_img = Image.new("RGB", (total_width, max_height))
170
- combined_img.paste(pil_img1, (0, 0))
171
- combined_img.paste(pil_img2, (pil_img1.width, 0))
172
- else:
173
- combined_img = pil_img1
174
-
175
- # -------------------------
176
- # 3. OPTIONAL CATEGORY CLICK LOGIC
177
- # -------------------------
178
- if user_id and category_id:
179
- try:
180
- admin_client = MongoClient(os.getenv("ADMIN_MONGODB_URI"))
181
- admin_db = admin_client["adminPanel"]
182
-
183
- categories_col = admin_db.categories
184
- media_clicks_col = admin_db.media_clicks
185
-
186
- # Validate user_oid & category_oid
187
- user_oid = ObjectId(user_id)
188
- category_oid = ObjectId(category_id)
189
-
190
- # Check category exists
191
- category_doc = categories_col.find_one({"_id": category_oid})
192
- if not category_doc:
193
- raise HTTPException(400, f"Invalid category_id: {category_id}")
194
-
195
- now = datetime.utcnow()
196
-
197
- # Try updating existing category click
198
- update_res = media_clicks_col.update_one(
199
- {"userId": user_oid, "categories.categoryId": category_oid},
200
- {
201
- "$set": {
202
- "updatedAt": now,
203
- "categories.$.lastClickedAt": now
204
- },
205
- "$inc": {"categories.$.click_count": 1}
206
- }
207
- )
208
-
209
- # If user or category does not exist → create/push new
210
- if update_res.matched_count == 0:
211
- media_clicks_col.update_one(
212
- {"userId": user_oid},
213
- {
214
- "$setOnInsert": {"createdAt": now},
215
- "$set": {"updatedAt": now},
216
- "$push": {
217
- "categories": {
218
- "categoryId": category_oid,
219
- "click_count": 1,
220
- "lastClickedAt": now
221
- }
222
- }
223
- },
224
- upsert=True
225
- )
226
-
227
- except Exception as e:
228
- print("CATEGORY_LOG_ERROR:", e)
229
- # but do NOT stop the image generation
230
-
231
- # -------------------------
232
- # 4. HF INFERENCE
233
- # -------------------------
234
- try:
235
- pil_output = hf_client.image_to_image(
236
- image=combined_img,
237
- prompt=prompt,
238
- model="Qwen/Qwen-Image-Edit"
239
- )
240
- except Exception as e:
241
- response_time_ms = round((time.time() - start_time) * 1000)
242
- logs_collection.insert_one({
243
- "timestamp": datetime.utcnow(),
244
- "status": "failure",
245
- "input1_id": str(input1_id),
246
- "input2_id": str(input2_id) if input2_id else None,
247
- "prompt": prompt,
248
- "user_email": user.get("email"),
249
- "error": str(e),
250
- "response_time_ms": response_time_ms
251
- })
252
- raise HTTPException(500, f"Inference failed: {e}")
253
-
254
- # -------------------------
255
- # 5. SAVE OUTPUT IMAGE
256
- # -------------------------
257
- out_buf = io.BytesIO()
258
- pil_output.save(out_buf, format="PNG")
259
- out_bytes = out_buf.getvalue()
260
-
261
- out_id = fs.put(
262
- out_bytes,
263
- filename=f"result_{input1_id}.png",
264
- contentType="image/png",
265
- metadata={
266
- "role": "output",
267
- "prompt": prompt,
268
- "input1_id": str(input1_id),
269
- "input2_id": str(input2_id) if input2_id else None,
270
- "user_email": user.get("email"),
271
- }
272
- )
273
-
274
- response_time_ms = round((time.time() - start_time) * 1000)
275
-
276
- # -------------------------
277
- # 6. LOG SUCCESS
278
- # -------------------------
279
- logs_collection.insert_one({
280
- "timestamp": datetime.utcnow(),
281
- "status": "success",
282
- "input1_id": str(input1_id),
283
- "input2_id": str(input2_id) if input2_id else None,
284
- "output_id": str(out_id),
285
- "prompt": prompt,
286
- "user_email": user.get("email"),
287
- "response_time_ms": response_time_ms
288
- })
289
-
290
- return JSONResponse({
291
- "output_image_id": str(out_id),
292
- "user": user.get("email"),
293
- "response_time_ms": response_time_ms
294
- })
295
-
296
  # @app.post("/generate")
297
  # async def generate(
298
  # prompt: str = Form(...),
299
  # image1: UploadFile = File(...),
300
  # image2: Optional[UploadFile] = File(None),
 
 
301
  # user=Depends(verify_firebase_token)
302
  # ):
303
  # start_time = time.time()
304
 
305
- # # PREPARE IMAGE(S)
 
 
306
  # try:
307
  # img1_bytes = await image1.read()
308
  # pil_img1 = prepare_image(img1_bytes)
@@ -313,7 +141,7 @@ async def generate(
313
  # metadata={"role": "input"}
314
  # )
315
  # except Exception as e:
316
- # raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")
317
 
318
  # img2_bytes = None
319
  # input2_id = None
@@ -330,9 +158,11 @@ async def generate(
330
  # metadata={"role": "input"}
331
  # )
332
  # except Exception as e:
333
- # raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")
334
 
335
- # # COMBINE IF NEEDED
 
 
336
  # if pil_img2:
337
  # total_width = pil_img1.width + pil_img2.width
338
  # max_height = max(pil_img1.height, pil_img2.height)
@@ -342,7 +172,65 @@ async def generate(
342
  # else:
343
  # combined_img = pil_img1
344
 
345
- # # INFERENCE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  # try:
347
  # pil_output = hf_client.image_to_image(
348
  # image=combined_img,
@@ -350,7 +238,6 @@ async def generate(
350
  # model="Qwen/Qwen-Image-Edit"
351
  # )
352
  # except Exception as e:
353
- # # LOG FAILURE
354
  # response_time_ms = round((time.time() - start_time) * 1000)
355
  # logs_collection.insert_one({
356
  # "timestamp": datetime.utcnow(),
@@ -362,9 +249,11 @@ async def generate(
362
  # "error": str(e),
363
  # "response_time_ms": response_time_ms
364
  # })
365
- # raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
366
 
367
- # # SAVE OUTPUT IMAGE
 
 
368
  # out_buf = io.BytesIO()
369
  # pil_output.save(out_buf, format="PNG")
370
  # out_bytes = out_buf.getvalue()
@@ -382,19 +271,20 @@ async def generate(
382
  # }
383
  # )
384
 
385
- # # FINAL RESPONSE TIME
386
  # response_time_ms = round((time.time() - start_time) * 1000)
387
 
388
- # # LOG SUCCESS - THIS WAS MISSING THE STATUS AND RESPONSE_TIME_MS FIELDS!
 
 
389
  # logs_collection.insert_one({
390
  # "timestamp": datetime.utcnow(),
391
- # "status": "success", # ✅ FIXED: Added status field
392
  # "input1_id": str(input1_id),
393
  # "input2_id": str(input2_id) if input2_id else None,
394
  # "output_id": str(out_id),
395
  # "prompt": prompt,
396
- # "user_email": user.get("email"), # ✅ FIXED: Changed from "user" to "user_email"
397
- # "response_time_ms": response_time_ms # ✅ FIXED: Added response_time_ms field
398
  # })
399
 
400
  # return JSONResponse({
@@ -403,6 +293,116 @@ async def generate(
403
  # "response_time_ms": response_time_ms
404
  # })
405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
407
 
408
  @app.get("/image/{image_id}")
 
117
  mongo.admin.command("ping")
118
  return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  # @app.post("/generate")
121
  # async def generate(
122
  # prompt: str = Form(...),
123
  # image1: UploadFile = File(...),
124
  # image2: Optional[UploadFile] = File(None),
125
+ # user_id: Optional[str] = Form(None),
126
+ # category_id: Optional[str] = Form(None),
127
  # user=Depends(verify_firebase_token)
128
  # ):
129
  # start_time = time.time()
130
 
131
+ # # -------------------------
132
+ # # 1. VALIDATE & READ IMAGES
133
+ # # -------------------------
134
  # try:
135
  # img1_bytes = await image1.read()
136
  # pil_img1 = prepare_image(img1_bytes)
 
141
  # metadata={"role": "input"}
142
  # )
143
  # except Exception as e:
144
+ # raise HTTPException(400, f"Failed to read first image: {e}")
145
 
146
  # img2_bytes = None
147
  # input2_id = None
 
158
  # metadata={"role": "input"}
159
  # )
160
  # except Exception as e:
161
+ # raise HTTPException(400, f"Failed to read second image: {e}")
162
 
163
+ # # -------------------------
164
+ # # 2. COMBINE IF NEEDED
165
+ # # -------------------------
166
  # if pil_img2:
167
  # total_width = pil_img1.width + pil_img2.width
168
  # max_height = max(pil_img1.height, pil_img2.height)
 
172
  # else:
173
  # combined_img = pil_img1
174
 
175
+ # # -------------------------
176
+ # # 3. OPTIONAL CATEGORY CLICK LOGIC
177
+ # # -------------------------
178
+ # if user_id and category_id:
179
+ # try:
180
+ # admin_client = MongoClient(os.getenv("ADMIN_MONGODB_URI"))
181
+ # admin_db = admin_client["adminPanel"]
182
+
183
+ # categories_col = admin_db.categories
184
+ # media_clicks_col = admin_db.media_clicks
185
+
186
+ # # Validate user_oid & category_oid
187
+ # user_oid = ObjectId(user_id)
188
+ # category_oid = ObjectId(category_id)
189
+
190
+ # # Check category exists
191
+ # category_doc = categories_col.find_one({"_id": category_oid})
192
+ # if not category_doc:
193
+ # raise HTTPException(400, f"Invalid category_id: {category_id}")
194
+
195
+ # now = datetime.utcnow()
196
+
197
+ # # Try updating existing category click
198
+ # update_res = media_clicks_col.update_one(
199
+ # {"userId": user_oid, "categories.categoryId": category_oid},
200
+ # {
201
+ # "$set": {
202
+ # "updatedAt": now,
203
+ # "categories.$.lastClickedAt": now
204
+ # },
205
+ # "$inc": {"categories.$.click_count": 1}
206
+ # }
207
+ # )
208
+
209
+ # # If user or category does not exist → create/push new
210
+ # if update_res.matched_count == 0:
211
+ # media_clicks_col.update_one(
212
+ # {"userId": user_oid},
213
+ # {
214
+ # "$setOnInsert": {"createdAt": now},
215
+ # "$set": {"updatedAt": now},
216
+ # "$push": {
217
+ # "categories": {
218
+ # "categoryId": category_oid,
219
+ # "click_count": 1,
220
+ # "lastClickedAt": now
221
+ # }
222
+ # }
223
+ # },
224
+ # upsert=True
225
+ # )
226
+
227
+ # except Exception as e:
228
+ # print("CATEGORY_LOG_ERROR:", e)
229
+ # # but do NOT stop the image generation
230
+
231
+ # # -------------------------
232
+ # # 4. HF INFERENCE
233
+ # # -------------------------
234
  # try:
235
  # pil_output = hf_client.image_to_image(
236
  # image=combined_img,
 
238
  # model="Qwen/Qwen-Image-Edit"
239
  # )
240
  # except Exception as e:
 
241
  # response_time_ms = round((time.time() - start_time) * 1000)
242
  # logs_collection.insert_one({
243
  # "timestamp": datetime.utcnow(),
 
249
  # "error": str(e),
250
  # "response_time_ms": response_time_ms
251
  # })
252
+ # raise HTTPException(500, f"Inference failed: {e}")
253
 
254
+ # # -------------------------
255
+ # # 5. SAVE OUTPUT IMAGE
256
+ # # -------------------------
257
  # out_buf = io.BytesIO()
258
  # pil_output.save(out_buf, format="PNG")
259
  # out_bytes = out_buf.getvalue()
 
271
  # }
272
  # )
273
 
 
274
  # response_time_ms = round((time.time() - start_time) * 1000)
275
 
276
+ # # -------------------------
277
+ # # 6. LOG SUCCESS
278
+ # # -------------------------
279
  # logs_collection.insert_one({
280
  # "timestamp": datetime.utcnow(),
281
+ # "status": "success",
282
  # "input1_id": str(input1_id),
283
  # "input2_id": str(input2_id) if input2_id else None,
284
  # "output_id": str(out_id),
285
  # "prompt": prompt,
286
+ # "user_email": user.get("email"),
287
+ # "response_time_ms": response_time_ms
288
  # })
289
 
290
  # return JSONResponse({
 
293
  # "response_time_ms": response_time_ms
294
  # })
295
 
296
+ @app.post("/generate")
297
+ async def generate(
298
+ prompt: str = Form(...),
299
+ image1: UploadFile = File(...),
300
+ image2: Optional[UploadFile] = File(None),
301
+ user=Depends(verify_firebase_token)
302
+ ):
303
+ start_time = time.time()
304
+
305
+ # PREPARE IMAGE(S)
306
+ try:
307
+ img1_bytes = await image1.read()
308
+ pil_img1 = prepare_image(img1_bytes)
309
+ input1_id = fs.put(
310
+ img1_bytes,
311
+ filename=image1.filename,
312
+ contentType=image1.content_type,
313
+ metadata={"role": "input"}
314
+ )
315
+ except Exception as e:
316
+ raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")
317
+
318
+ img2_bytes = None
319
+ input2_id = None
320
+ pil_img2 = None
321
+
322
+ if image2:
323
+ try:
324
+ img2_bytes = await image2.read()
325
+ pil_img2 = prepare_image(img2_bytes)
326
+ input2_id = fs.put(
327
+ img2_bytes,
328
+ filename=image2.filename,
329
+ contentType=image2.content_type,
330
+ metadata={"role": "input"}
331
+ )
332
+ except Exception as e:
333
+ raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")
334
+
335
+ # COMBINE IF NEEDED
336
+ if pil_img2:
337
+ total_width = pil_img1.width + pil_img2.width
338
+ max_height = max(pil_img1.height, pil_img2.height)
339
+ combined_img = Image.new("RGB", (total_width, max_height))
340
+ combined_img.paste(pil_img1, (0, 0))
341
+ combined_img.paste(pil_img2, (pil_img1.width, 0))
342
+ else:
343
+ combined_img = pil_img1
344
+
345
+ # INFERENCE
346
+ try:
347
+ pil_output = hf_client.image_to_image(
348
+ image=combined_img,
349
+ prompt=prompt,
350
+ model="Qwen/Qwen-Image-Edit"
351
+ )
352
+ except Exception as e:
353
+ # LOG FAILURE
354
+ response_time_ms = round((time.time() - start_time) * 1000)
355
+ logs_collection.insert_one({
356
+ "timestamp": datetime.utcnow(),
357
+ "status": "failure",
358
+ "input1_id": str(input1_id),
359
+ "input2_id": str(input2_id) if input2_id else None,
360
+ "prompt": prompt,
361
+ "user_email": user.get("email"),
362
+ "error": str(e),
363
+ "response_time_ms": response_time_ms
364
+ })
365
+ raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
366
+
367
+ # SAVE OUTPUT IMAGE
368
+ out_buf = io.BytesIO()
369
+ pil_output.save(out_buf, format="PNG")
370
+ out_bytes = out_buf.getvalue()
371
+
372
+ out_id = fs.put(
373
+ out_bytes,
374
+ filename=f"result_{input1_id}.png",
375
+ contentType="image/png",
376
+ metadata={
377
+ "role": "output",
378
+ "prompt": prompt,
379
+ "input1_id": str(input1_id),
380
+ "input2_id": str(input2_id) if input2_id else None,
381
+ "user_email": user.get("email"),
382
+ }
383
+ )
384
+
385
+ # FINAL RESPONSE TIME
386
+ response_time_ms = round((time.time() - start_time) * 1000)
387
+
388
+ # LOG SUCCESS - THIS WAS MISSING THE STATUS AND RESPONSE_TIME_MS FIELDS!
389
+ logs_collection.insert_one({
390
+ "timestamp": datetime.utcnow(),
391
+ "status": "success", # ✅ FIXED: Added status field
392
+ "input1_id": str(input1_id),
393
+ "input2_id": str(input2_id) if input2_id else None,
394
+ "output_id": str(out_id),
395
+ "prompt": prompt,
396
+ "user_email": user.get("email"), # ✅ FIXED: Changed from "user" to "user_email"
397
+ "response_time_ms": response_time_ms # ✅ FIXED: Added response_time_ms field
398
+ })
399
+
400
+ return JSONResponse({
401
+ "output_image_id": str(out_id),
402
+ "user": user.get("email"),
403
+ "response_time_ms": response_time_ms
404
+ })
405
+
406
 
407
 
408
  @app.get("/image/{image_id}")