Spaces:
Running
on
T4
Running
on
T4
Update app.py
Browse files
app.py
CHANGED
|
@@ -147,6 +147,14 @@ MONGODB_URL = os.getenv("MONGODB_URL")
|
|
| 147 |
client = None
|
| 148 |
database = None
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
# --------------------- FastAPI ---------------------
|
| 151 |
fastapi_app = FastAPI()
|
| 152 |
|
|
@@ -285,69 +293,181 @@ async def health():
|
|
| 285 |
async def face_swap_api(
|
| 286 |
source: UploadFile = File(...),
|
| 287 |
target_category_id: str = Form(...),
|
|
|
|
|
|
|
| 288 |
user_email: str = Depends(verify_firebase_token)
|
| 289 |
):
|
| 290 |
-
# start_time = datetime.utcnow()
|
| 291 |
start_time = datetime.now(timezone.utc)
|
|
|
|
| 292 |
try:
|
|
|
|
| 293 |
src_bytes = await source.read()
|
| 294 |
src_key = f"bikini-theme/source/{uuid.uuid4().hex}_{source.filename}"
|
| 295 |
upload_to_spaces(src_bytes, src_key, content_type=source.content_type)
|
| 296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
target_filename = f"{target_category_id}.png"
|
| 298 |
target_url = f"https://{DO_SPACES_BUCKET}.{DO_SPACES_REGION}.digitaloceanspaces.com/bikini-theme/target/{target_filename}"
|
| 299 |
|
| 300 |
resp = requests.get(target_url)
|
| 301 |
if resp.status_code != 200:
|
| 302 |
-
# end_time = datetime.utcnow()
|
| 303 |
end_time = datetime.now(timezone.utc)
|
| 304 |
-
await log_faceswap_hit(user_email,
|
| 305 |
-
raise HTTPException(
|
| 306 |
|
| 307 |
tgt_bytes = resp.content
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)
|
| 313 |
|
| 314 |
if src_bgr is None or tgt_bgr is None:
|
| 315 |
-
#end_time = datetime.utcnow()
|
| 316 |
end_time = datetime.now(timezone.utc)
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
raise HTTPException(status_code=400, detail="Invalid image data")
|
| 320 |
|
| 321 |
src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
|
| 322 |
tgt_rgb = cv2.cvtColor(tgt_bgr, cv2.COLOR_BGR2RGB)
|
| 323 |
|
| 324 |
final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
|
| 325 |
if err:
|
| 326 |
-
end_time = datetime.
|
| 327 |
-
await log_faceswap_hit(user_email,
|
| 328 |
-
raise HTTPException(
|
| 329 |
|
| 330 |
with open(final_path, "rb") as f:
|
| 331 |
result_bytes = f.read()
|
|
|
|
| 332 |
result_key = f"bikini-theme/result/{uuid.uuid4().hex}_enhanced.png"
|
| 333 |
-
result_url = upload_to_spaces(result_bytes, result_key,
|
| 334 |
|
| 335 |
-
#end_time = datetime.utcnow()
|
| 336 |
end_time = datetime.now(timezone.utc)
|
| 337 |
-
await log_faceswap_hit(user_email,
|
| 338 |
|
| 339 |
return {"result_url": result_url}
|
| 340 |
|
| 341 |
except Exception as e:
|
| 342 |
-
#end_time = datetime.utcnow()
|
| 343 |
end_time = datetime.now(timezone.utc)
|
| 344 |
-
|
| 345 |
-
# Ensure we log the error with timestamps before raising
|
| 346 |
try:
|
| 347 |
-
await log_faceswap_hit(user_email,
|
| 348 |
-
except
|
| 349 |
-
|
| 350 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
|
| 353 |
@fastapi_app.get("/preview/{result_key:path}")
|
|
|
|
| 147 |
client = None
|
| 148 |
database = None
|
| 149 |
|
| 150 |
+
# --------------------- Admin Panel DB (categories + media_clicks) ---------------------
|
| 151 |
+
ADMIN_MONGO_URL = os.getenv("ADMIN_MONGO_URL")
|
| 152 |
+
admin_client = AsyncIOMotorClient(ADMIN_MONGO_URL)
|
| 153 |
+
admin_db = admin_client.adminPanel
|
| 154 |
+
|
| 155 |
+
categories_col = admin_db.categories
|
| 156 |
+
media_clicks_col = admin_db.media_clicks
|
| 157 |
+
|
| 158 |
# --------------------- FastAPI ---------------------
|
| 159 |
fastapi_app = FastAPI()
|
| 160 |
|
|
|
|
| 293 |
async def face_swap_api(
|
| 294 |
source: UploadFile = File(...),
|
| 295 |
target_category_id: str = Form(...),
|
| 296 |
+
user_id: Optional[str] = Form(None),
|
| 297 |
+
category_id: Optional[str] = Form(None),
|
| 298 |
user_email: str = Depends(verify_firebase_token)
|
| 299 |
):
|
|
|
|
| 300 |
start_time = datetime.now(timezone.utc)
|
| 301 |
+
|
| 302 |
try:
|
| 303 |
+
# READ SOURCE
|
| 304 |
src_bytes = await source.read()
|
| 305 |
src_key = f"bikini-theme/source/{uuid.uuid4().hex}_{source.filename}"
|
| 306 |
upload_to_spaces(src_bytes, src_key, content_type=source.content_type)
|
| 307 |
|
| 308 |
+
# ------------------------------------------------------------------
|
| 309 |
+
# OPTIONAL CATEGORY CLICK LOGGING
|
| 310 |
+
# ------------------------------------------------------------------
|
| 311 |
+
if user_id and category_id:
|
| 312 |
+
try:
|
| 313 |
+
user_oid = ObjectId(user_id)
|
| 314 |
+
category_oid = ObjectId(category_id)
|
| 315 |
+
now = datetime.utcnow()
|
| 316 |
+
|
| 317 |
+
# check category exists
|
| 318 |
+
category_doc = await categories_col.find_one({"_id": category_oid})
|
| 319 |
+
if category_doc:
|
| 320 |
+
update_res = await media_clicks_col.update_one(
|
| 321 |
+
{"userId": user_oid, "categories.categoryId": category_oid},
|
| 322 |
+
{
|
| 323 |
+
"$set": {
|
| 324 |
+
"updatedAt": now,
|
| 325 |
+
"categories.$.lastClickedAt": now
|
| 326 |
+
},
|
| 327 |
+
"$inc": {"categories.$.click_count": 1}
|
| 328 |
+
}
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
if update_res.matched_count == 0:
|
| 332 |
+
await media_clicks_col.update_one(
|
| 333 |
+
{"userId": user_oid},
|
| 334 |
+
{
|
| 335 |
+
"$setOnInsert": {"createdAt": now},
|
| 336 |
+
"$set": {"updatedAt": now},
|
| 337 |
+
"$push": {
|
| 338 |
+
"categories": {
|
| 339 |
+
"categoryId": category_oid,
|
| 340 |
+
"click_count": 1,
|
| 341 |
+
"lastClickedAt": now
|
| 342 |
+
}
|
| 343 |
+
}
|
| 344 |
+
},
|
| 345 |
+
upsert=True
|
| 346 |
+
)
|
| 347 |
+
else:
|
| 348 |
+
logger.error(f"Invalid category_id (not in categories collection): {category_id}")
|
| 349 |
+
|
| 350 |
+
except Exception as log_err:
|
| 351 |
+
logger.error(f"MEDIA_CLICK ERROR: {log_err}")
|
| 352 |
+
|
| 353 |
+
# ------------------------------------------------------------------
|
| 354 |
+
# TARGET IMAGE DOWNLOAD
|
| 355 |
+
# ------------------------------------------------------------------
|
| 356 |
target_filename = f"{target_category_id}.png"
|
| 357 |
target_url = f"https://{DO_SPACES_BUCKET}.{DO_SPACES_REGION}.digitaloceanspaces.com/bikini-theme/target/{target_filename}"
|
| 358 |
|
| 359 |
resp = requests.get(target_url)
|
| 360 |
if resp.status_code != 200:
|
|
|
|
| 361 |
end_time = datetime.now(timezone.utc)
|
| 362 |
+
await log_faceswap_hit(user_email, "error", start_time, end_time)
|
| 363 |
+
raise HTTPException(404, f"Target not found at {target_url}")
|
| 364 |
|
| 365 |
tgt_bytes = resp.content
|
| 366 |
|
| 367 |
+
# FACE SWAP
|
| 368 |
+
src_bgr = cv2.imdecode(np.frombuffer(src_bytes, np.uint8), cv2.IMREAD_COLOR)
|
| 369 |
+
tgt_bgr = cv2.imdecode(np.frombuffer(tgt_bytes, np.uint8), cv2.IMREAD_COLOR)
|
|
|
|
| 370 |
|
| 371 |
if src_bgr is None or tgt_bgr is None:
|
|
|
|
| 372 |
end_time = datetime.now(timezone.utc)
|
| 373 |
+
await log_faceswap_hit(user_email, "error", start_time, end_time)
|
| 374 |
+
raise HTTPException(400, "Invalid image data")
|
|
|
|
| 375 |
|
| 376 |
src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
|
| 377 |
tgt_rgb = cv2.cvtColor(tgt_bgr, cv2.COLOR_BGR2RGB)
|
| 378 |
|
| 379 |
final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
|
| 380 |
if err:
|
| 381 |
+
end_time = datetime.now(timezone.utc)
|
| 382 |
+
await log_faceswap_hit(user_email, "error", start_time, end_time)
|
| 383 |
+
raise HTTPException(500, err)
|
| 384 |
|
| 385 |
with open(final_path, "rb") as f:
|
| 386 |
result_bytes = f.read()
|
| 387 |
+
|
| 388 |
result_key = f"bikini-theme/result/{uuid.uuid4().hex}_enhanced.png"
|
| 389 |
+
result_url = upload_to_spaces(result_bytes, result_key, "image/png")
|
| 390 |
|
|
|
|
| 391 |
end_time = datetime.now(timezone.utc)
|
| 392 |
+
await log_faceswap_hit(user_email, "success", start_time, end_time)
|
| 393 |
|
| 394 |
return {"result_url": result_url}
|
| 395 |
|
| 396 |
except Exception as e:
|
|
|
|
| 397 |
end_time = datetime.now(timezone.utc)
|
|
|
|
|
|
|
| 398 |
try:
|
| 399 |
+
await log_faceswap_hit(user_email, "error", start_time, end_time)
|
| 400 |
+
except:
|
| 401 |
+
pass
|
| 402 |
+
raise HTTPException(500, f"Face swap failed: {e}")
|
| 403 |
+
|
| 404 |
+
# @fastapi_app.post("/face-swap")
|
| 405 |
+
# async def face_swap_api(
|
| 406 |
+
# source: UploadFile = File(...),
|
| 407 |
+
# target_category_id: str = Form(...),
|
| 408 |
+
# user_email: str = Depends(verify_firebase_token)
|
| 409 |
+
# ):
|
| 410 |
+
# # start_time = datetime.utcnow()
|
| 411 |
+
# start_time = datetime.now(timezone.utc)
|
| 412 |
+
# try:
|
| 413 |
+
# src_bytes = await source.read()
|
| 414 |
+
# src_key = f"bikini-theme/source/{uuid.uuid4().hex}_{source.filename}"
|
| 415 |
+
# upload_to_spaces(src_bytes, src_key, content_type=source.content_type)
|
| 416 |
+
|
| 417 |
+
# target_filename = f"{target_category_id}.png"
|
| 418 |
+
# target_url = f"https://{DO_SPACES_BUCKET}.{DO_SPACES_REGION}.digitaloceanspaces.com/bikini-theme/target/{target_filename}"
|
| 419 |
+
|
| 420 |
+
# resp = requests.get(target_url)
|
| 421 |
+
# if resp.status_code != 200:
|
| 422 |
+
# # end_time = datetime.utcnow()
|
| 423 |
+
# end_time = datetime.now(timezone.utc)
|
| 424 |
+
# await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
|
| 425 |
+
# raise HTTPException(status_code=404, detail=f"Target image not found at {target_url}")
|
| 426 |
+
|
| 427 |
+
# tgt_bytes = resp.content
|
| 428 |
+
|
| 429 |
+
# src_array = np.frombuffer(src_bytes, np.uint8)
|
| 430 |
+
# tgt_array = np.frombuffer(tgt_bytes, np.uint8)
|
| 431 |
+
# src_bgr = cv2.imdecode(src_array, cv2.IMREAD_COLOR)
|
| 432 |
+
# tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)
|
| 433 |
+
|
| 434 |
+
# if src_bgr is None or tgt_bgr is None:
|
| 435 |
+
# #end_time = datetime.utcnow()
|
| 436 |
+
# end_time = datetime.now(timezone.utc)
|
| 437 |
+
|
| 438 |
+
# await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
|
| 439 |
+
# raise HTTPException(status_code=400, detail="Invalid image data")
|
| 440 |
+
|
| 441 |
+
# src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
|
| 442 |
+
# tgt_rgb = cv2.cvtColor(tgt_bgr, cv2.COLOR_BGR2RGB)
|
| 443 |
+
|
| 444 |
+
# final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
|
| 445 |
+
# if err:
|
| 446 |
+
# end_time = datetime.utcnow()
|
| 447 |
+
# await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
|
| 448 |
+
# raise HTTPException(status_code=500, detail=err)
|
| 449 |
+
|
| 450 |
+
# with open(final_path, "rb") as f:
|
| 451 |
+
# result_bytes = f.read()
|
| 452 |
+
# result_key = f"bikini-theme/result/{uuid.uuid4().hex}_enhanced.png"
|
| 453 |
+
# result_url = upload_to_spaces(result_bytes, result_key, content_type="image/png")
|
| 454 |
+
|
| 455 |
+
# #end_time = datetime.utcnow()
|
| 456 |
+
# end_time = datetime.now(timezone.utc)
|
| 457 |
+
# await log_faceswap_hit(user_email, status="success", start_time=start_time, end_time=end_time)
|
| 458 |
+
|
| 459 |
+
# return {"result_url": result_url}
|
| 460 |
+
|
| 461 |
+
# except Exception as e:
|
| 462 |
+
# #end_time = datetime.utcnow()
|
| 463 |
+
# end_time = datetime.now(timezone.utc)
|
| 464 |
+
|
| 465 |
+
# # Ensure we log the error with timestamps before raising
|
| 466 |
+
# try:
|
| 467 |
+
# await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
|
| 468 |
+
# except Exception as log_exc:
|
| 469 |
+
# logger.error("Failed to write log_faceswap_hit: %s", log_exc)
|
| 470 |
+
# raise HTTPException(status_code=500, detail=f"Face swap failed: {str(e)}")
|
| 471 |
|
| 472 |
|
| 473 |
@fastapi_app.get("/preview/{result_key:path}")
|