LogicGoInfotechSpaces commited on
Commit
92a5960
·
verified ·
1 Parent(s): a9c5030

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -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({
@@ -402,6 +292,117 @@ async def generate(
402
  "user": user.get("email"),
403
  "response_time_ms": response_time_ms
404
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
 
406
 
407
 
 
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({
 
292
  "user": user.get("email"),
293
  "response_time_ms": response_time_ms
294
  })
295
+ ####################---------------------------------------------------------------------------------------------------###
296
+ ###-----OLD CODE--------------####
297
+ # @app.post("/generate")
298
+ # async def generate(
299
+ # prompt: str = Form(...),
300
+ # image1: UploadFile = File(...),
301
+ # image2: Optional[UploadFile] = File(None),
302
+ # user=Depends(verify_firebase_token)
303
+ # ):
304
+ # start_time = time.time()
305
+
306
+ # # PREPARE IMAGE(S)
307
+ # try:
308
+ # img1_bytes = await image1.read()
309
+ # pil_img1 = prepare_image(img1_bytes)
310
+ # input1_id = fs.put(
311
+ # img1_bytes,
312
+ # filename=image1.filename,
313
+ # contentType=image1.content_type,
314
+ # metadata={"role": "input"}
315
+ # )
316
+ # except Exception as e:
317
+ # raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")
318
+
319
+ # img2_bytes = None
320
+ # input2_id = None
321
+ # pil_img2 = None
322
+
323
+ # if image2:
324
+ # try:
325
+ # img2_bytes = await image2.read()
326
+ # pil_img2 = prepare_image(img2_bytes)
327
+ # input2_id = fs.put(
328
+ # img2_bytes,
329
+ # filename=image2.filename,
330
+ # contentType=image2.content_type,
331
+ # metadata={"role": "input"}
332
+ # )
333
+ # except Exception as e:
334
+ # raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")
335
+
336
+ # # COMBINE IF NEEDED
337
+ # if pil_img2:
338
+ # total_width = pil_img1.width + pil_img2.width
339
+ # max_height = max(pil_img1.height, pil_img2.height)
340
+ # combined_img = Image.new("RGB", (total_width, max_height))
341
+ # combined_img.paste(pil_img1, (0, 0))
342
+ # combined_img.paste(pil_img2, (pil_img1.width, 0))
343
+ # else:
344
+ # combined_img = pil_img1
345
+
346
+ # # INFERENCE
347
+ # try:
348
+ # pil_output = hf_client.image_to_image(
349
+ # image=combined_img,
350
+ # prompt=prompt,
351
+ # model="Qwen/Qwen-Image-Edit"
352
+ # )
353
+ # except Exception as e:
354
+ # # LOG FAILURE
355
+ # response_time_ms = round((time.time() - start_time) * 1000)
356
+ # logs_collection.insert_one({
357
+ # "timestamp": datetime.utcnow(),
358
+ # "status": "failure",
359
+ # "input1_id": str(input1_id),
360
+ # "input2_id": str(input2_id) if input2_id else None,
361
+ # "prompt": prompt,
362
+ # "user_email": user.get("email"),
363
+ # "error": str(e),
364
+ # "response_time_ms": response_time_ms
365
+ # })
366
+ # raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
367
+
368
+ # # SAVE OUTPUT IMAGE
369
+ # out_buf = io.BytesIO()
370
+ # pil_output.save(out_buf, format="PNG")
371
+ # out_bytes = out_buf.getvalue()
372
+
373
+ # out_id = fs.put(
374
+ # out_bytes,
375
+ # filename=f"result_{input1_id}.png",
376
+ # contentType="image/png",
377
+ # metadata={
378
+ # "role": "output",
379
+ # "prompt": prompt,
380
+ # "input1_id": str(input1_id),
381
+ # "input2_id": str(input2_id) if input2_id else None,
382
+ # "user_email": user.get("email"),
383
+ # }
384
+ # )
385
+
386
+ # # FINAL RESPONSE TIME
387
+ # response_time_ms = round((time.time() - start_time) * 1000)
388
+
389
+ # # LOG SUCCESS - THIS WAS MISSING THE STATUS AND RESPONSE_TIME_MS FIELDS!
390
+ # logs_collection.insert_one({
391
+ # "timestamp": datetime.utcnow(),
392
+ # "status": "success", # ✅ FIXED: Added status field
393
+ # "input1_id": str(input1_id),
394
+ # "input2_id": str(input2_id) if input2_id else None,
395
+ # "output_id": str(out_id),
396
+ # "prompt": prompt,
397
+ # "user_email": user.get("email"), # ✅ FIXED: Changed from "user" to "user_email"
398
+ # "response_time_ms": response_time_ms # ✅ FIXED: Added response_time_ms field
399
+ # })
400
+
401
+ # return JSONResponse({
402
+ # "output_image_id": str(out_id),
403
+ # "user": user.get("email"),
404
+ # "response_time_ms": response_time_ms
405
+ # })
406
 
407
 
408