File size: 51,469 Bytes
031a705
7a955d9
078d18a
91eee68
078d18a
e6468b0
 
 
 
 
d2df5a7
 
bb8d3b6
e6468b0
7a955d9
 
 
533b0a8
4b4508d
eb78ab5
3c79ccf
533b0a8
d2df5a7
 
4b9cc62
e6468b0
 
a234b0a
 
ec15dbc
3c79ccf
 
 
533b0a8
 
eb78ab5
ec15dbc
 
7a955d9
533b0a8
4b9cc62
7a955d9
4b9cc62
7a955d9
533b0a8
 
 
 
 
 
 
 
 
 
 
31b7c7a
 
 
 
533b0a8
 
 
 
 
 
eb78ab5
4b9cc62
533b0a8
4b9cc62
7a955d9
4b9cc62
7a955d9
eb78ab5
 
7a955d9
eb78ab5
533b0a8
4b9cc62
 
 
533b0a8
4b9cc62
eb78ab5
 
4b9cc62
533b0a8
 
4b9cc62
 
533b0a8
4b9cc62
7a955d9
eb78ab5
ec15dbc
c0b300b
 
4b9cc62
7a955d9
eb78ab5
7a955d9
 
 
 
4b9cc62
 
 
 
 
7a955d9
 
 
e6468b0
eb78ab5
e6468b0
 
 
 
3c79ccf
 
e6468b0
 
3c79ccf
e6468b0
 
 
 
 
 
 
4b4508d
eb78ab5
 
033a45d
eb78ab5
 
 
 
033a45d
15642e3
31384f7
15642e3
3c79ccf
31384f7
15642e3
31384f7
15642e3
31384f7
 
15642e3
31384f7
eb78ab5
078d18a
4b4508d
d2df5a7
7a955d9
078d18a
3c79ccf
d2df5a7
 
3c79ccf
 
 
7a955d9
078d18a
 
7a955d9
078d18a
 
 
 
7a955d9
3c79ccf
078d18a
 
 
ec15dbc
078d18a
7a955d9
d2df5a7
 
078d18a
 
 
7a955d9
3c79ccf
078d18a
 
 
 
 
d2df5a7
 
 
 
078d18a
 
7a955d9
 
a520e24
a234b0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c09773
eb78ab5
a234b0a
 
d8fb1f1
a234b0a
 
 
d8fb1f1
a234b0a
 
 
 
7a955d9
a234b0a
 
 
7a955d9
a234b0a
7a955d9
3c79ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb78ab5
c0b300b
4b4508d
a234b0a
4b4508d
031a705
4b9cc62
f4e2d1c
4b4508d
031a705
 
a79508a
 
 
 
 
 
 
 
7517761
 
 
 
 
 
 
 
 
b2062f5
7517761
 
 
 
 
 
 
 
 
b2062f5
7517761
 
b2062f5
7517761
 
b2062f5
ea23782
 
7517761
 
b2062f5
7517761
 
b2062f5
7517761
 
 
 
 
 
b3620b8
7517761
 
 
 
b2062f5
7517761
 
 
b2062f5
7517761
 
b2062f5
7517761
 
 
 
 
b2062f5
7517761
 
b2062f5
7517761
 
b2062f5
7517761
 
 
b2062f5
9f29203
 
 
da2abb5
 
d2df5a7
 
 
 
 
 
 
 
 
da2abb5
297e5c4
bb8d3b6
 
 
f6241b2
bb8d3b6
f6241b2
 
 
 
 
 
 
bb8d3b6
 
f6241b2
 
 
 
 
744da5a
bb8d3b6
 
 
 
 
744da5a
bb8d3b6
28443f0
744da5a
 
 
3e726a0
 
 
 
 
 
 
28443f0
3e726a0
 
ed59e54
3e726a0
744da5a
 
3e726a0
744da5a
28443f0
3e726a0
744da5a
28443f0
3e726a0
744da5a
 
 
 
28443f0
744da5a
 
28443f0
3e726a0
28443f0
 
744da5a
 
 
 
 
 
28443f0
ed59e54
bb8d3b6
 
f6241b2
da2abb5
 
 
 
 
 
297e5c4
 
 
 
da2abb5
297e5c4
 
 
da2abb5
 
 
297e5c4
f6241b2
bb8d3b6
f6241b2
da2abb5
 
f6241b2
da2abb5
297e5c4
 
 
 
 
 
 
da2abb5
 
 
 
 
 
 
f6241b2
da2abb5
198389d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297e5c4
 
bb8d3b6
297e5c4
 
 
 
da2abb5
 
 
98a6c5d
 
 
7517761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb8d3b6
7517761
 
 
 
 
 
 
 
 
 
 
b2062f5
7517761
 
98a6c5d
 
 
d2df5a7
 
 
 
98a6c5d
7517761
 
98a6c5d
 
7517761
98a6c5d
 
 
 
7517761
 
 
98a6c5d
 
7517761
98a6c5d
 
 
 
7517761
 
a234b0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a6c5d
 
 
 
 
 
 
 
 
 
 
7517761
 
 
a234b0a
 
7517761
 
98a6c5d
 
 
7517761
98a6c5d
 
 
 
 
 
 
 
7517761
 
 
3c79ccf
 
0fd380e
3c79ccf
0fd380e
4b4508d
e6468b0
3c79ccf
e6468b0
3c79ccf
e6468b0
eb78ab5
8bde1d8
4b9cc62
 
0fd380e
d2df5a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# --------------------- 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
import tempfile
import sys
from datetime import datetime,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 fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from motor.motor_asyncio import AsyncIOMotorClient
from bson import ObjectId
from bson.errors import InvalidId
import httpx
import uvicorn
import gradio as gr
from gradio import mount_gradio_app
from PIL import Image
import io

# DigitalOcean Spaces
import boto3
from botocore.client import Config
from typing import Optional

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

# --------------------- Secrets & Paths ---------------------
REPO_ID = "HariLogicgo/face_swap_models"
MODELS_DIR = "./models"
os.makedirs(MODELS_DIR, exist_ok=True)

HF_TOKEN = os.getenv("HF_TOKEN")
API_SECRET_TOKEN = os.getenv("API_SECRET_TOKEN")

DO_SPACES_REGION = os.getenv("DO_SPACES_REGION", "blr1")
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")

# NEW admin DB
ADMIN_MONGO_URL = os.getenv("ADMIN_MONGO_URL")
admin_client = AsyncIOMotorClient(ADMIN_MONGO_URL)
admin_db = admin_client.adminPanel
subcategories_col = admin_db.subcategories
media_clicks_col = admin_db.media_clicks

# OLD logs DB
MONGODB_URL = os.getenv("MONGODB_URL")
client = None
database = None

# --------------------- Download Models ---------------------
def download_models():
    logger.info("Downloading models...")
    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.")
    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()


# --------------------- 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")

# --------------------- Auth ---------------------
security = HTTPBearer()

def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):
    if credentials.credentials != API_SECRET_TOKEN:
        raise HTTPException(status_code=401, detail="Invalid or missing token")
    return credentials.credentials

# --------------------- Logging API Hits ---------------------
async def log_faceswap_hit(token: str, status: str = "success"):
    global database
    if database is None:
        return
    await database.api_logs.insert_one({
        "token": token,
        "endpoint": "/faceswap",
        "status": status,
        "timestamp": datetime.utcnow()
    })

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

def face_swap_and_enhance(src_img, tgt_img, temp_dir=None):
    try:
        with swap_lock:
            # Use a temp dir for intermediate files
            if temp_dir is None:
                temp_dir = os.path.join(tempfile.gettempdir(), f"faceswap_work_{uuid.uuid4().hex[:8]}")
            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 = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)

            src_faces = face_analysis_app.get(src_bgr)
            tgt_faces = face_analysis_app.get(tgt_bgr)
            if not src_faces or not tgt_faces:
                return None, None, "❌ Face not detected in one of the images"

            swapped_path = os.path.join(temp_dir, f"swapped_{uuid.uuid4().hex[:8]}.jpg")
            swapped_bgr = swapper.get(tgt_bgr, tgt_faces[0], src_faces[0])
            if swapped_bgr is None:
                return None, None, "❌ Face swap failed"

            cv2.imwrite(swapped_path, swapped_bgr)

            python_cmd = sys.executable if sys.executable else "python3"
            cmd = f"{python_cmd} {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_bgr = cv2.imread(final_path)
            if final_img_bgr is None:
                return None, None, "❌ Failed to read enhanced image file"
            final_img = cv2.cvtColor(final_img_bgr, cv2.COLOR_BGR2RGB)

            return final_img, final_path, ""

    except Exception as e:
        return None, None, f"❌ Error: {str(e)}"
        
def compress_image(
    image_bytes: bytes,
    max_size=(1280, 1280),   # max width/height
    quality=75               # JPEG quality (60–80 is ideal)
) -> bytes:
    """
    Compress image by resizing and lowering quality.
    Returns compressed image bytes.
    """
    img = Image.open(io.BytesIO(image_bytes)).convert("RGB")

    # Resize while maintaining aspect ratio
    img.thumbnail(max_size, Image.LANCZOS)

    output = io.BytesIO()
    img.save(
        output,
        format="JPEG",
        quality=quality,
        optimize=True,
        progressive=True
    )

    return output.getvalue()

# --------------------- 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 {"status": "healthy"}

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

from fastapi import Form
import requests
@fastapi_app.get("/test-admin-db")
async def test_admin_db():
    try:
        doc = await admin_db.list_collection_names()
        return {"ok": True, "collections": doc}
    except Exception as e:
        return {"ok": False, "error": str(e), "url": ADMIN_MONGO_URL}

@fastapi_app.post("/face-swap", dependencies=[Depends(verify_token)])
async def face_swap_api(
    source: UploadFile = File(...),
    target_category_id: str = Form(None),
    new_category_id: str = Form(None),
    user_id: Optional[str] = Form(None),
    credentials: HTTPAuthorizationCredentials = Security(security)
):
    start_time = datetime.utcnow()

    try:
        # ------------------------------------------------------------------
        # VALIDATION
        # ------------------------------------------------------------------
        # --------------------------------------------------------------
        # BACKWARD COMPATIBILITY FOR OLD ANDROID VERSIONS
        # --------------------------------------------------------------
        if target_category_id == "":
            target_category_id = None
        
        if new_category_id == "":
            new_category_id = None
        
        if user_id == "":
            user_id = None

        logger.info(f"[FaceSwap] Incoming request β†’ target_category_id={target_category_id}, new_category_id={new_category_id}, user_id={user_id}")

        if target_category_id and new_category_id:
            raise HTTPException(400, "Provide only one of new_category_id or target_category_id.")

        if not target_category_id and not new_category_id:
            raise HTTPException(400, "Either new_category_id or target_category_id is required.")

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

        # ------------------------------------------------------------------
        # CASE 1 : new_category_id β†’ MongoDB lookup
        # ------------------------------------------------------------------
        if new_category_id:

            doc = await subcategories_col.find_one({
                "asset_images._id": ObjectId(new_category_id)
            })

            if not doc:
                raise HTTPException(404, "Asset image not found in database")

            # extract correct asset
            asset = next(
                (img for img in doc["asset_images"] if str(img["_id"]) == new_category_id),
                None
            )

            if not asset:
                raise HTTPException(404, "Asset image URL not found")

            # correct URL
            target_url = asset["url"]

            # correct categoryId (ObjectId)
            #category_oid = doc["categoryId"]   # <-- DO NOT CONVERT TO STRING
            subcategory_oid = doc["_id"]
    
            # ------------------------------------------------------------------#
            # # MEDIA_CLICKS (ONLY IF user_id PRESENT)
            # ------------------------------------------------------------------#
            if user_id:
                try:
                    user_id_clean = user_id.strip()
                    if not user_id_clean:
                        raise ValueError("user_id cannot be empty")
                    try:
                        user_oid = ObjectId(user_id_clean)
                    except (InvalidId, ValueError) as e:
                        logger.error(f"Invalid user_id format: {user_id_clean}")
                        raise ValueError(f"Invalid user_id format: {user_id_clean}")
                    
                    now = datetime.utcnow()
            
                    # Normalize dates (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: Handle DAILY USAGE (BINARY, NO DUPLICATES)
                    # -------------------------------------------------
                    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 []
                    
                    # Normalize today to UTC midnight
                    today_date = datetime(now.year, now.month, now.day)
                    
                    # Build normalized date β†’ count map (THIS ENFORCES UNIQUENESS)
                    daily_map = {}
                    for entry in daily_entries:
                        d = entry["date"]
                        if isinstance(d, datetime):
                            d = datetime(d.year, d.month, d.day)
                        daily_map[d] = entry["count"]  # overwrite = no duplicates
                    
                    # Determine last recorded date
                    last_date = max(daily_map.keys()) if daily_map else today_date
                    
                    # Fill ALL missing days with count = 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 list: OLDEST β†’ NEWEST
                    final_daily_entries = [
                        {"date": d, "count": daily_map[d]}
                        for d in sorted(daily_map.keys())
                    ]
                    
                    # Keep only last 32 days
                    final_daily_entries = final_daily_entries[-32:]
                    
                    # Atomic replace
                    await media_clicks_col.update_one(
                        {"userId": user_oid},
                        {
                            "$set": {
                                "ai_edit_daily_count": final_daily_entries,
                                "updatedAt": now
                            }
                        }
                    )

                    # -------------------------------------------------
                    # STEP 3: Try updating existing subCategory
                    # -------------------------------------------------
                    update_result = await media_clicks_col.update_one(
                        {
                            "userId": user_oid,
                            "subCategories.subCategoryId": subcategory_oid
                        },
                        {
                            "$inc": {
                                "subCategories.$.click_count": 1,
                                "ai_edit_complete": 1
                            },
                            "$set": {
                                "subCategories.$.lastClickedAt": now,
                                "ai_edit_last_date": now,
                                "updatedAt": now
                            }
                        }
                    )
            
                    # -------------------------------------------------
                    # STEP 4: Push subCategory if missing
                    # -------------------------------------------------
                    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": {
                                    "subCategories": {
                                        "subCategoryId": subcategory_oid,
                                        "click_count": 1,
                                        "lastClickedAt": now
                                    }
                                }
                            }
                        )
                    
                    # -------------------------------------------------
                    # STEP 5: Sort subCategories by lastClickedAt (ascending - oldest first)
                    # -------------------------------------------------
                    user_doc = await media_clicks_col.find_one({"userId": user_oid})
                    if user_doc and "subCategories" in user_doc:
                        subcategories = user_doc["subCategories"]
                        # Sort by lastClickedAt in ascending order (oldest first)
                        # Handle missing or None dates by using datetime.min
                        subcategories_sorted = sorted(
                            subcategories,
                            key=lambda x: x.get("lastClickedAt") if x.get("lastClickedAt") is not None else datetime.min
                        )
                        # Update with sorted array
                        await media_clicks_col.update_one(
                            {"userId": user_oid},
                            {
                                "$set": {
                                    "subCategories": subcategories_sorted,
                                    "updatedAt": now
                                }
                            }
                        )
            
                    logger.info(
                        "[MEDIA_CLICK] user=%s subCategory=%s ai_edit_complete++ daily_tracked",
                        user_id,
                        str(subcategory_oid)
                    )
            
                except Exception as media_err:
                    logger.error(f"MEDIA_CLICK ERROR: {media_err}")

#         # ------------------------------------------------------------------
#         # CASE 2 : target_category_id β†’ DigitalOcean path (unchanged logic)
#         # ------------------------------------------------------------------
        if target_category_id:
            client = get_spaces_client()
            base_prefix = "faceswap/target/"
            resp = client.list_objects_v2(
                Bucket=DO_SPACES_BUCKET, Prefix=base_prefix, Delimiter="/"
            )
            
            # Extract categories from the CommonPrefixes
            categories = [p["Prefix"].split("/")[2] for p in resp.get("CommonPrefixes", [])]

            target_url = None
            
            # --- FIX STARTS HERE ---
            for category in categories:
                original_prefix = f"faceswap/target/{category}/original/"
                thumb_prefix = f"faceswap/target/{category}/thumb/" # Keep for file list check (optional but safe)
                
                # List objects in original/
                original_objects = client.list_objects_v2(
                    Bucket=DO_SPACES_BUCKET, Prefix=original_prefix
                ).get("Contents", [])

                # List objects in thumb/ (optional: for the old code's extra check)
                thumb_objects = client.list_objects_v2(
                    Bucket=DO_SPACES_BUCKET, Prefix=thumb_prefix
                ).get("Contents", [])
                
                # Extract only the filenames and filter for .png
                original_filenames = sorted([
                    obj["Key"].split("/")[-1] for obj in original_objects 
                    if obj["Key"].split("/")[-1].endswith(".png")
                ])
                thumb_filenames = [
                    obj["Key"].split("/")[-1] for obj in thumb_objects
                ]

                # Replicate the old indexing logic based on sorted filenames
                for idx, filename in enumerate(original_filenames, start=1):
                    cid = f"{category.lower()}image_{idx}"

                    # Optional: Replicate the thumb file check for 100% parity
                    # if filename in thumb_filenames and cid == target_category_id:
                    # Simpler check just on the ID, assuming thumb files are present
                    if cid == target_category_id:
                        # Construct the final target URL using the full prefix and the filename
                        target_url = f"{DO_SPACES_ENDPOINT}/{DO_SPACES_BUCKET}/{original_prefix}{filename}"
                        break
                
                if target_url:
                    break
            # --- FIX ENDS HERE ---

            if not target_url:
                raise HTTPException(404, "Target categoryId not found")
#         # ------------------------------------------------------------------
#         # DOWNLOAD TARGET IMAGE
#         # ------------------------------------------------------------------
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(target_url)
            response.raise_for_status()
            tgt_bytes = response.content

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

        if src_bgr is None or tgt_bgr is None:
            raise HTTPException(400, "Invalid image data")

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

        # ------------------------------------------------------------------
        # FACE SWAP EXECUTION
        # ------------------------------------------------------------------
        final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
        if err:
            raise HTTPException(500, err)

        with open(final_path, "rb") as f:
            result_bytes = f.read()

        result_key = f"faceswap/result/{uuid.uuid4().hex}_enhanced.png"
        result_url = upload_to_spaces(result_bytes, result_key)
        # -------------------------------------------------
        # COMPRESS IMAGE (2–3 MB target)
        # -------------------------------------------------
        compressed_bytes = compress_image(
            image_bytes=result_bytes,
            max_size=(1280, 1280),
            quality=72
        )
        
        compressed_key = f"faceswap/result/{uuid.uuid4().hex}_enhanced_compressed.jpg"
        compressed_url = upload_to_spaces(
            compressed_bytes,
            compressed_key,
            content_type="image/jpeg"
        )
        end_time = datetime.utcnow()
        response_time_ms = (end_time - start_time).total_seconds() * 1000

        if database is not None:
            await database.api_logs.insert_one({
                "endpoint": "/face-swap",
                "status": "success",
                "response_time_ms": response_time_ms,
                "timestamp": end_time
            })


        return {
            "result_key": result_key,
            "result_url": result_url,
            "Compressed_Image_URL": compressed_url
        }
        
    except Exception as e:
        end_time = datetime.utcnow()
        response_time_ms = (end_time - start_time).total_seconds() * 1000

        if database is not None:
            await database.api_logs.insert_one({
                "endpoint": "/face-swap",
                "status": "fail",
                "response_time_ms": response_time_ms,
                "timestamp": end_time,
                "error": str(e)
            })

        raise HTTPException(500, 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 ---------------------


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,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 fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
# from motor.motor_asyncio import AsyncIOMotorClient
# from bson import ObjectId
# import requests
# import uvicorn
# import gradio as gr
# from gradio import mount_gradio_app

# # DigitalOcean Spaces
# import boto3
# from botocore.client import Config
# from typing import Optional

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

# # --------------------- Secrets & Paths ---------------------
# REPO_ID = "HariLogicgo/face_swap_models"
# MODELS_DIR = "./models"
# os.makedirs(MODELS_DIR, exist_ok=True)

# HF_TOKEN = os.getenv("HF_TOKEN")
# API_SECRET_TOKEN = os.getenv("API_SECRET_TOKEN")

# DO_SPACES_REGION = os.getenv("DO_SPACES_REGION", "blr1")
# 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")

# # NEW admin DB
# ADMIN_MONGO_URL = os.getenv("ADMIN_MONGO_URL")
# admin_client = AsyncIOMotorClient(ADMIN_MONGO_URL)
# admin_db = admin_client.adminPanel
# subcategories_col = admin_db.subcategories
# media_clicks_col = admin_db.media_clicks

# # OLD logs DB
# MONGODB_URL = os.getenv("MONGODB_URL")
# client = None
# database = None

# # --------------------- Download Models ---------------------
# def download_models():
#     logger.info("Downloading models...")
#     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.")
#     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()


# # --------------------- 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")

# # --------------------- Auth ---------------------
# security = HTTPBearer()

# def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):
#     if credentials.credentials != API_SECRET_TOKEN:
#         raise HTTPException(status_code=401, detail="Invalid or missing token")
#     return credentials.credentials

# # --------------------- Logging API Hits ---------------------
# async def log_faceswap_hit(token: str, status: str = "success"):
#     global database
#     if database is None:
#         return
#     await database.api_logs.insert_one({
#         "token": token,
#         "endpoint": "/faceswap",
#         "status": status,
#         "timestamp": datetime.utcnow()
#     })

# # --------------------- 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:
#             # Use a temp dir for intermediate files
#             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 = cv2.cvtColor(tgt_img, cv2.COLOR_RGB2BGR)

#             src_faces = face_analysis_app.get(src_bgr)
#             tgt_faces = face_analysis_app.get(tgt_bgr)
#             if not src_faces or not tgt_faces:
#                 return None, None, "❌ Face not detected in one of the images"

#             swapped_path = os.path.join(temp_dir, f"swapped_{uuid.uuid4().hex[:8]}.jpg")
#             swapped_bgr = swapper.get(tgt_bgr, tgt_faces[0], src_faces[0])
#             if swapped_bgr is None:
#                 return None, None, "❌ Face swap failed"

#             cv2.imwrite(swapped_path, swapped_bgr)

#             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"}

# from fastapi import Form
# import requests
# @fastapi_app.get("/test-admin-db")
# async def test_admin_db():
#     try:
#         doc = await admin_db.list_collection_names()
#         return {"ok": True, "collections": doc}
#     except Exception as e:
#         return {"ok": False, "error": str(e), "url": ADMIN_MONGO_URL}

# @fastapi_app.post("/face-swap", dependencies=[Depends(verify_token)])
# async def face_swap_api(
#     source: UploadFile = File(...),
#     target_category_id: str = Form(None),
#     new_category_id: str = Form(None),
#     user_id: Optional[str] = Form(None),
#     credentials: HTTPAuthorizationCredentials = Security(security)
# ):
#     start_time = datetime.utcnow()

#     try:
#         # ------------------------------------------------------------------
#         # VALIDATION
#         # ------------------------------------------------------------------
#         # --------------------------------------------------------------
#         # BACKWARD COMPATIBILITY FOR OLD ANDROID VERSIONS
#         # --------------------------------------------------------------
#         if target_category_id == "":
#             target_category_id = None
        
#         if new_category_id == "":
#             new_category_id = None
        
#         if user_id == "":
#             user_id = None

#         logger.info(f"[FaceSwap] Incoming request β†’ target_category_id={target_category_id}, new_category_id={new_category_id}, user_id={user_id}")

#         if target_category_id and new_category_id:
#             raise HTTPException(400, "Provide only one of new_category_id or target_category_id.")

#         if not target_category_id and not new_category_id:
#             raise HTTPException(400, "Either new_category_id or target_category_id is required.")

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

#         # ------------------------------------------------------------------
#         # CASE 1 : new_category_id β†’ MongoDB lookup
#         # ------------------------------------------------------------------
#         if new_category_id:

#             doc = await subcategories_col.find_one({
#                 "asset_images._id": ObjectId(new_category_id)
#             })

#             if not doc:
#                 raise HTTPException(404, "Asset image not found in database")

#             # extract correct asset
#             asset = next(
#                 (img for img in doc["asset_images"] if str(img["_id"]) == new_category_id),
#                 None
#             )

#             if not asset:
#                 raise HTTPException(404, "Asset image URL not found")

#             # correct URL
#             target_url = asset["url"]

#             # correct categoryId (ObjectId)
#             #category_oid = doc["categoryId"]   # <-- DO NOT CONVERT TO STRING
#             subcategory_oid = doc["_id"]
    
#             # ------------------------------------------------------------------#
#             # # MEDIA_CLICKS (ONLY IF user_id PRESENT)
#             # ------------------------------------------------------------------#
#             if user_id:
#                 try:
#                     user_oid = ObjectId(user_id.strip())
#                     now = datetime.utcnow()
            
#                     # Normalize dates (UTC midnight)
#                     today_date = datetime(now.year, now.month, now.day)
#                     yesterday_date = today_date - timedelta(days=1)
            
#                     # -------------------------------------------------
#                     # 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: Handle DAILY USAGE (BINARY, NO DUPLICATES)
#                     # -------------------------------------------------
#                     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 []
                    
#                     # Normalize today to UTC midnight
#                     today_date = datetime(now.year, now.month, now.day)
                    
#                     # Build normalized date β†’ count map (THIS ENFORCES UNIQUENESS)
#                     daily_map = {}
#                     for entry in daily_entries:
#                         d = entry["date"]
#                         if isinstance(d, datetime):
#                             d = datetime(d.year, d.month, d.day)
#                         daily_map[d] = entry["count"]  # overwrite = no duplicates
                    
#                     # Determine last recorded date
#                     last_date = max(daily_map.keys()) if daily_map else today_date
                    
#                     # Fill ALL missing days with count = 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 list: OLDEST β†’ NEWEST
#                     final_daily_entries = [
#                         {"date": d, "count": daily_map[d]}
#                         for d in sorted(daily_map.keys())
#                     ]
                    
#                     # Keep only last 32 days
#                     final_daily_entries = final_daily_entries[-32:]
                    
#                     # Atomic replace
#                     await media_clicks_col.update_one(
#                         {"userId": user_oid},
#                         {
#                             "$set": {
#                                 "ai_edit_daily_count": final_daily_entries,
#                                 "updatedAt": now
#                             }
#                         }
#                     )

#                     # -------------------------------------------------
#                     # STEP 3: Try updating existing subCategory
#                     # -------------------------------------------------
#                     update_result = await media_clicks_col.update_one(
#                         {
#                             "userId": user_oid,
#                             "subCategories.subCategoryId": subcategory_oid
#                         },
#                         {
#                             "$inc": {
#                                 "subCategories.$.click_count": 1,
#                                 "ai_edit_complete": 1
#                             },
#                             "$set": {
#                                 "subCategories.$.lastClickedAt": now,
#                                 "ai_edit_last_date": now,
#                                 "updatedAt": now
#                             }
#                         }
#                     )
            
#                     # -------------------------------------------------
#                     # STEP 4: Push subCategory if missing
#                     # -------------------------------------------------
#                     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": {
#                                     "subCategories": {
#                                         "subCategoryId": subcategory_oid,
#                                         "click_count": 1,
#                                         "lastClickedAt": now
#                                     }
#                                 }
#                             }
#                         )
            
#                     logger.info(
#                         "[MEDIA_CLICK] user=%s subCategory=%s ai_edit_complete++ daily_tracked",
#                         user_id,
#                         str(subcategory_oid)
#                     )
            
#                 except Exception as media_err:
#                     logger.error(f"MEDIA_CLICK ERROR: {media_err}")

# #         # ------------------------------------------------------------------
# #         # CASE 2 : target_category_id β†’ DigitalOcean path (unchanged logic)
# #         # ------------------------------------------------------------------
#         if target_category_id:
#             client = get_spaces_client()
#             base_prefix = "faceswap/target/"
#             resp = client.list_objects_v2(
#                 Bucket=DO_SPACES_BUCKET, Prefix=base_prefix, Delimiter="/"
#             )
            
#             # Extract categories from the CommonPrefixes
#             categories = [p["Prefix"].split("/")[2] for p in resp.get("CommonPrefixes", [])]

#             target_url = None
            
#             # --- FIX STARTS HERE ---
#             for category in categories:
#                 original_prefix = f"faceswap/target/{category}/original/"
#                 thumb_prefix = f"faceswap/target/{category}/thumb/" # Keep for file list check (optional but safe)
                
#                 # List objects in original/
#                 original_objects = client.list_objects_v2(
#                     Bucket=DO_SPACES_BUCKET, Prefix=original_prefix
#                 ).get("Contents", [])

#                 # List objects in thumb/ (optional: for the old code's extra check)
#                 thumb_objects = client.list_objects_v2(
#                     Bucket=DO_SPACES_BUCKET, Prefix=thumb_prefix
#                 ).get("Contents", [])
                
#                 # Extract only the filenames and filter for .png
#                 original_filenames = sorted([
#                     obj["Key"].split("/")[-1] for obj in original_objects 
#                     if obj["Key"].split("/")[-1].endswith(".png")
#                 ])
#                 thumb_filenames = [
#                     obj["Key"].split("/")[-1] for obj in thumb_objects
#                 ]

#                 # Replicate the old indexing logic based on sorted filenames
#                 for idx, filename in enumerate(original_filenames, start=1):
#                     cid = f"{category.lower()}image_{idx}"

#                     # Optional: Replicate the thumb file check for 100% parity
#                     # if filename in thumb_filenames and cid == target_category_id:
#                     # Simpler check just on the ID, assuming thumb files are present
#                     if cid == target_category_id:
#                         # Construct the final target URL using the full prefix and the filename
#                         target_url = f"{DO_SPACES_ENDPOINT}/{DO_SPACES_BUCKET}/{original_prefix}{filename}"
#                         break
                
#                 if target_url:
#                     break
#             # --- FIX ENDS HERE ---

#             if not target_url:
#                 raise HTTPException(404, "Target categoryId not found")
# #         # ------------------------------------------------------------------
# #         # DOWNLOAD TARGET IMAGE
# #         # ------------------------------------------------------------------
#         tgt_bytes = requests.get(target_url).content

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

#         if src_bgr is None or tgt_bgr is None:
#             raise HTTPException(400, "Invalid image data")

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

#         # ------------------------------------------------------------------
#         # FACE SWAP EXECUTION
#         # ------------------------------------------------------------------
#         final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
#         if err:
#             raise HTTPException(500, err)

#         with open(final_path, "rb") as f:
#             result_bytes = f.read()

#         result_key = f"faceswap/result/{uuid.uuid4().hex}_enhanced.png"
#         result_url = upload_to_spaces(result_bytes, result_key)
#         end_time = datetime.utcnow()
#         response_time_ms = (end_time - start_time).total_seconds() * 1000

#         if database is not None:
#             await database.api_logs.insert_one({
#                 "endpoint": "/face-swap",
#                 "status": "success",
#                 "response_time_ms": response_time_ms,
#                 "timestamp": end_time
#             })


#         return {
#             "result_key": result_key,
#             "result_url": result_url
#         }
        
#     except Exception as e:
#         end_time = datetime.utcnow()
#         response_time_ms = (end_time - start_time).total_seconds() * 1000

#         if database is not None:
#             await database.api_logs.insert_one({
#                 "endpoint": "/face-swap",
#                 "status": "fail",
#                 "response_time_ms": response_time_ms,
#                 "timestamp": end_time,
#                 "error": str(e)
#             })

#         raise HTTPException(500, 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)