File size: 51,324 Bytes
031a705
7a955d9
078d18a
91eee68
078d18a
e6468b0
 
 
 
 
5df6f28
7a955d9
 
 
b60a4ed
4b4508d
 
3c79ccf
4b9cc62
e6468b0
 
3c79ccf
 
 
 
b60a4ed
 
08a3aa6
986fc3b
25592c0
 
eb78ab5
ec15dbc
 
eb78ab5
4b9cc62
7a955d9
 
4b9cc62
eb78ab5
 
b60a4ed
 
bb894d7
b60a4ed
bb894d7
b60a4ed
 
 
 
 
 
 
 
08a3aa6
 
 
 
 
 
 
 
 
 
 
 
b60a4ed
 
 
 
 
 
 
 
 
 
 
 
 
 
eb78ab5
4b9cc62
eb78ab5
4b9cc62
7a955d9
4b9cc62
7a955d9
eb78ab5
 
7a955d9
4b9cc62
 
 
 
 
 
 
 
 
 
 
 
eb78ab5
 
4b9cc62
ec15dbc
4b9cc62
 
eb78ab5
ec15dbc
c0b300b
 
4b9cc62
eb78ab5
7a955d9
 
 
4b9cc62
 
 
 
 
7a955d9
b60a4ed
88e5de6
031a705
e6468b0
cc4e1a8
a105acd
 
 
cc4e1a8
a105acd
cc4e1a8
a105acd
25592c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb78ab5
e6468b0
 
 
3c79ccf
 
e6468b0
 
3c79ccf
e6468b0
 
 
 
 
 
15642e3
913f4d4
15642e3
3c79ccf
31384f7
913f4d4
15642e3
b60a4ed
 
31384f7
913f4d4
 
 
15642e3
31384f7
26ea417
1179404
c12b71c
 
 
26ea417
c12b71c
 
 
 
 
 
26ea417
5df6f28
c12b71c
 
26ea417
c12b71c
 
 
 
 
 
 
5df6f28
 
c12b71c
 
 
 
 
5df6f28
26ea417
5df6f28
 
 
 
 
26ea417
5df6f28
4016953
26ea417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5df6f28
c12b71c
26ea417
c12b71c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ea417
c12b71c
 
 
 
 
26ea417
 
c12b71c
 
 
 
 
 
 
 
 
 
 
26ea417
c12b71c
 
 
 
 
 
26ea417
16338f5
 
c12b71c
26ea417
16338f5
 
 
 
 
 
26ea417
 
 
 
5df6f28
16338f5
5df6f28
 
 
 
16338f5
 
5df6f28
 
 
 
 
 
 
 
 
26ea417
 
5df6f28
 
 
 
 
26ea417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5df6f28
 
 
16338f5
 
 
 
 
 
 
5df6f28
 
 
 
 
 
 
16338f5
 
 
 
5df6f28
 
 
16338f5
 
5df6f28
16338f5
5df6f28
 
 
 
 
 
 
16338f5
 
 
 
 
 
 
5df6f28
16338f5
5df6f28
 
26ea417
5df6f28
 
 
16338f5
 
5df6f28
 
16338f5
0d7ed1a
078d18a
3c79ccf
7a955d9
078d18a
3c79ccf
 
 
078d18a
4c4b7b9
078d18a
4c4b7b9
0d7ed1a
 
 
 
b60a4ed
 
 
 
 
3c79ccf
078d18a
 
0d7ed1a
 
 
 
 
 
 
078d18a
7a955d9
a520e24
0d7ed1a
 
 
 
 
 
 
 
 
 
 
 
 
 
3c79ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb78ab5
c0b300b
4b4508d
 
031a705
4b9cc62
4b4508d
 
cc4e1a8
 
 
d8eb8a0
 
cc4e1a8
 
 
 
 
1179404
 
cc4e1a8
 
d8eb8a0
cc4e1a8
1179404
 
 
 
be23cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1179404
cc4e1a8
 
 
1179404
 
 
 
cc4e1a8
 
 
 
1179404
cc4e1a8
 
 
 
 
 
 
 
 
 
 
 
 
d8eb8a0
cc4e1a8
1179404
 
d8eb8a0
cc4e1a8
 
 
 
 
1179404
 
d8eb8a0
1179404
 
 
 
 
 
 
 
 
d8eb8a0
cc4e1a8
 
d8eb8a0
cc4e1a8
 
 
d8eb8a0
cc4e1a8
1179404
 
 
d8eb8a0
 
 
 
 
 
 
 
 
1179404
cc4e1a8
 
d8eb8a0
 
 
 
 
 
 
 
cc4e1a8
 
 
 
 
 
 
 
 
 
1179404
cc4e1a8
 
 
 
 
 
 
 
 
 
 
 
 
 
25592c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1179404
cc4e1a8
 
 
1179404
 
cc4e1a8
 
1179404
cc4e1a8
25592c0
 
cc4e1a8
 
1179404
 
 
cc4e1a8
1179404
 
 
 
 
 
 
 
cc4e1a8
 
1179404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a105acd
 
 
1179404
 
 
 
a105acd
 
 
1179404
a105acd
1179404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a105acd
 
 
 
1179404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc4e1a8
 
1179404
cc4e1a8
 
a105acd
 
1179404
cc4e1a8
a105acd
 
 
 
1179404
 
 
a105acd
 
1179404
cc4e1a8
a105acd
1179404
a105acd
 
1179404
a105acd
1179404
a105acd
1179404
a105acd
1179404
 
 
 
 
 
 
 
 
a105acd
 
1179404
cc4e1a8
913f4d4
e6468b0
1179404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
# --------------------- List Images Endpoint ---------------------
import os
os.environ["OMP_NUM_THREADS"] = "1"
import shutil
import uuid
import cv2
import numpy as np
import threading
import subprocess
import logging
from datetime import datetime, timezone,timedelta
import insightface
from insightface.app import FaceAnalysis
from huggingface_hub import hf_hub_download
from fastapi import FastAPI, UploadFile, File, HTTPException, Response, Depends, Security, Form
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
from motor.motor_asyncio import AsyncIOMotorClient
import uvicorn
import gradio as gr
from gradio import mount_gradio_app
# DigitalOcean Spaces
import boto3
from botocore.client import Config
from io import BytesIO
from typing import Optional
import requests
import json
from bson import ObjectId  
from PIL import Image
import io
# --------------------- Logging ---------------------
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --------------------- Paths -----------------------
REPO_ID = "HariLogicgo/face_swap_models"
BASE_DIR = "./workspace"
MODELS_DIR = "./models"
os.makedirs(MODELS_DIR, exist_ok=True)
# --------------------- Secrets ---------------------
HF_TOKEN = os.getenv("HF_TOKEN")  # Hugging Face private repo token
# Firebase credentials JSON
FIREBASE_CREDENTIALS_PATH = os.getenv("FIREBASE_CREDENTIALS_PATH")
# --------------------- DigitalOcean Spaces Credentials ---------------------
DO_SPACES_REGION = os.getenv("DO_SPACES_REGION", "blr1")
DO_SPACES_ENDPOINT = os.getenv("DO_SPACES_ENDPOINT", f"https://{DO_SPACES_REGION}.digitaloceanspaces.com")
DO_SPACES_KEY = os.getenv("DO_SPACES_KEY")
DO_SPACES_SECRET = os.getenv("DO_SPACES_SECRET")
DO_SPACES_BUCKET = os.getenv("DO_SPACES_BUCKET")
# --------------------- Firebase Auth ---------------------
import firebase_admin
from firebase_admin import credentials, auth
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
if not firebase_admin._apps:
    FIREBASE_CREDENTIALS = os.getenv("FIREBASE_CREDENTIALS_PATH")
    if not FIREBASE_CREDENTIALS:
        raise RuntimeError("❌ FIREBASE_CREDENTIALS_PATH not set in environment variables")
    try:
        # Try parsing as JSON string
        cred_dict = json.loads(FIREBASE_CREDENTIALS)
        cred = credentials.Certificate(cred_dict)
        logger.info("βœ… Firebase initialized from JSON string in environment variable")
    except json.JSONDecodeError:
        # Fallback: assume it's a file path
        cred = credentials.Certificate(FIREBASE_CREDENTIALS)
        logger.info("βœ… Firebase initialized from JSON file path")
    firebase_admin.initialize_app(cred)
security = HTTPBearer()
def verify_firebase_token(credentials: HTTPAuthorizationCredentials = Security(security)):
    """Verify Firebase ID token from Authorization header."""
    try:
        id_token = credentials.credentials
        decoded_token = auth.verify_id_token(id_token)
        user_email = decoded_token.get("email")
        if not user_email:
            raise HTTPException(status_code=401, detail="Firebase token invalid or missing email")
        return user_email
    except Exception as e:
        logger.error(f"Firebase auth failed: {e}")
        raise HTTPException(status_code=401, detail="Unauthorized: Invalid Firebase token")
# --------------------- Download Models ---------------------
def download_models():
    logger.info("Downloading models from private HF repo...")
    inswapper_path = hf_hub_download(
        repo_id=REPO_ID,
        filename="models/inswapper_128.onnx",
        repo_type="model",
        local_dir=MODELS_DIR,
        token=HF_TOKEN
    )
    buffalo_files = [
        "1k3d68.onnx",
        "2d106det.onnx",
        "genderage.onnx",
        "det_10g.onnx",
        "w600k_r50.onnx"
    ]
    for f in buffalo_files:
        hf_hub_download(
            repo_id=REPO_ID,
            filename=f"models/buffalo_l/{f}",
            repo_type="model",
            local_dir=MODELS_DIR,
            token=HF_TOKEN
        )
    logger.info("Models downloaded successfully")
    return inswapper_path
inswapper_path = download_models()
# --------------------- Face Analysis + Swapper ---------------------
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
face_analysis_app = FaceAnalysis(name="buffalo_l", root=MODELS_DIR, providers=providers)
face_analysis_app.prepare(ctx_id=0, det_size=(640, 640))
swapper = insightface.model_zoo.get_model(inswapper_path, providers=providers)
# --------------------- CodeFormer ---------------------
CODEFORMER_PATH = "CodeFormer/inference_codeformer.py"
def ensure_codeformer():
    if not os.path.exists("CodeFormer"):
        subprocess.run("git clone https://github.com/sczhou/CodeFormer.git", shell=True, check=True)
        subprocess.run("pip install -r CodeFormer/requirements.txt", shell=True, check=True)
        subprocess.run("python CodeFormer/basicsr/setup.py develop", shell=True, check=True)
        subprocess.run("python CodeFormer/scripts/download_pretrained_models.py facelib", shell=True, check=True)
        subprocess.run("python CodeFormer/scripts/download_pretrained_models.py CodeFormer", shell=True, check=True)
ensure_codeformer()
# --------------------- MongoDB ---------------------
MONGODB_URL = os.getenv("MONGODB_URL")
client = None
database = None
# --------------------- Admin Panel DB (categories + subcategories + media_clicks) ---------------------
ADMIN_MONGO_URL = os.getenv("ADMIN_MONGO_URL")
admin_client = AsyncIOMotorClient(ADMIN_MONGO_URL)
admin_db = admin_client.adminPanel
# Collections
categories_col = admin_db.categories
subcategories_col = admin_db.subcategories
media_clicks_col = admin_db.media_clicks

MAX_COMPRESSED_SIZE = 2 * 1024 * 1024  # 2 MB
def compress_image_bytes(
    image_bytes: bytes,
    max_dim: int = 1280
) -> bytes:
    """
    Compress image bytes by reducing dimensions + quality.
    Guaranteed <= 2MB (best-effort).
    """
    img = Image.open(io.BytesIO(image_bytes)).convert("RGB")

    # Reduce dimensions (keep aspect ratio)
    img.thumbnail((max_dim, max_dim), Image.LANCZOS)

    quality = 80
    buffer = io.BytesIO()

    while quality >= 40:
        buffer.seek(0)
        buffer.truncate()

        img.save(
            buffer,
            format="PNG",   # keep PNG since your output expects .png
            optimize=True
        )

        # PNG ignores quality, so if still big β†’ fallback to JPEG
        if buffer.tell() <= MAX_COMPRESSED_SIZE:
            return buffer.getvalue()

        quality -= 5

    # ---- FALLBACK TO JPEG (much smaller) ----
    buffer = io.BytesIO()
    img.save(
        buffer,
        format="JPEG",
        quality=70,
        optimize=True,
        progressive=True
    )
    return buffer.getvalue()
    
# --------------------- FastAPI ---------------------
fastapi_app = FastAPI()
@fastapi_app.on_event("startup")
async def startup_db():
    global client, database
    logger.info("Initializing MongoDB for API logs...")
    client = AsyncIOMotorClient(MONGODB_URL)
    database = client.FaceSwap
    logger.info("MongoDB initialized for API logs")
@fastapi_app.on_event("shutdown")
async def shutdown_db():
    global client
    if client:
        client.close()
        logger.info("MongoDB connection closed")
# --------------------- Logging API Hits ---------------------
async def log_faceswap_hit(user_email: str, status: str, start_time: datetime, end_time: datetime):
    global database
    if database is None:
        return
    response_time_ms = (end_time - start_time).total_seconds() * 1000
    await database.api_logs.insert_one({
        "user": user_email,
        "endpoint": "/face-swap",
        "status": status,
        "start_time": start_time,
        "end_time": end_time,
        "response_time_ms": response_time_ms
    })

# --------------------- Media Click Logging Helper ---------------------
# --------------------- Media Click Logging Helper ---------------------
async def log_media_click(user_id: str, category_oid_str: str):
    """
    Logs a click event to the media_clicks collection against the Category.
    ai_edit_daily_count is binary per day (no duplicate dates).
    """
    try:
        user_oid = ObjectId(user_id.strip())
        category_oid = ObjectId(category_oid_str.strip())
        now = datetime.utcnow()

        # Normalize today (UTC midnight)
        today_date = datetime(now.year, now.month, now.day)

        # -------------------------------------------------
        # STEP 1: Ensure root document exists
        # -------------------------------------------------
        await media_clicks_col.update_one(
            {"userId": user_oid},
            {
                "$setOnInsert": {
                    "userId": user_oid,
                    "createdAt": now,
                    "ai_edit_complete": 0,
                    "ai_edit_daily_count": []
                }
            },
            upsert=True
        )

        # -------------------------------------------------
        # STEP 2: FIXED DAILY BINARY TRACKING
        # -------------------------------------------------
        doc = await media_clicks_col.find_one(
            {"userId": user_oid},
            {"ai_edit_daily_count": 1}
        )

        daily_entries = doc.get("ai_edit_daily_count", []) if doc else []

        # Convert to date -> count map (unique by design)
        daily_map = {
            entry["date"]: entry["count"]
            for entry in daily_entries
        }

        # Determine last recorded date
        last_date = max(daily_map.keys()) if daily_map else today_date

        # Fill ALL missing days with 0
        next_day = last_date + timedelta(days=1)
        while next_day < today_date:
            daily_map.setdefault(next_day, 0)
            next_day += timedelta(days=1)

        # Mark today as used (binary)
        daily_map[today_date] = 1

        # Rebuild sorted list (old β†’ new)
        final_daily_entries = [
            {"date": d, "count": daily_map[d]}
            for d in sorted(daily_map.keys())
        ]

        # Keep last 32 days only
        final_daily_entries = final_daily_entries[-32:]

        # Atomic replace (NO $push)
        await media_clicks_col.update_one(
            {"userId": user_oid},
            {
                "$set": {
                    "ai_edit_daily_count": final_daily_entries,
                    "ai_edit_last_date": now,
                    "updatedAt": now
                }
            }
        )

        # -------------------------------------------------
        # STEP 3: CATEGORY CLICK LOGIC (DATES CAN REPEAT)
        # -------------------------------------------------
        update_result = await media_clicks_col.update_one(
            {
                "userId": user_oid,
                "categories.categoryId": category_oid
            },
            {
                "$inc": {
                    "categories.$.click_count": 1,
                    "ai_edit_complete": 1
                },
                "$set": {
                    "categories.$.lastClickedAt": now,
                    "updatedAt": now
                }
            }
        )

        # -------------------------------------------------
        # STEP 4: Push category if missing (order = time)
        # -------------------------------------------------
        if update_result.matched_count == 0:
            await media_clicks_col.update_one(
                {"userId": user_oid},
                {
                    "$inc": {"ai_edit_complete": 1},
                    "$set": {"updatedAt": now},
                    "$push": {
                        "categories": {
                            "categoryId": category_oid,
                            "click_count": 1,
                            "lastClickedAt": now
                        }
                    }
                }
            )

        logger.info(
            "[MEDIA_CLICK] user=%s category=%s daily_binary_tracked",
            user_id,
            category_oid_str
        )

    except Exception as media_err:
        logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)

# async def log_media_click(user_id: str, category_oid_str: str):
#     """
#     Logs a click event to the media_clicks collection against the Category.
#     Safely updates ai_edit_last_date, ai_edit_complete, and ai_edit_daily_count.
#     """
#     try:
#         user_oid = ObjectId(user_id.strip())
#         category_oid = ObjectId(category_oid_str.strip())
#         now = datetime.utcnow()

#         # Normalize dates (UTC midnight)
#         today_date = datetime(now.year, now.month, now.day)
#         yesterday_date = today_date - timedelta(days=1)

#         # Optional safety check
#         if not await categories_col.find_one({"_id": category_oid}):
#             logger.warning(
#                 "Category ID %s not found. Skipping media click logging.",
#                 category_oid_str
#             )
#             return

#         # -------------------------------------------------
#         # STEP 1: Ensure user document + root fields exist
#         # -------------------------------------------------
#         await media_clicks_col.update_one(
#             {"userId": user_oid},
#             {
#                 "$setOnInsert": {
#                     "userId": user_oid,
#                     "createdAt": now,
#                     "ai_edit_complete": 0,
#                     "ai_edit_daily_count": []
#                 }
#             },
#             upsert=True
#         )

#         # -------------------------------------------------
#         # STEP 1.5: Handle ai_edit_daily_count
#         # -------------------------------------------------
#         doc = await media_clicks_col.find_one(
#             {"userId": user_oid},
#             {"ai_edit_daily_count": 1}
#         )
#         daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
#         daily_updates = []
        
#         if not daily_entries:
#             # First-ever usage β†’ only today
#             daily_updates.append({"date": today_date, "count": 1})
#         else:
#             # Build existing date map for lookup
#             existing_dates = {entry["date"].date(): entry["count"] for entry in daily_entries}
#             last_date_in_db = max(entry["date"].date() for entry in daily_entries)
        
#             # Fill missing days between last recorded day and today-1
#             next_day = last_date_in_db + timedelta(days=1)
#             while next_day < today_date:
#                 if next_day not in existing_dates:
#                     daily_updates.append({"date": next_day, "count": 0})
#                 next_day += timedelta(days=1)
        
#             # Add today if not already present
#             if today_date not in existing_dates:
#                 daily_updates.append({"date": today_date, "count": 1})
        
#         # Push updates if any
#         if daily_updates:
#             await media_clicks_col.update_one(
#                 {"userId": user_oid},
#                 {"$push": {"ai_edit_daily_count": {"$each": daily_updates}}}
#             )
        
#         # Sort oldest β†’ newest and trim to last 32 entries
#         doc = await media_clicks_col.find_one({"userId": user_oid}, {"ai_edit_daily_count": 1})
#         daily_entries = doc.get("ai_edit_daily_count", []) if doc else []
#         daily_entries.sort(key=lambda x: x["date"])
#         if len(daily_entries) > 32:
#             daily_entries = daily_entries[-32:]
#             await media_clicks_col.update_one(
#                 {"userId": user_oid},
#                 {"$set": {"ai_edit_daily_count": daily_entries}}
#             )


#         # -------------------------------------------------
#         # STEP 2: Try updating existing category
#         # -------------------------------------------------
#         update_result = await media_clicks_col.update_one(
#             {
#                 "userId": user_oid,
#                 "categories.categoryId": category_oid
#             },
#             {
#                 "$inc": {
#                     "categories.$.click_count": 1,
#                     "ai_edit_complete": 1
#                 },
#                 "$set": {
#                     "categories.$.lastClickedAt": now,
#                     "ai_edit_last_date": now,
#                     "updatedAt": now
#                 }
#             }
#         )

#         # -------------------------------------------------
#         # STEP 3: Category not present β†’ push new
#         # -------------------------------------------------
#         if update_result.matched_count == 0:
#             await media_clicks_col.update_one(
#                 {"userId": user_oid},
#                 {
#                     "$inc": {
#                         "ai_edit_complete": 1
#                     },
#                     "$set": {
#                         "ai_edit_last_date": now,
#                         "updatedAt": now
#                     },
#                     "$push": {
#                         "categories": {
#                             "categoryId": category_oid,
#                             "click_count": 1,
#                             "lastClickedAt": now
#                         }
#                     }
#                 }
#             )

#         logger.info(
#             "[MEDIA_CLICK] user=%s category=%s ai_edit_complete incremented & daily_tracked",
#             user_id,
#             category_oid_str
#         )

#     except Exception as media_err:
#         logger.error("MEDIA_CLICK LOGGING ERROR: %s", media_err)


# --------------------- Face Swap Pipeline ---------------------
swap_lock = threading.Lock()
def face_swap_and_enhance(src_img, tgt_img, temp_dir="/tmp/faceswap_work"):
    try:
        with swap_lock:
            if os.path.exists(temp_dir):
                shutil.rmtree(temp_dir)
            os.makedirs(temp_dir, exist_ok=True)
            src_bgr = cv2.cvtColor(src_img, cv2.COLOR_RGB2BGR)
            tgt_bgr_full = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)
            src_faces = face_analysis_app.get(src_bgr)
            tgt_faces = face_analysis_app.get(tgt_bgr_full)
            if not src_faces or not tgt_faces:
                return None, None, "❌ Face not detected in source or target image"
            src_face0 = src_faces[0]
            tgt_face0 = tgt_faces[0]
            swapped_bgr_full = swapper.get(tgt_bgr_full, tgt_face0, src_face0)
            if swapped_bgr_full is None:
                return None, None, "❌ Face swap failed"
            swapped_path = os.path.join(temp_dir, f"swapped_{uuid.uuid4().hex[:8]}.jpg")
            cv2.imwrite(swapped_path, swapped_bgr_full)
            cmd = f"python {CODEFORMER_PATH} -w 0.7 --input_path {swapped_path} --output_path {temp_dir} --bg_upsampler realesrgan --face_upsample"
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            if result.returncode != 0:
                return None, None, f"❌ CodeFormer failed:\n{result.stderr}"
            final_results_dir = os.path.join(temp_dir, "final_results")
            final_files = [f for f in os.listdir(final_results_dir) if f.endswith(".png")]
            if not final_files:
                return None, None, "❌ No enhanced image found"
            final_path = os.path.join(final_results_dir, final_files[0])
            final_img = cv2.cvtColor(cv2.imread(final_path), cv2.COLOR_BGR2RGB)
            return final_img, final_path, ""
    except Exception as e:
        return None, None, f"❌ Error: {str(e)}"
# --------------------- Gradio ---------------------
with gr.Blocks() as demo:
    gr.Markdown("Face Swap")
    with gr.Row():
        src_input = gr.Image(type="numpy", label="Upload Your Face")
        tgt_input = gr.Image(type="numpy", label="Upload Target Image")
    btn = gr.Button("Swap Face")
    output_img = gr.Image(type="numpy", label="Enhanced Output")
    download = gr.File(label="⬇️ Download Enhanced Image")
    error_box = gr.Textbox(label="Logs / Errors", interactive=False)
    def process(src, tgt):
        img, path, err = face_swap_and_enhance(src, tgt)
        return img, path, err
    btn.click(process, [src_input, tgt_input], [output_img, download, error_box])
# --------------------- DigitalOcean Spaces Helper ---------------------
def get_spaces_client():
    session = boto3.session.Session()
    client = session.client(
        's3',
        region_name=DO_SPACES_REGION,
        endpoint_url=DO_SPACES_ENDPOINT,
        aws_access_key_id=DO_SPACES_KEY,
        aws_secret_access_key=DO_SPACES_SECRET,
        config=Config(signature_version='s3v4')
    )
    return client
def upload_to_spaces(file_bytes, key, content_type="image/png"):
    client = get_spaces_client()
    client.put_object(Bucket=DO_SPACES_BUCKET, Key=key, Body=file_bytes, ContentType=content_type, ACL='public-read')
    return f"{DO_SPACES_ENDPOINT}/{DO_SPACES_BUCKET}/{key}"
def download_from_spaces(key):
    client = get_spaces_client()
    obj = client.get_object(Bucket=DO_SPACES_BUCKET, Key=key)
    return obj['Body'].read()
# --------------------- API Endpoints ---------------------
@fastapi_app.get("/")
def root():
    return RedirectResponse("/gradio")
@fastapi_app.get("/health")
async def health():
    return {"status": "healthy"}

@fastapi_app.post("/face-swap")
async def face_swap_api(
    source: UploadFile = File(...),
    target_category_id: Optional[str] = Form(None), 
    category_id: Optional[str] = Form(None), # <-- The ID to use for media click logging
    user_id: Optional[str] = Form(None),
    new_subcategory_id: Optional[str] = Form(None),
    user_email: str = Depends(verify_firebase_token)
):
    start_time = datetime.now(timezone.utc)
    target_url = None
    
    try:
        # ---------------------------------------------------------
        # NORMALIZE EMPTY STRINGS
        # ---------------------------------------------------------
        if target_category_id == "": target_category_id = None
        if new_subcategory_id == "": new_subcategory_id = None
        if category_id == "": category_id = None
        if user_id == "": user_id = None

        # ---------------------------------------------------------
        # REQUEST TRACE LOG
        # ---------------------------------------------------------
        logger.info(
            "FACE_SWAP_REQUEST | user_id=%s | category_id=%s | new_subcategory_id=%s",
            user_id,
            category_id,
            new_subcategory_id
        )
        
        # Optional warning if nothing useful is provided
        if not user_id and not category_id and not new_subcategory_id:
            logger.warning(
                "FACE_SWAP_REQUEST_MISSING_IDS | user_id=%s | category_id=%s | new_subcategory_id=%s",
                user_id,
                category_id,
                new_subcategory_id
            )
        
        # ---------------------------------------------------------
        # STRICT XOR VALIDATION
        # ---------------------------------------------------------
        target_provided = target_category_id is not None
        new_sub_provided = new_subcategory_id is not None

        if target_provided and new_sub_provided:
            raise HTTPException(
                status_code=400,
                detail="Provide ONLY ONE of: target_category_id OR new_subcategory_id"
            )
        if not target_provided and not new_sub_provided:
            raise HTTPException(
                status_code=400,
                detail="Either target_category_id OR new_subcategory_id is required"
            )

        # ---------------------------------------------------------
        # READ SOURCE IMAGE
        # ---------------------------------------------------------
        src_bytes = await source.read()
        src_key = f"bikini-theme/source/{uuid.uuid4().hex}_{source.filename}"
        upload_to_spaces(src_bytes, src_key, content_type=source.content_type)

        # ---------------------------------------------------------
        # TARGET IMAGE RETRIEVAL
        # ---------------------------------------------------------

        if target_provided:
            # CASE 1 β€” Old behavior (use DO Spaces target image)
            target_filename = f"{target_category_id}.png"
            target_url = (
                f"https://{DO_SPACES_BUCKET}.{DO_SPACES_REGION}."
                f"digitaloceanspaces.com/bikini-theme/target/{target_filename}"
            )
            
        elif new_sub_provided:
            # CASE 2 β€” New behavior (use subcategory asset image)
            
            try:
                asset_oid = ObjectId(new_subcategory_id)
            except:
                raise HTTPException(400, "Invalid new_subcategory_id format.")

            # 1. Find subcategory asset by asset_images._id
            subcat_doc = await subcategories_col.find_one(
                {"asset_images._id": asset_oid},
                {"asset_images.$": 1} # Only need the asset image URL
            )

            if not subcat_doc or "asset_images" not in subcat_doc:
                await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
                raise HTTPException(
                    status_code=404,
                    detail="Subcategory asset image not found in DB."
                )
            
            asset_url = subcat_doc["asset_images"][0]["url"]
            target_url = asset_url 
        
        # ---------------------------------------------------------
        # DOWNLOAD TARGET IMAGE
        # ---------------------------------------------------------
        resp = requests.get(target_url)
        if resp.status_code != 200:
            await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
            raise HTTPException(status_code=404, detail=f"Target image not found or download failed: {target_url}")
        tgt_bytes = resp.content


        # ---------------------------------------------------------
        # MEDIA CLICK LOGGING (Unified Logic)
        # ---------------------------------------------------------
        if user_id and category_id:
            # Log only if both optional logging fields are provided
            await log_media_click(user_id, category_id)

        # ---------------------------------------------------------
        # DECODE & FACE SWAP
        # ---------------------------------------------------------
        src_array = np.frombuffer(src_bytes, np.uint8)
        tgt_array = np.frombuffer(tgt_bytes, np.uint8)
        src_bgr = cv2.imdecode(src_array, cv2.IMREAD_COLOR)
        tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)

        if src_bgr is None or tgt_bgr is None:
            await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
            raise HTTPException(status_code=400, detail="Invalid image data")

        # Convert to RGB for processing
        src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
        tgt_rgb = cv2.cvtColor(tgt_bgr, cv2.COLOR_BGR2RGB)

        # FACE SWAP & ENHANCE
        final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
        if err:
            await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
            raise HTTPException(status_code=500, detail=err)

        # Save final output to DO Spaces
        with open(final_path, "rb") as f:
            result_bytes = f.read()
        result_key = f"bikini-theme/result/{uuid.uuid4().hex}_enhanced.png"
        result_url = upload_to_spaces(result_bytes, result_key, "image/png")
        # ---------------------------------------------------------
        # COMPRESS RESULT IMAGE
        # ---------------------------------------------------------
        compressed_bytes = compress_image_bytes(
            image_bytes=result_bytes,
            max_dim=1280
        )
        
        compressed_key = result_key.replace("_enhanced.png", "_compressed.png")
        
        compressed_url = upload_to_spaces(
            compressed_bytes,
            compressed_key,
            "image/png"
        )
        
        # ---------------------------------------------------------
        # SUCCESS RESPONSE
        # ---------------------------------------------------------
        await log_faceswap_hit(user_email, "success", start_time, datetime.now(timezone.utc))
        
        return {
            "result_url": result_url,
            "category_id": category_id, 
            "user_id": user_id,
            "new_subcategory_id": new_subcategory_id,
            "Compressed_Image_URL": compressed_url
        }

    except HTTPException:
        raise
        
    except Exception as e:
        end_time = datetime.now(timezone.utc)
        try:
            await log_faceswap_hit(user_email, "error", start_time, end_time)
        except Exception as log_exc:
            logger.error("Failed to write log_faceswap_hit: %s", log_exc)
            
        logger.error(f"Critical /face-swap error: {e}")
        raise HTTPException(status_code=500, detail=f"Face swap failed: Internal server error.")


@fastapi_app.get("/preview/{result_key:path}")
async def preview_result(result_key: str):
    try:
        img_bytes = download_from_spaces(result_key)
    except Exception:
        raise HTTPException(status_code=404, detail="Result not found")
    return Response(
        content=img_bytes,
        media_type="image/png",
        headers={"Content-Disposition": "inline; filename=result.png"}
    )
# --------------------- Mount Gradio ---------------------
fastapi_app = mount_gradio_app(fastapi_app, demo, path="/gradio")
if __name__ == "__main__":
    uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)










# # --------------------- List Images Endpoint ---------------------
# import os
# os.environ["OMP_NUM_THREADS"] = "1"
# import shutil
# import uuid
# import cv2
# import numpy as np
# import threading
# import subprocess
# import logging
# from datetime import datetime, timezone

# import insightface
# from insightface.app import FaceAnalysis
# from huggingface_hub import hf_hub_download

# from fastapi import FastAPI, UploadFile, File, HTTPException, Response, Depends, Security, Form
# from fastapi.responses import RedirectResponse
# from pydantic import BaseModel
# from motor.motor_asyncio import AsyncIOMotorClient

# import uvicorn
# import gradio as gr
# from gradio import mount_gradio_app

# # DigitalOcean Spaces
# import boto3
# from botocore.client import Config
# from io import BytesIO
# from typing import Optional
# import requests
# import json
# from bson import ObjectId  

# # --------------------- Logging ---------------------
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # --------------------- Paths -----------------------
# REPO_ID = "HariLogicgo/face_swap_models"
# BASE_DIR = "./workspace"
# MODELS_DIR = "./models"

# os.makedirs(MODELS_DIR, exist_ok=True)

# # --------------------- Secrets ---------------------
# HF_TOKEN = os.getenv("HF_TOKEN")  # Hugging Face private repo token
# # Firebase credentials JSON
# FIREBASE_CREDENTIALS_PATH = os.getenv("FIREBASE_CREDENTIALS_PATH")

# # --------------------- DigitalOcean Spaces Credentials ---------------------
# DO_SPACES_REGION = os.getenv("DO_SPACES_REGION", "blr1")
# DO_SPACES_ENDPOINT = os.getenv("DO_SPACES_ENDPOINT", f"https://{DO_SPACES_REGION}.digitaloceanspaces.com")
# DO_SPACES_KEY = os.getenv("DO_SPACES_KEY")
# DO_SPACES_SECRET = os.getenv("DO_SPACES_SECRET")
# DO_SPACES_BUCKET = os.getenv("DO_SPACES_BUCKET")

# # --------------------- Firebase Auth ---------------------
# import firebase_admin
# from firebase_admin import credentials, auth
# from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

# if not firebase_admin._apps:
#     FIREBASE_CREDENTIALS = os.getenv("FIREBASE_CREDENTIALS_PATH")
#     if not FIREBASE_CREDENTIALS:
#         raise RuntimeError("❌ FIREBASE_CREDENTIALS_PATH not set in environment variables")

#     try:
#         # Try parsing as JSON string
#         cred_dict = json.loads(FIREBASE_CREDENTIALS)
#         cred = credentials.Certificate(cred_dict)
#         logger.info("βœ… Firebase initialized from JSON string in environment variable")
#     except json.JSONDecodeError:
#         # Fallback: assume it's a file path
#         cred = credentials.Certificate(FIREBASE_CREDENTIALS)
#         logger.info("βœ… Firebase initialized from JSON file path")

#     firebase_admin.initialize_app(cred)

# security = HTTPBearer()

# def verify_firebase_token(credentials: HTTPAuthorizationCredentials = Security(security)):
#     """Verify Firebase ID token from Authorization header."""
#     try:
#         id_token = credentials.credentials
#         decoded_token = auth.verify_id_token(id_token)
#         user_email = decoded_token.get("email")
#         if not user_email:
#             raise HTTPException(status_code=401, detail="Firebase token invalid or missing email")
#         return user_email
#     except Exception as e:
#         logger.error(f"Firebase auth failed: {e}")
#         raise HTTPException(status_code=401, detail="Unauthorized: Invalid Firebase token")

# # --------------------- Download Models ---------------------
# def download_models():
#     logger.info("Downloading models from private HF repo...")
#     inswapper_path = hf_hub_download(
#         repo_id=REPO_ID,
#         filename="models/inswapper_128.onnx",
#         repo_type="model",
#         local_dir=MODELS_DIR,
#         token=HF_TOKEN
#     )

#     buffalo_files = [
#         "1k3d68.onnx",
#         "2d106det.onnx",
#         "genderage.onnx",
#         "det_10g.onnx",
#         "w600k_r50.onnx"
#     ]
#     for f in buffalo_files:
#         hf_hub_download(
#             repo_id=REPO_ID,
#             filename=f"models/buffalo_l/{f}",
#             repo_type="model",
#             local_dir=MODELS_DIR,
#             token=HF_TOKEN
#         )
#     logger.info("Models downloaded successfully")
#     return inswapper_path

# inswapper_path = download_models()

# # --------------------- Face Analysis + Swapper ---------------------
# providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
# face_analysis_app = FaceAnalysis(name="buffalo_l", root=MODELS_DIR, providers=providers)
# face_analysis_app.prepare(ctx_id=0, det_size=(640, 640))
# swapper = insightface.model_zoo.get_model(inswapper_path, providers=providers)

# # --------------------- CodeFormer ---------------------
# CODEFORMER_PATH = "CodeFormer/inference_codeformer.py"

# def ensure_codeformer():
#     if not os.path.exists("CodeFormer"):
#         subprocess.run("git clone https://github.com/sczhou/CodeFormer.git", shell=True, check=True)
#         subprocess.run("pip install -r CodeFormer/requirements.txt", shell=True, check=True)
#         subprocess.run("python CodeFormer/basicsr/setup.py develop", shell=True, check=True)
#         subprocess.run("python CodeFormer/scripts/download_pretrained_models.py facelib", shell=True, check=True)
#         subprocess.run("python CodeFormer/scripts/download_pretrained_models.py CodeFormer", shell=True, check=True)

# ensure_codeformer()

# # --------------------- MongoDB ---------------------
# MONGODB_URL = os.getenv("MONGODB_URL")

# client = None
# database = None

# # --------------------- Admin Panel DB (categories + media_clicks) ---------------------
# # --------------------- Admin Panel DB (categories + subcategories + media_clicks) ---------------------
# ADMIN_MONGO_URL = os.getenv("ADMIN_MONGO_URL")
# admin_client = AsyncIOMotorClient(ADMIN_MONGO_URL)
# admin_db = admin_client.adminPanel

# # Collections
# categories_col = admin_db.categories
# subcategories_col = admin_db.subcategories
# media_clicks_col = admin_db.media_clicks
# users_col = admin_db.users  # optional, only if needed

# # --------------------- FastAPI ---------------------
# fastapi_app = FastAPI()

# @fastapi_app.on_event("startup")
# async def startup_db():
#     global client, database
#     logger.info("Initializing MongoDB for API logs...")
#     client = AsyncIOMotorClient(MONGODB_URL)
#     database = client.FaceSwap
#     logger.info("MongoDB initialized for API logs")

# @fastapi_app.on_event("shutdown")
# async def shutdown_db():
#     global client
#     if client:
#         client.close()
#         logger.info("MongoDB connection closed")

# # --------------------- Logging API Hits ---------------------
# async def log_faceswap_hit(user_email: str, status: str, start_time: datetime, end_time: datetime):
#     global database
#     if database is None:
#         return

#     response_time_ms = (end_time - start_time).total_seconds() * 1000

#     await database.api_logs.insert_one({
#         "user": user_email,
#         "endpoint": "/face-swap",
#         "status": status,
#         "start_time": start_time,
#         "end_time": end_time,
#         "response_time_ms": response_time_ms
#     })


# # --------------------- Face Swap Pipeline ---------------------
# swap_lock = threading.Lock()

# def face_swap_and_enhance(src_img, tgt_img, temp_dir="/tmp/faceswap_work"):
#     try:
#         with swap_lock:
#             if os.path.exists(temp_dir):
#                 shutil.rmtree(temp_dir)
#             os.makedirs(temp_dir, exist_ok=True)

#             src_bgr = cv2.cvtColor(src_img, cv2.COLOR_RGB2BGR)
#             tgt_bgr_full = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)

#             src_faces = face_analysis_app.get(src_bgr)
#             tgt_faces = face_analysis_app.get(tgt_bgr_full)

#             if not src_faces or not tgt_faces:
#                 return None, None, "❌ Face not detected in source or target image"

#             src_face0 = src_faces[0]
#             tgt_face0 = tgt_faces[0]

#             swapped_bgr_full = swapper.get(tgt_bgr_full, tgt_face0, src_face0)
#             if swapped_bgr_full is None:
#                 return None, None, "❌ Face swap failed"

#             swapped_path = os.path.join(temp_dir, f"swapped_{uuid.uuid4().hex[:8]}.jpg")
#             cv2.imwrite(swapped_path, swapped_bgr_full)

#             cmd = f"python {CODEFORMER_PATH} -w 0.7 --input_path {swapped_path} --output_path {temp_dir} --bg_upsampler realesrgan --face_upsample"
#             result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
#             if result.returncode != 0:
#                 return None, None, f"❌ CodeFormer failed:\n{result.stderr}"

#             final_results_dir = os.path.join(temp_dir, "final_results")
#             final_files = [f for f in os.listdir(final_results_dir) if f.endswith(".png")]
#             if not final_files:
#                 return None, None, "❌ No enhanced image found"

#             final_path = os.path.join(final_results_dir, final_files[0])
#             final_img = cv2.cvtColor(cv2.imread(final_path), cv2.COLOR_BGR2RGB)

#             return final_img, final_path, ""

#     except Exception as e:
#         return None, None, f"❌ Error: {str(e)}"

# # --------------------- Gradio ---------------------
# with gr.Blocks() as demo:
#     gr.Markdown("Face Swap")

#     with gr.Row():
#         src_input = gr.Image(type="numpy", label="Upload Your Face")
#         tgt_input = gr.Image(type="numpy", label="Upload Target Image")

#     btn = gr.Button("Swap Face")
#     output_img = gr.Image(type="numpy", label="Enhanced Output")
#     download = gr.File(label="⬇️ Download Enhanced Image")
#     error_box = gr.Textbox(label="Logs / Errors", interactive=False)

#     def process(src, tgt):
#         img, path, err = face_swap_and_enhance(src, tgt)
#         return img, path, err

#     btn.click(process, [src_input, tgt_input], [output_img, download, error_box])

# # --------------------- DigitalOcean Spaces Helper ---------------------
# def get_spaces_client():
#     session = boto3.session.Session()
#     client = session.client(
#         's3',
#         region_name=DO_SPACES_REGION,
#         endpoint_url=DO_SPACES_ENDPOINT,
#         aws_access_key_id=DO_SPACES_KEY,
#         aws_secret_access_key=DO_SPACES_SECRET,
#         config=Config(signature_version='s3v4')
#     )
#     return client

# def upload_to_spaces(file_bytes, key, content_type="image/png"):
#     client = get_spaces_client()
#     client.put_object(Bucket=DO_SPACES_BUCKET, Key=key, Body=file_bytes, ContentType=content_type, ACL='public-read')
#     return f"{DO_SPACES_ENDPOINT}/{DO_SPACES_BUCKET}/{key}"

# def download_from_spaces(key):
#     client = get_spaces_client()
#     obj = client.get_object(Bucket=DO_SPACES_BUCKET, Key=key)
#     return obj['Body'].read()

# # --------------------- API Endpoints ---------------------
# @fastapi_app.get("/")
# def root():
#     return RedirectResponse("/gradio")

# @fastapi_app.get("/health")
# async def health():
#     return {"status": "healthy"}

# @fastapi_app.post("/face-swap")
# async def face_swap_api(
#     source: UploadFile = File(...),
#     target_category_id: str = Form(...),  # REQUIRED (old behavior preserved)
#     category_id: Optional[str] = Form(None),
#     user_id: Optional[str] = Form(None),
#     new_subcategory_id: Optional[str] = Form(None),
#     user_email: str = Depends(verify_firebase_token)
# ):
#     start_time = datetime.now(timezone.utc)

#     try:
#         # ---------------------------------------------------------
#         # NORMALIZE EMPTY STRINGS (Android older versions)
#         # ---------------------------------------------------------
#         if target_category_id == "":
#             target_category_id = None

#         if new_subcategory_id == "":
#             new_subcategory_id = None

#         if category_id == "":
#             category_id = None

#         if user_id == "":
#             user_id = None

#         # ---------------------------------------------------------
#         # STRICT XOR VALIDATION
#         # ---------------------------------------------------------
#         if target_category_id and new_subcategory_id:
#             raise HTTPException(
#                 status_code=400,
#                 detail="Provide ONLY ONE of: target_category_id OR new_subcategory_id"
#             )

#         if not target_category_id and not new_subcategory_id:
#             raise HTTPException(
#                 status_code=400,
#                 detail="Either target_category_id OR new_subcategory_id is required"
#             )

#         # ---------------------------------------------------------
#         # READ SOURCE IMAGE
#         # ---------------------------------------------------------
#         src_bytes = await source.read()
#         src_key = f"bikini-theme/source/{uuid.uuid4().hex}_{source.filename}"
#         upload_to_spaces(src_bytes, src_key, content_type=source.content_type)

#         # ---------------------------------------------------------
#         # CASE 1 β€” Old behavior (use DO Spaces target image)
#         # ---------------------------------------------------------
#         if target_category_id:
#             target_filename = f"{target_category_id}.png"
#             target_url = (
#                 f"https://{DO_SPACES_BUCKET}.{DO_SPACES_REGION}."
#                 f"digitaloceanspaces.com/bikini-theme/target/{target_filename}"
#             )

#             resp = requests.get(target_url)
#             if resp.status_code != 200:
#                 await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
#                 raise HTTPException(status_code=404, detail=f"Target image not found: {target_url}")

#             tgt_bytes = resp.content

#         # ---------------------------------------------------------
#         # CASE 2 β€” New behavior (use subcategory asset image)
#         # ---------------------------------------------------------
#         else:
#             # Find subcategory asset by asset_images._id
#             asset = await admin_db.subcategories.find_one(
#                 {"asset_images._id": ObjectId(new_subcategory_id)},
#                 {"asset_images.$": 1}
#             )

#             if not asset or "asset_images" not in asset:
#                 await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
#                 raise HTTPException(
#                     status_code=404,
#                     detail="Subcategory asset image not found"
#                 )

#             # Extract the single matching image URL
#             asset_url = asset["asset_images"][0]["url"]

#             resp = requests.get(asset_url)
#             if resp.status_code != 200:
#                 raise HTTPException(
#                     status_code=404,
#                     detail=f"Failed to download asset image: {asset_url}"
#                 )

#             tgt_bytes = resp.content

#         # ---------------------------------------------------------
#         # DECODE BOTH IMAGES
#         # ---------------------------------------------------------
#         src_array = np.frombuffer(src_bytes, np.uint8)
#         tgt_array = np.frombuffer(tgt_bytes, np.uint8)

#         src_bgr = cv2.imdecode(src_array, cv2.IMREAD_COLOR)
#         tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)

#         if src_bgr is None or tgt_bgr is None:
#             await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
#             raise HTTPException(status_code=400, detail="Invalid image data")

#         src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
#         tgt_rgb = cv2.cvtColor(tgt_bgr, cv2.COLOR_BGR2RGB)

#         # ---------------------------------------------------------
#         # FACE SWAP & ENHANCE
#         # ---------------------------------------------------------
#         final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
#         if err:
#             await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
#             raise HTTPException(status_code=500, detail=err)

#         # Save final output to DO Spaces
#         with open(final_path, "rb") as f:
#             result_bytes = f.read()

#         result_key = f"bikini-theme/result/{uuid.uuid4().hex}_enhanced.png"
#         result_url = upload_to_spaces(result_bytes, result_key, "image/png")

#         await log_faceswap_hit(user_email, "success", start_time, datetime.now(timezone.utc))

#         # ---------------------------------------------------------
#         # SUCCESS RESPONSE
#         # ---------------------------------------------------------
#         return {
#             "result_url": result_url,
#             "category_id": category_id,
#             "user_id": user_id,
#             "new_subcategory_id": new_subcategory_id
#         }

#     except Exception as e:
#         await log_faceswap_hit(user_email, "error", start_time, datetime.now(timezone.utc))
#         raise HTTPException(status_code=500, detail=f"Face swap failed: {str(e)}")


# ####------------------------------------OLD CODE------------------------------------####
# # @fastapi_app.post("/face-swap")
# # async def face_swap_api(
# #     source: UploadFile = File(...),
# #     target_category_id: str = Form(...),
# #     user_email: str = Depends(verify_firebase_token)
# # ):
# #     # start_time = datetime.utcnow()
# #     start_time = datetime.now(timezone.utc)
# #     try:
# #         src_bytes = await source.read()
# #         src_key = f"bikini-theme/source/{uuid.uuid4().hex}_{source.filename}"
# #         upload_to_spaces(src_bytes, src_key, content_type=source.content_type)

# #         target_filename = f"{target_category_id}.png"
# #         target_url = f"https://{DO_SPACES_BUCKET}.{DO_SPACES_REGION}.digitaloceanspaces.com/bikini-theme/target/{target_filename}"

# #         resp = requests.get(target_url)
# #         if resp.status_code != 200:
# #             # end_time = datetime.utcnow()
# #             end_time = datetime.now(timezone.utc)
# #             await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
# #             raise HTTPException(status_code=404, detail=f"Target image not found at {target_url}")

# #         tgt_bytes = resp.content

# #         src_array = np.frombuffer(src_bytes, np.uint8)
# #         tgt_array = np.frombuffer(tgt_bytes, np.uint8)
# #         src_bgr = cv2.imdecode(src_array, cv2.IMREAD_COLOR)
# #         tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)

# #         if src_bgr is None or tgt_bgr is None:
# #             #end_time = datetime.utcnow()
# #             end_time = datetime.now(timezone.utc)

# #             await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
# #             raise HTTPException(status_code=400, detail="Invalid image data")

# #         src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
# #         tgt_rgb = cv2.cvtColor(tgt_bgr, cv2.COLOR_BGR2RGB)

# #         final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
# #         if err:
# #             end_time = datetime.utcnow()
# #             await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
# #             raise HTTPException(status_code=500, detail=err)

# #         with open(final_path, "rb") as f:
# #             result_bytes = f.read()
# #         result_key = f"bikini-theme/result/{uuid.uuid4().hex}_enhanced.png"
# #         result_url = upload_to_spaces(result_bytes, result_key, content_type="image/png")

# #         #end_time = datetime.utcnow()
# #         end_time = datetime.now(timezone.utc)
# #         await log_faceswap_hit(user_email, status="success", start_time=start_time, end_time=end_time)

# #         return {"result_url": result_url}

# #     except Exception as e:
# #         #end_time = datetime.utcnow()
# #         end_time = datetime.now(timezone.utc)

# #         # Ensure we log the error with timestamps before raising
# #         try:
# #             await log_faceswap_hit(user_email, status="error", start_time=start_time, end_time=end_time)
# #         except Exception as log_exc:
# #             logger.error("Failed to write log_faceswap_hit: %s", log_exc)
# #         raise HTTPException(status_code=500, detail=f"Face swap failed: {str(e)}")


# @fastapi_app.get("/preview/{result_key:path}")
# async def preview_result(result_key: str):
#     try:
#         img_bytes = download_from_spaces(result_key)
#     except Exception:
#         raise HTTPException(status_code=404, detail="Result not found")
#     return Response(
#         content=img_bytes,
#         media_type="image/png",
#         headers={"Content-Disposition": "inline; filename=result.png"}
#     )

# # --------------------- Mount Gradio ---------------------
# fastapi_app = mount_gradio_app(fastapi_app, demo, path="/gradio")

# if __name__ == "__main__":
#     uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)