LogicGoInfotechSpaces commited on
Commit
5df6f28
·
verified ·
1 Parent(s): c12b71c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -22
app.py CHANGED
@@ -8,7 +8,7 @@ import numpy as np
8
  import threading
9
  import subprocess
10
  import logging
11
- from datetime import datetime, timezone
12
  import insightface
13
  from insightface.app import FaceAnalysis
14
  from huggingface_hub import hf_hub_download
@@ -165,13 +165,17 @@ async def log_faceswap_hit(user_email: str, status: str, start_time: datetime, e
165
  async def log_media_click(user_id: str, category_oid_str: str):
166
  """
167
  Logs a click event to the media_clicks collection against the Category.
168
- Safely updates ai_edit_last_date and ai_edit_complete at ROOT level.
169
  """
170
  try:
171
  user_oid = ObjectId(user_id.strip())
172
  category_oid = ObjectId(category_oid_str.strip())
173
  now = datetime.utcnow()
174
 
 
 
 
 
175
  # Optional safety check
176
  if not await categories_col.find_one({"_id": category_oid}):
177
  logger.warning(
@@ -189,12 +193,44 @@ async def log_media_click(user_id: str, category_oid_str: str):
189
  "$setOnInsert": {
190
  "userId": user_oid,
191
  "createdAt": now,
192
- "ai_edit_complete": 0
 
193
  }
194
  },
195
  upsert=True
196
  )
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  # -------------------------------------------------
199
  # STEP 2: Try updating existing category
200
  # -------------------------------------------------
@@ -241,52 +277,81 @@ async def log_media_click(user_id: str, category_oid_str: str):
241
  )
242
 
243
  logger.info(
244
- "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented",
245
  user_id,
246
  category_oid_str
247
  )
248
 
249
  except Exception as media_err:
250
  logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)
251
-
252
  # async def log_media_click(user_id: str, category_oid_str: str):
253
  # """
254
  # Logs a click event to the media_clicks collection against the Category.
 
255
  # """
256
  # try:
257
  # user_oid = ObjectId(user_id.strip())
258
  # category_oid = ObjectId(category_oid_str.strip())
259
  # now = datetime.utcnow()
260
 
261
- # # Check if category exists (optional, but prevents logging invalid IDs)
262
  # if not await categories_col.find_one({"_id": category_oid}):
263
- # logger.warning(f"Category ID {category_oid_str} not found. Skipping click logging.")
 
 
 
264
  # return
265
 
266
- # # 1) Try updating existing category click entry
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  # update_result = await media_clicks_col.update_one(
268
  # {
269
  # "userId": user_oid,
270
  # "categories.categoryId": category_oid
271
  # },
272
  # {
273
- # "$set": {
274
- # "updatedAt": now,
275
- # "categories.$.lastClickedAt": now
276
- # },
277
  # "$inc": {
278
- # "categories.$.click_count": 1
 
 
 
 
 
 
279
  # }
280
  # }
281
  # )
282
 
283
- # # 2) If no category entry exists → push new one (or create doc)
 
 
284
  # if update_result.matched_count == 0:
285
  # await media_clicks_col.update_one(
286
- # { "userId": user_oid },
287
  # {
288
- # "$setOnInsert": { "createdAt": now },
289
- # "$set": { "updatedAt": now },
 
 
 
 
 
290
  # "$push": {
291
  # "categories": {
292
  # "categoryId": category_oid,
@@ -294,14 +359,18 @@ async def log_media_click(user_id: str, category_oid_str: str):
294
  # "lastClickedAt": now
295
  # }
296
  # }
297
- # },
298
- # upsert=True
299
  # )
300
-
301
- # logger.info(f"Media click logged for User {user_id} on Category {category_oid_str}")
 
 
 
 
302
 
303
  # except Exception as media_err:
304
- # logger.error(f"MEDIA_CLICK LOGGING ERROR: {media_err}")
 
305
 
306
  # --------------------- Face Swap Pipeline ---------------------
307
  swap_lock = threading.Lock()
 
8
  import threading
9
  import subprocess
10
  import logging
11
+ from datetime import datetime, timezone,timedelta
12
  import insightface
13
  from insightface.app import FaceAnalysis
14
  from huggingface_hub import hf_hub_download
 
165
  async def log_media_click(user_id: str, category_oid_str: str):
166
  """
167
  Logs a click event to the media_clicks collection against the Category.
168
+ Safely updates ai_edit_last_date, ai_edit_complete, and ai_edit_daily_count.
169
  """
170
  try:
171
  user_oid = ObjectId(user_id.strip())
172
  category_oid = ObjectId(category_oid_str.strip())
173
  now = datetime.utcnow()
174
 
175
+ # Normalize dates (UTC midnight)
176
+ today_date = datetime(now.year, now.month, now.day)
177
+ yesterday_date = today_date - timedelta(days=1)
178
+
179
  # Optional safety check
180
  if not await categories_col.find_one({"_id": category_oid}):
181
  logger.warning(
 
193
  "$setOnInsert": {
194
  "userId": user_oid,
195
  "createdAt": now,
196
+ "ai_edit_complete": 0,
197
+ "ai_edit_daily_count": []
198
  }
199
  },
200
  upsert=True
201
  )
202
 
203
+ # -------------------------------------------------
204
+ # STEP 1.5: Handle ai_edit_daily_count
205
+ # -------------------------------------------------
206
+ doc = await media_clicks_col.find_one(
207
+ {"userId": user_oid},
208
+ {"ai_edit_daily_count": 1}
209
+ )
210
+
211
+ daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
212
+ is_first_time = len(daily_entries) == 0
213
+
214
+ existing_dates = {entry["date"].date(): entry["count"] for entry in daily_entries}
215
+ daily_updates = []
216
+
217
+ if is_first_time:
218
+ # First ever usage → only today
219
+ daily_updates.append({"date": today_date, "count": 1})
220
+ else:
221
+ # Backfill yesterday if missing
222
+ if yesterday_date.date() not in existing_dates:
223
+ daily_updates.append({"date": yesterday_date, "count": 0})
224
+ # Insert today if missing
225
+ if today_date.date() not in existing_dates:
226
+ daily_updates.append({"date": today_date, "count": 1})
227
+
228
+ if daily_updates:
229
+ await media_clicks_col.update_one(
230
+ {"userId": user_oid},
231
+ {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
232
+ )
233
+
234
  # -------------------------------------------------
235
  # STEP 2: Try updating existing category
236
  # -------------------------------------------------
 
277
  )
278
 
279
  logger.info(
280
+ "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented & daily_tracked",
281
  user_id,
282
  category_oid_str
283
  )
284
 
285
  except Exception as media_err:
286
  logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)
 
287
  # async def log_media_click(user_id: str, category_oid_str: str):
288
  # """
289
  # Logs a click event to the media_clicks collection against the Category.
290
+ # Safely updates ai_edit_last_date and ai_edit_complete at ROOT level.
291
  # """
292
  # try:
293
  # user_oid = ObjectId(user_id.strip())
294
  # category_oid = ObjectId(category_oid_str.strip())
295
  # now = datetime.utcnow()
296
 
297
+ # # Optional safety check
298
  # if not await categories_col.find_one({"_id": category_oid}):
299
+ # logger.warning(
300
+ # "Category ID %s not found. Skipping media click logging.",
301
+ # category_oid_str
302
+ # )
303
  # return
304
 
305
+ # # -------------------------------------------------
306
+ # # STEP 1: Ensure user document + root fields exist
307
+ # # -------------------------------------------------
308
+ # await media_clicks_col.update_one(
309
+ # {"userId": user_oid},
310
+ # {
311
+ # "$setOnInsert": {
312
+ # "userId": user_oid,
313
+ # "createdAt": now,
314
+ # "ai_edit_complete": 0
315
+ # }
316
+ # },
317
+ # upsert=True
318
+ # )
319
+
320
+ # # -------------------------------------------------
321
+ # # STEP 2: Try updating existing category
322
+ # # -------------------------------------------------
323
  # update_result = await media_clicks_col.update_one(
324
  # {
325
  # "userId": user_oid,
326
  # "categories.categoryId": category_oid
327
  # },
328
  # {
 
 
 
 
329
  # "$inc": {
330
+ # "categories.$.click_count": 1,
331
+ # "ai_edit_complete": 1
332
+ # },
333
+ # "$set": {
334
+ # "categories.$.lastClickedAt": now,
335
+ # "ai_edit_last_date": now,
336
+ # "updatedAt": now
337
  # }
338
  # }
339
  # )
340
 
341
+ # # -------------------------------------------------
342
+ # # STEP 3: Category not present → push new
343
+ # # -------------------------------------------------
344
  # if update_result.matched_count == 0:
345
  # await media_clicks_col.update_one(
346
+ # {"userId": user_oid},
347
  # {
348
+ # "$inc": {
349
+ # "ai_edit_complete": 1
350
+ # },
351
+ # "$set": {
352
+ # "ai_edit_last_date": now,
353
+ # "updatedAt": now
354
+ # },
355
  # "$push": {
356
  # "categories": {
357
  # "categoryId": category_oid,
 
359
  # "lastClickedAt": now
360
  # }
361
  # }
362
+ # }
 
363
  # )
364
+
365
+ # logger.info(
366
+ # "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented",
367
+ # user_id,
368
+ # category_oid_str
369
+ # )
370
 
371
  # except Exception as media_err:
372
+ # logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)
373
+
374
 
375
  # --------------------- Face Swap Pipeline ---------------------
376
  swap_lock = threading.Lock()