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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -14
app.py CHANGED
@@ -117,17 +117,20 @@ def health():
117
  mongo.admin.command("ping")
118
  return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
119
 
120
-
121
  @app.post("/generate")
122
  async def generate(
123
  prompt: str = Form(...),
124
  image1: UploadFile = File(...),
125
  image2: Optional[UploadFile] = File(None),
 
 
126
  user=Depends(verify_firebase_token)
127
  ):
128
  start_time = time.time()
129
 
130
- # PREPARE IMAGE(S)
 
 
131
  try:
132
  img1_bytes = await image1.read()
133
  pil_img1 = prepare_image(img1_bytes)
@@ -138,7 +141,7 @@ async def generate(
138
  metadata={"role": "input"}
139
  )
140
  except Exception as e:
141
- raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")
142
 
143
  img2_bytes = None
144
  input2_id = None
@@ -155,9 +158,11 @@ async def generate(
155
  metadata={"role": "input"}
156
  )
157
  except Exception as e:
158
- raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")
159
 
160
- # COMBINE IF NEEDED
 
 
161
  if pil_img2:
162
  total_width = pil_img1.width + pil_img2.width
163
  max_height = max(pil_img1.height, pil_img2.height)
@@ -167,7 +172,65 @@ async def generate(
167
  else:
168
  combined_img = pil_img1
169
 
170
- # INFERENCE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  try:
172
  pil_output = hf_client.image_to_image(
173
  image=combined_img,
@@ -175,7 +238,6 @@ async def generate(
175
  model="Qwen/Qwen-Image-Edit"
176
  )
177
  except Exception as e:
178
- # LOG FAILURE
179
  response_time_ms = round((time.time() - start_time) * 1000)
180
  logs_collection.insert_one({
181
  "timestamp": datetime.utcnow(),
@@ -187,9 +249,11 @@ async def generate(
187
  "error": str(e),
188
  "response_time_ms": response_time_ms
189
  })
190
- raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
191
 
192
- # SAVE OUTPUT IMAGE
 
 
193
  out_buf = io.BytesIO()
194
  pil_output.save(out_buf, format="PNG")
195
  out_bytes = out_buf.getvalue()
@@ -207,19 +271,20 @@ async def generate(
207
  }
208
  )
209
 
210
- # FINAL RESPONSE TIME
211
  response_time_ms = round((time.time() - start_time) * 1000)
212
 
213
- # LOG SUCCESS - THIS WAS MISSING THE STATUS AND RESPONSE_TIME_MS FIELDS!
 
 
214
  logs_collection.insert_one({
215
  "timestamp": datetime.utcnow(),
216
- "status": "success", # ✅ FIXED: Added status field
217
  "input1_id": str(input1_id),
218
  "input2_id": str(input2_id) if input2_id else None,
219
  "output_id": str(out_id),
220
  "prompt": prompt,
221
- "user_email": user.get("email"), # ✅ FIXED: Changed from "user" to "user_email"
222
- "response_time_ms": response_time_ms # ✅ FIXED: Added response_time_ms field
223
  })
224
 
225
  return JSONResponse({
@@ -228,6 +293,116 @@ async def generate(
228
  "response_time_ms": response_time_ms
229
  })
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
 
233
  @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}")