LogicGoInfotechSpaces commited on
Commit
26ea417
·
verified ·
1 Parent(s): 4016953

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -65
app.py CHANGED
@@ -161,31 +161,23 @@ async def log_faceswap_hit(user_email: str, status: str, start_time: datetime, e
161
  "response_time_ms": response_time_ms
162
  })
163
 
 
164
  # --------------------- Media Click Logging Helper ---------------------
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(
182
- "Category ID %s not found. Skipping media click logging.",
183
- category_oid_str
184
- )
185
- return
186
 
187
  # -------------------------------------------------
188
- # STEP 1: Ensure user document + root fields exist
189
  # -------------------------------------------------
190
  await media_clicks_col.update_one(
191
  {"userId": user_oid},
@@ -201,55 +193,56 @@ async def log_media_click(user_id: str, category_oid_str: str):
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
  daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
211
- daily_updates = []
212
-
213
- if not daily_entries:
214
- # First-ever usage → only today
215
- daily_updates.append({"date": today_date, "count": 1})
216
- else:
217
- # Build existing date map for lookup
218
- existing_dates = {entry["date"].date(): entry["count"] for entry in daily_entries}
219
- last_date_in_db = max(entry["date"].date() for entry in daily_entries)
220
-
221
- # Fill missing days between last recorded day and today-1
222
- next_day = last_date_in_db + timedelta(days=1)
223
- while next_day < today_date:
224
- if next_day not in existing_dates:
225
- daily_updates.append({"date": next_day, "count": 0})
226
- next_day += timedelta(days=1)
227
-
228
- # Add today if not already present
229
- if today_date not in existing_dates:
230
- daily_updates.append({"date": today_date, "count": 1})
231
-
232
- # Push updates if any
233
- if daily_updates:
234
- await media_clicks_col.update_one(
235
- {"userId": user_oid},
236
- {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
237
- )
238
-
239
- # Sort oldest → newest and trim to last 32 entries
240
- doc = await media_clicks_col.find_one({"userId": user_oid}, {"ai_edit_daily_count": 1})
241
- daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
242
- daily_entries.sort(key=lambda x: x["date"])
243
- if len(daily_entries) > 32:
244
- daily_entries = daily_entries[-32:]
245
- await media_clicks_col.update_one(
246
- {"userId": user_oid},
247
- {"$set": {"ai_edit_daily_count": daily_entries}}
248
- )
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
 
251
  # -------------------------------------------------
252
- # STEP 2: Try updating existing category
253
  # -------------------------------------------------
254
  update_result = await media_clicks_col.update_one(
255
  {
@@ -263,26 +256,20 @@ async def log_media_click(user_id: str, category_oid_str: str):
263
  },
264
  "$set": {
265
  "categories.$.lastClickedAt": now,
266
- "ai_edit_last_date": now,
267
  "updatedAt": now
268
  }
269
  }
270
  )
271
 
272
  # -------------------------------------------------
273
- # STEP 3: Category not present push new
274
  # -------------------------------------------------
275
  if update_result.matched_count == 0:
276
  await media_clicks_col.update_one(
277
  {"userId": user_oid},
278
  {
279
- "$inc": {
280
- "ai_edit_complete": 1
281
- },
282
- "$set": {
283
- "ai_edit_last_date": now,
284
- "updatedAt": now
285
- },
286
  "$push": {
287
  "categories": {
288
  "categoryId": category_oid,
@@ -294,23 +281,28 @@ async def log_media_click(user_id: str, category_oid_str: str):
294
  )
295
 
296
  logger.info(
297
- "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented & daily_tracked",
298
  user_id,
299
  category_oid_str
300
  )
301
 
302
  except Exception as media_err:
303
  logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)
 
304
  # async def log_media_click(user_id: str, category_oid_str: str):
305
  # """
306
  # Logs a click event to the media_clicks collection against the Category.
307
- # Safely updates ai_edit_last_date and ai_edit_complete at ROOT level.
308
  # """
309
  # try:
310
  # user_oid = ObjectId(user_id.strip())
311
  # category_oid = ObjectId(category_oid_str.strip())
312
  # now = datetime.utcnow()
313
 
 
 
 
 
314
  # # Optional safety check
315
  # if not await categories_col.find_one({"_id": category_oid}):
316
  # logger.warning(
@@ -328,12 +320,61 @@ async def log_media_click(user_id: str, category_oid_str: str):
328
  # "$setOnInsert": {
329
  # "userId": user_oid,
330
  # "createdAt": now,
331
- # "ai_edit_complete": 0
 
332
  # }
333
  # },
334
  # upsert=True
335
  # )
336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  # # -------------------------------------------------
338
  # # STEP 2: Try updating existing category
339
  # # -------------------------------------------------
@@ -380,7 +421,7 @@ async def log_media_click(user_id: str, category_oid_str: str):
380
  # )
381
 
382
  # logger.info(
383
- # "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented",
384
  # user_id,
385
  # category_oid_str
386
  # )
 
161
  "response_time_ms": response_time_ms
162
  })
163
 
164
+ # --------------------- Media Click Logging Helper ---------------------
165
  # --------------------- Media Click Logging Helper ---------------------
166
  async def log_media_click(user_id: str, category_oid_str: str):
167
  """
168
  Logs a click event to the media_clicks collection against the Category.
169
+ ai_edit_daily_count is binary per day (no duplicate dates).
170
  """
171
  try:
172
  user_oid = ObjectId(user_id.strip())
173
  category_oid = ObjectId(category_oid_str.strip())
174
  now = datetime.utcnow()
175
 
176
+ # Normalize today (UTC midnight)
177
  today_date = datetime(now.year, now.month, now.day)
 
 
 
 
 
 
 
 
 
178
 
179
  # -------------------------------------------------
180
+ # STEP 1: Ensure root document exists
181
  # -------------------------------------------------
182
  await media_clicks_col.update_one(
183
  {"userId": user_oid},
 
193
  )
194
 
195
  # -------------------------------------------------
196
+ # STEP 2: FIXED DAILY BINARY TRACKING
197
  # -------------------------------------------------
198
  doc = await media_clicks_col.find_one(
199
  {"userId": user_oid},
200
  {"ai_edit_daily_count": 1}
201
  )
202
+
203
  daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
+ # Convert to date -> count map (unique by design)
206
+ daily_map = {
207
+ entry["date"]: entry["count"]
208
+ for entry in daily_entries
209
+ }
210
+
211
+ # Determine last recorded date
212
+ last_date = max(daily_map.keys()) if daily_map else today_date
213
+
214
+ # Fill ALL missing days with 0
215
+ next_day = last_date + timedelta(days=1)
216
+ while next_day < today_date:
217
+ daily_map.setdefault(next_day, 0)
218
+ next_day += timedelta(days=1)
219
+
220
+ # Mark today as used (binary)
221
+ daily_map[today_date] = 1
222
+
223
+ # Rebuild sorted list (old → new)
224
+ final_daily_entries = [
225
+ {"date": d, "count": daily_map[d]}
226
+ for d in sorted(daily_map.keys())
227
+ ]
228
+
229
+ # Keep last 32 days only
230
+ final_daily_entries = final_daily_entries[-32:]
231
+
232
+ # Atomic replace (NO $push)
233
+ await media_clicks_col.update_one(
234
+ {"userId": user_oid},
235
+ {
236
+ "$set": {
237
+ "ai_edit_daily_count": final_daily_entries,
238
+ "ai_edit_last_date": now,
239
+ "updatedAt": now
240
+ }
241
+ }
242
+ )
243
 
244
  # -------------------------------------------------
245
+ # STEP 3: CATEGORY CLICK LOGIC (DATES CAN REPEAT)
246
  # -------------------------------------------------
247
  update_result = await media_clicks_col.update_one(
248
  {
 
256
  },
257
  "$set": {
258
  "categories.$.lastClickedAt": now,
 
259
  "updatedAt": now
260
  }
261
  }
262
  )
263
 
264
  # -------------------------------------------------
265
+ # STEP 4: Push category if missing (order = time)
266
  # -------------------------------------------------
267
  if update_result.matched_count == 0:
268
  await media_clicks_col.update_one(
269
  {"userId": user_oid},
270
  {
271
+ "$inc": {"ai_edit_complete": 1},
272
+ "$set": {"updatedAt": now},
 
 
 
 
 
273
  "$push": {
274
  "categories": {
275
  "categoryId": category_oid,
 
281
  )
282
 
283
  logger.info(
284
+ "[MEDIA_CLICK] user=%s category=%s daily_binary_tracked",
285
  user_id,
286
  category_oid_str
287
  )
288
 
289
  except Exception as media_err:
290
  logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)
291
+
292
  # async def log_media_click(user_id: str, category_oid_str: str):
293
  # """
294
  # Logs a click event to the media_clicks collection against the Category.
295
+ # Safely updates ai_edit_last_date, ai_edit_complete, and ai_edit_daily_count.
296
  # """
297
  # try:
298
  # user_oid = ObjectId(user_id.strip())
299
  # category_oid = ObjectId(category_oid_str.strip())
300
  # now = datetime.utcnow()
301
 
302
+ # # Normalize dates (UTC midnight)
303
+ # today_date = datetime(now.year, now.month, now.day)
304
+ # yesterday_date = today_date - timedelta(days=1)
305
+
306
  # # Optional safety check
307
  # if not await categories_col.find_one({"_id": category_oid}):
308
  # logger.warning(
 
320
  # "$setOnInsert": {
321
  # "userId": user_oid,
322
  # "createdAt": now,
323
+ # "ai_edit_complete": 0,
324
+ # "ai_edit_daily_count": []
325
  # }
326
  # },
327
  # upsert=True
328
  # )
329
 
330
+ # # -------------------------------------------------
331
+ # # STEP 1.5: Handle ai_edit_daily_count
332
+ # # -------------------------------------------------
333
+ # doc = await media_clicks_col.find_one(
334
+ # {"userId": user_oid},
335
+ # {"ai_edit_daily_count": 1}
336
+ # )
337
+ # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
338
+ # daily_updates = []
339
+
340
+ # if not daily_entries:
341
+ # # First-ever usage → only today
342
+ # daily_updates.append({"date": today_date, "count": 1})
343
+ # else:
344
+ # # Build existing date map for lookup
345
+ # existing_dates = {entry["date"].date(): entry["count"] for entry in daily_entries}
346
+ # last_date_in_db = max(entry["date"].date() for entry in daily_entries)
347
+
348
+ # # Fill missing days between last recorded day and today-1
349
+ # next_day = last_date_in_db + timedelta(days=1)
350
+ # while next_day < today_date:
351
+ # if next_day not in existing_dates:
352
+ # daily_updates.append({"date": next_day, "count": 0})
353
+ # next_day += timedelta(days=1)
354
+
355
+ # # Add today if not already present
356
+ # if today_date not in existing_dates:
357
+ # daily_updates.append({"date": today_date, "count": 1})
358
+
359
+ # # Push updates if any
360
+ # if daily_updates:
361
+ # await media_clicks_col.update_one(
362
+ # {"userId": user_oid},
363
+ # {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
364
+ # )
365
+
366
+ # # Sort oldest → newest and trim to last 32 entries
367
+ # doc = await media_clicks_col.find_one({"userId": user_oid}, {"ai_edit_daily_count": 1})
368
+ # daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
369
+ # daily_entries.sort(key=lambda x: x["date"])
370
+ # if len(daily_entries) > 32:
371
+ # daily_entries = daily_entries[-32:]
372
+ # await media_clicks_col.update_one(
373
+ # {"userId": user_oid},
374
+ # {"$set": {"ai_edit_daily_count": daily_entries}}
375
+ # )
376
+
377
+
378
  # # -------------------------------------------------
379
  # # STEP 2: Try updating existing category
380
  # # -------------------------------------------------
 
421
  # )
422
 
423
  # logger.info(
424
+ # "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented & daily_tracked",
425
  # user_id,
426
  # category_oid_str
427
  # )