File size: 54,314 Bytes
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
974774f
43a520c
 
 
 
 
112cef0
43a520c
 
112cef0
 
43a520c
 
 
 
 
 
 
 
 
 
ce4ee40
43a520c
53d62f2
d4cf293
b808a53
 
43a520c
 
 
 
da3749a
 
 
 
 
501c814
 
43a520c
b7c9de4
911e2e6
02d4619
 
43a520c
0973c3d
43a520c
e863fc4
aaa8cb2
9ecb143
 
43a520c
 
 
 
11ad08f
 
9ecb143
43a520c
28c21ce
 
501c814
28c21ce
 
43a520c
 
 
8d21336
1cb797c
9ecb143
77a5c10
1cafdf9
 
9946154
fd36ba6
28c21ce
974774f
11ad08f
28c21ce
 
 
 
 
 
fd36ba6
e863fc4
28c21ce
11ad08f
43a520c
501c814
 
 
 
9ecb143
 
1a5d0dc
43a520c
1cb797c
 
48b87b0
 
 
 
b808a53
 
 
 
 
 
 
 
 
48b87b0
 
23cad14
 
 
 
 
 
 
 
 
43a520c
23cad14
43a520c
 
 
 
 
 
 
501c814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e823380
 
 
 
501c814
 
 
 
 
 
 
 
 
 
879828f
501c814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f593d1d
501c814
a281fbe
67992d4
0b98925
67992d4
 
0b98925
a281fbe
67992d4
501c814
0b98925
 
 
 
 
67992d4
c77d359
 
 
0b98925
 
 
 
 
67992d4
c77d359
a281fbe
 
0b98925
a281fbe
3d10576
0b98925
67992d4
 
309ab24
0b98925
309ab24
 
 
 
 
 
 
 
172d18c
c77d359
 
 
0b98925
309ab24
 
 
 
 
c77d359
309ab24
aaa8cb2
 
 
 
a281fbe
 
67992d4
43a520c
 
501c814
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a281fbe
43a520c
0b98925
43a520c
 
 
0b98925
43a520c
 
0b98925
c77d359
 
aaa8cb2
c77d359
43a520c
aaa8cb2
 
 
 
43a520c
a281fbe
0b98925
a281fbe
43a520c
0b98925
43a520c
 
0b98925
43a520c
 
 
 
501c814
0b98925
43a520c
5a04c21
a281fbe
43a520c
0b98925
c77d359
 
 
0b98925
43a520c
0b98925
43a520c
0b98925
43a520c
c77d359
a281fbe
 
0b98925
a281fbe
43a520c
0b98925
43a520c
 
efb3aec
9ecb143
efb3aec
 
 
 
 
 
 
 
 
 
c77d359
43a520c
5062335
a281fbe
5062335
 
 
 
0b98925
f72ea12
f3d65c2
 
 
 
0973c3d
f3d65c2
 
0973c3d
f3d65c2
 
 
 
 
9ecb143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11ad08f
9ecb143
 
c77d359
43a520c
0b98925
43a520c
 
 
 
0b98925
 
 
 
43a520c
 
 
 
 
 
 
 
c77d359
 
 
43a520c
 
 
 
 
c77d359
570137d
 
43a520c
c77d359
43a520c
0b98925
43a520c
 
 
0b98925
 
43a520c
0b98925
43a520c
 
 
 
 
 
 
 
 
 
c77d359
 
 
43a520c
 
c77d359
43a520c
 
 
 
 
d681cd0
 
 
 
 
2256f29
f0a24e7
48b87b0
d681cd0
ae6eb7d
 
f0a24e7
ae6eb7d
d681cd0
d8c5ebf
0b9435b
d8c5ebf
0b9435b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8c5ebf
 
0b9435b
 
 
d8c5ebf
0b9435b
d8c5ebf
9ecb143
 
 
 
48b87b0
9ecb143
48b87b0
9ecb143
 
 
 
0b9435b
48b87b0
9ecb143
48b87b0
9ecb143
43e59d3
 
 
 
 
 
 
 
 
 
 
 
48b87b0
 
43e59d3
48b87b0
43e59d3
da3749a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7838dbc
70b712d
 
 
7838dbc
1cb797c
 
 
 
 
 
7838dbc
1cb797c
 
 
b808a53
1cb797c
7838dbc
beca021
 
7838dbc
1cb797c
 
 
9ecb143
 
 
 
 
 
 
 
 
 
 
 
 
 
b808a53
9ecb143
 
 
 
 
 
b808a53
9ecb143
f3d65c2
 
 
48b87b0
9ecb143
11ad08f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b808a53
11ad08f
 
 
 
 
 
 
 
 
 
 
b808a53
11ad08f
 
 
 
 
48b87b0
11ad08f
9ecb143
 
 
 
 
 
 
 
 
 
 
 
 
 
b808a53
9ecb143
 
 
 
 
 
b808a53
9ecb143
f3d65c2
 
 
48b87b0
9ecb143
 
 
 
 
 
 
 
 
 
 
b808a53
9ecb143
 
 
 
 
 
b808a53
9ecb143
f3d65c2
 
 
 
9ecb143
c77d359
0b98925
c97e3fc
0b98925
 
c97e3fc
 
ae6eb7d
c97e3fc
 
ae6eb7d
c97e3fc
0b98925
c97e3fc
 
ae6eb7d
c97e3fc
 
ae6eb7d
0b98925
43e59d3
f16b37f
 
f4a19a2
f16b37f
 
974774f
5d77efe
 
 
 
da2c06c
f4a19a2
5d77efe
 
 
 
 
 
 
 
 
 
 
d8781d0
48b87b0
974774f
 
 
 
 
48b87b0
974774f
 
48b87b0
974774f
 
 
 
 
 
5d77efe
 
 
 
da2c06c
5d77efe
 
 
 
 
 
 
 
 
 
 
d8781d0
48b87b0
43e59d3
c77d359
0b98925
 
 
 
fd36ba6
 
8e64de4
fd36ba6
 
 
 
0b98925
fd36ba6
 
8e64de4
fd36ba6
 
 
 
48b87b0
fd36ba6
b808a53
fd36ba6
02d4619
 
 
 
 
 
 
 
 
 
 
 
 
 
e248e87
 
02d4619
c77d359
dc7493e
f0280ed
 
 
 
 
 
879828f
5de4d86
879828f
70b562d
45c626f
70b562d
 
 
e823380
70b562d
879828f
 
 
e846e9b
 
879828f
 
ae6eb7d
 
879828f
 
 
 
 
 
 
 
 
 
 
 
 
 
e863fc4
879828f
 
 
 
 
 
ae6eb7d
e863fc4
c77d359
21a37fb
0b98925
21a37fb
 
 
 
3c64daa
21a37fb
 
 
 
0b98925
21a37fb
 
 
 
 
 
48b87b0
21a37fb
b808a53
21a37fb
38374b1
28c21ce
38374b1
28c21ce
 
38374b1
28c21ce
38374b1
28c21ce
 
 
 
 
 
 
 
38374b1
 
 
28c21ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38374b1
28c21ce
38374b1
28c21ce
 
 
 
 
 
 
 
 
 
 
 
 
38374b1
28c21ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38374b1
 
43a520c
38374b1
43a520c
 
 
 
 
 
 
 
 
 
38374b1
 
43a520c
38374b1
43a520c
 
 
 
 
 
 
 
 
38374b1
 
43a520c
 
38374b1
 
 
 
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48b87b0
ee74014
9946154
ee74014
9946154
 
48b87b0
9946154
 
 
48b87b0
9946154
48b87b0
9946154
38374b1
ee74014
 
 
67992d4
43a520c
67992d4
43a520c
 
 
 
 
 
 
 
ee74014
cf13354
 
 
 
 
ee74014
cf13354
 
 
 
 
 
 
43a520c
 
 
38374b1
ee74014
43a520c
 
ee74014
 
 
43a520c
 
ee74014
 
43a520c
 
 
 
ee74014
 
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee74014
 
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38374b1
 
 
43a520c
570137d
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38374b1
52a1d3d
1cafdf9
38374b1
43a520c
 
67992d4
43a520c
 
 
 
 
38374b1
43a520c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67992d4
43a520c
08b5cce
52a1d3d
08b5cce
52a1d3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08b5cce
52a1d3d
 
 
 
 
 
 
 
 
43a520c
 
08b5cce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43a520c
 
08b5cce
 
 
 
 
 
 
 
 
 
 
 
 
43a520c
 
08b5cce
 
 
 
 
 
 
 
 
 
 
 
 
43a520c
 
08b5cce
 
 
 
 
 
 
 
 
 
 
 
 
43a520c
 
08b5cce
 
 
 
 
 
 
 
 
 
 
 
 
43a520c
 
08b5cce
 
 
 
 
 
 
 
 
 
 
 
 
d4cf293
 
 
 
 
 
b808a53
 
 
 
 
 
 
 
 
 
 
d4cf293
 
 
 
 
02d4619
d4cf293
 
 
 
 
 
 
 
 
 
 
b808a53
d8c5ebf
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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020-2023 (c) Randy W @xtdevs, @xtsea
#
# from : https://github.com/TeamKillerX
# Channel : @RendyProjects
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import requests
import json
import base64
import re
import uvicorn
import os
import shutil
import random
import tempfile
import io
import openai
from io import BytesIO
from datetime import datetime as dt
from dotenv import load_dotenv
from bs4 import BeautifulSoup

from typing import *
from typing_extensions import Annotated
from typing import Annotated, Union
from typing import Optional, List, Dict, Any

from pydantic import BaseModel
from base64 import b64decode as kc
from base64 import b64decode
from random import choice
from gpytranslate import SyncTranslator
from httpx import AsyncClient
from telegraph import Telegraph, upload_file
from pathlib import Path
from serpapi import GoogleSearch

from fastapi import FastAPI, UploadFile, File, Response
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException, status
from fastapi.openapi.utils import get_openapi
from fastapi.responses import StreamingResponse, JSONResponse, FileResponse
from fastapi import Request, Header
from fastapi import Body, Query
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

import g4f
from g4f.client import Client as BingClient
from g4f.cookies import set_cookies
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini

from pymongo import MongoClient

from RyuzakiLib.hackertools.chatgpt import RendyDevChat
from RyuzakiLib.hackertools.gemini import GeminiLatest
from RyuzakiLib.hackertools.openai_api import OpenAiToken
from RyuzakiLib.hackertools.huggingface import BetaRag

from RyuzakiLib.mental import BadWordsList
from RyuzakiLib.system import System

from bardapi import Bard
from models import *
from gpytranslate import SyncTranslator

import logging
import functions as code

logging.basicConfig(level=logging.ERROR)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

load_dotenv()

# Database url
MONGO_URL = os.environ["MONGO_URL"]

# source url
SOURCE_UNSPLASH_URL = os.environ["SOURCE_UNSPLASH_URL"]
SOURCE_OCR_URL = os.environ["SOURCE_OCR_URL"]
SOURCE_ALPHA_URL = os.environ["SOURCE_ALPHA_URL"]
SOURCE_OPENDALLE_URL = os.environ["SOURCE_OPENDALLE_URL"]
SOURCE_DALLE3XL_URL = os.environ["SOURCE_DALLE3XL_URL"]
SOURCE_ANIME_STYLED_URL = os.environ["SOURCE_ANIME_STYLED_URL"]
SOURCE_WAIFU_URL = os.environ["SOURCE_WAIFU_URL"]
SOURCE_TIKTOK_WTF_URL = os.environ["SOURCE_TIKTOK_WTF_URL"]
SOURCE_TIKTOK_TECH_URL = os.environ["SOURCE_TIKTOK_TECH_URL"]
SOURCE_WHAT_GAY_URL = os.environ["SOURCE_WHAT_GAY_URL"]
SOURCE_ASSISTANT_GOOGLE_AI = os.environ["SOURCE_ASSISTANT_GOOGLE_AI"]
SOURCE_MONITOR_URL = os.environ["SOURCE_MONITOR_URL"]
SOURCE_OPENAI_ACCESS_URL = os.environ["SOURCE_OPENAI_ACCESS_URL"]
SOURCE_PICSART_URL = os.environ["SOURCE_PICSART_URL"]

# api keys
REVERSE_IMAGE_API = os.environ["REVERSE_IMAGE_API"]
OCR_API_KEY = os.environ["OCR_API_KEY"]
ONLY_DEVELOPER_API_KEYS = os.environ["ONLY_DEVELOPER_API_KEYS"]
HUGGING_TOKEN = os.environ["HUGGING_TOKEN"]
ASSISTANT_GOOGLE_API_KEYS = os.environ["ASSISTANT_GOOGLE_API_KEYS"]
COOKIE_BARD_TOKEN = os.environ["COOKIE_BARD_TOKEN"]
MONITOR_API_KEYS = os.environ["MONITOR_API_KEYS"]
PICSART_API_KEY = os.environ["PICSART_API_KEY"]

client_mongo = MongoClient(MONGO_URL)
db = client_mongo["tiktokbot"]
collection = db["users"]

trans = SyncTranslator()

app = FastAPI(docs_url=None, redoc_url="/")

timeout = 100

contact_support = """
We are aware that AI is currently offline. This seems to be caused by the API
We are investigating and doing our best to get things back online as soon as possible. Thank you for your patience

~ Contact Support @xtdevs
"""

internal_error = """
There has been an Internal error. We are aware of this error and notice that it can be
caused by your search terms being to explict, too confusing, or it can be caused by the API.
Please modify your search terms and/or try again later thank you for your understanding.

~ @xtdevs Team
"""

def get_all_api_keys():
    user = collection.find({})
    api_keys = []
    for x in user:
        api_key = x.get("ryuzaki_api_key")
        if api_key:
            api_keys.append(api_key)
    return api_keys

def validate_api_key(api_key: str = Header(...)):
    USERS_API_KEYS = get_all_api_keys()
    if api_key not in USERS_API_KEYS:
        raise HTTPException(status_code=401, detail="Invalid API key")

def validate_api_key_only_devs(api_key: str = Header(...)):
    if api_key not in ONLY_DEVELOPER_API_KEYS:
        raise HTTPException(status_code=401, detail="Invalid API key")

RAMDOM_STATUS = [
    "civilian",
    "wanted",
    "undercover",
    "rogue_agent",
    "innocent",
    "fugitive",
    "covert_operator"
]

def remove_sibyl_system_banned(user_id):
    update_doc = {
        "sibyl_ban": None,
        "reason_sibyl": None,
        "is_banned_sibly": None,
        "date_joined_sib": None,
        "sibyl_userid": None
    }
    return collection.update_one({"user_id": user_id}, {"$unset": update_doc}, upsert=True)

def new_sibyl_system_banned(user_id, name, reason, date_joined):
    update_doc = {
        "sibyl_ban": name,
        "reason_sibyl": reason,
        "is_banned_sibly": True,
        "date_joined_sib": date_joined,
        "sibyl_userid": user_id
    }
    return collection.update_one({"user_id": user_id}, {"$set": update_doc}, upsert=True)

def cybersecuritydb(user_id, mongo_url):
    update_doc = {"mongodb": mongo_url}
    return collection.update_one({"user_id": user_id}, {"$set": update_doc}, upsert=True)

def get_sibyl_system_banned(user_id):
    user = collection.find_one({"user_id": user_id})
    if user:
        sibyl_name = user.get("sibyl_ban")
        reason = user.get("reason_sibyl")
        is_banned = user.get("is_banned_sibly")
        date_joined = user.get("date_joined_sib")
        sibyl_user_id = user.get("sibyl_userid")
        return sibyl_name, reason, is_banned, date_joined, sibyl_user_id
    else:
        return None

def get_all_banned():
    banned_users = []

    users = collection.find({})

    for user_id in users:
        reason = user_id.get("reason_sibyl")
        user_id = user_id.get("sibyl_userid")
        banned_users.append({"user_id": user_id, "reason": reason})
    return banned_users

def new_profile_clone(
    user_id,
    first_name,
    last_name=None,
    profile_id=None,
    bio=None
):
    update_doc = {
        "first_name_2": first_name,
        "last_name_2": last_name,
        "profile_id_2": profile_id,
        "bio_2": bio
    }
    collection.update_one({"user_id": user_id}, {"$set": update_doc}, upsert=True)

def get_profile_clone(user_id):
    user = collection.find_one({"user_id": user_id})
    if user:
        first_name = user.get("first_name_2")
        last_name = user.get("last_name_2")
        profile_id = user.get("profile_id_2")
        bio = user.get("bio_2")
        return first_name, last_name, profile_id, bio
    else:
        return None

@app.post("/ryuzaki/profile-clone", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def profile_clone(
    item: ProfileClone,
    api_key: None = Depends(validate_api_key)
):
    if item.user_id == 1191668125:
        return SuccessResponse(status="False", randydev={"message": "Only Developer."})
    try:
        new_profile_clone(
            user_id=item.user_id,
            first_name=item.first_name,
            last_name=item.last_name,
            profile_id=item.profile_id,
            bio=item.bio
        )
        return SuccessResponse(
            status="True",
            randydev={
                "user_id": item.user_id,
                "first_name": item.first_name,
                "last_name": item.last_name,
                "profile_id": item.profile_id,
                "bio": item.bio
            }
        )
    except Exception:
        return SuccessResponse(status="False", randydev={"message": "Internal server error."})

@app.get("/ryuzaki/get-profile-clone", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def get_profile_(
    item: GetProfileClone,
    api_key: None = Depends(validate_api_key)
):
    try:
        first_name, last_name, profile_id, bio = get_profile_clone(item.user_id)
        if last_name is None:
            last_name_str = ""
        else:
            last_name_str = last_name
        if bio is None:
            bio_str = ""
        else:
            bio_str = bio
        if first_name and profile_id:
            return SuccessResponse(
                status="True",
                randydev={
                    "user_id": item.user_id,
                    "first_name": first_name,
                    "last_name": last_name_str,
                    "profile_id": profile_id,
                    "bio": bio_str
                }
            )
        else:
            return SuccessResponse(
                status="False",
                randydev={"message": "Not found user"}
            )
    except Exception:
        return SuccessResponse(status="False", randydev={"message": "Internal server error."})

@app.get("/ryuzaki/getbanlist")
def sibyl_get_all_banlist():
    banned_users = get_all_banned()
    return {
        "status": "True",
        "randydev": {
            "results": banned_users
        }
    }

@app.get("/ryuzaki/blacklist-words")
def blacklist_words():
    try:
        BLACKLIST_WORDS = BadWordsList()
        results_all = BLACKLIST_WORDS.banned_by_google(file_txt="banned_by_google.txt", storage=True)
        return {"status": "true", "results": results_all}
    except Exception as e:
        return {"status": "false", "message": f"Internal server error: {str(e)}"}

@app.delete("/ryuzaki/sibyldel", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def sibyl_system_delete(
    item: SibylSystemDel,
    api_key: None = Depends(validate_api_key_only_devs)
):
    try:
        _, _, _, _, sibyl_user_id = get_sibyl_system_banned(item.user_id)

        if sibyl_user_id:
            remove_sibyl_system_banned(item.user_id)
            return SuccessResponse(
                status="True",
                randydev={"message": f"Successfully removed {item.user_id} from the Sibyl ban list"}
            )
        else:
            return SuccessResponse(
                status="False",
                randydev={"message": "Not Found UserID"}
            )
    except Exception as e:
        return SuccessResponse(status="False", randydev={"message": "Internal server error."})

@app.post("/ryuzaki/sibylban", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def sibyl_system_ban(
    item: SibylSystemBan,
    api_key: None = Depends(validate_api_key)
):
    if item.user_id == 1191668125:
        return {"status": "false", "message": "Only Developer"}

    try:
        date_joined = str(dt.now())
        sibyl_ban = random.choice(RAMDOM_STATUS)
        _, _, is_banned, _, sibyl_user_id = get_sibyl_system_banned(item.user_id)

        if sibyl_user_id is not None and is_banned:
            return SuccessResponse(status="False", randydev={"message": "User is already banned."})

        new_sibyl_system_banned(item.user_id, sibyl_ban, item.reason, date_joined)
        return SuccessResponse(
            status="True",
            randydev={
                "user_id": item.user_id,
                "sibyl_name": sibyl_ban,
                "reason": item.reason,
                "date_joined": date_joined,
                "message": f"Successfully banned {item.user_id} from the Sibyl ban list."
            }
        )
    except Exception:
        return SuccessResponse(status="False", randydev={"message": "Internal server error."})

@app.get("/ryuzaki/sibyl", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def sibyl_system(
    item: SibylSystem,
    api_key: None = Depends(validate_api_key)
):
    sibyl_result = get_sibyl_system_banned(item.user_id)
    if sibyl_result:
        sibyl_name, reason, is_banned, date_joined, sibyl_user_id = sibyl_result
        return SuccessResponse(
            status="True",
            randydev={
                "sibyl_name": sibyl_name,
                "reason": reason,
                "is_banned": is_banned,
                "date_joined": date_joined,
                "sibyl_user_id": sibyl_user_id
            }
        )
    else:
        return SuccessResponse(
            status="False",
            randydev={
                "message": "Not found user"
            }
        )

@app.get("/ryuzaki/pypi-search", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def pypi_search(
    item: TextCustom,
):
    try:
        response = System.show(f"pip3 show {item.query}")
        return SuccessResponse(
            status="True",
            randydev={"results": response})
    except:
        return SuccessResponse(
            status="True",
            randydev={"message": "Error not responding"})

@app.get("/ryuzaki/translate", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def get_translate(
    item: TranslateCustom,
):
    try:
        source = trans.detect(item.text)
        translation = trans(item.text, sourcelang=source, targetlang=item.setlang)
        return SuccessResponse(
            status="True",
            randydev={
                "translation": translation.text,
                "translation_original": item.text
            }
        )
    except:
        return SuccessResponse(
            status="False",
            randydev={"message": "Error not responding"})

@app.get("/ryuzaki/reverse", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def google_reverse(
    item: GoogleReverse,
    api_key: None = Depends(validate_api_key)
):
    params = {
        "api_key": REVERSE_IMAGE_API,
        "engine": item.engine,
        "image_url": item.image_url,
        "hl": item.language,
        "gl": item.google_lang
    }
    try:
        search = GoogleSearch(params)
        results = search.get_dict()
        link = results["search_metadata"]["google_reverse_image_url"]
        total_time_taken = results["search_metadata"]["total_time_taken"]
        create_at = results["search_metadata"]["created_at"]
        processed_at = results["search_metadata"]["processed_at"]
        return SuccessResponse(
            status="True",
            randydev={
                "link": link,
                "total_time_taken": total_time_taken,
                "create_at": create_at,
                "processed_at": processed_at
            }
        )
    except Exception:
        return {"status": "false", "message": "Internal server error"}

@app.get("/ryuzaki/ocr", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def ocr_space_url(
    item: OrcSpaceUrl,
    api_key: None = Depends(validate_api_key)
):
    payload = {
        "url": item.url,
        "isOverlayRequired": item.overlay,
        "apikey": OCR_API_KEY,
        "language": item.language
    }
    try:
        response = requests.post(SOURCE_OCR_URL, data=payload)
        response.raise_for_status()
        test_url = response.content.decode()
    except requests.exceptions.RequestException as e:
        return f"Error: {str(e)}"
    try:
        parsed_response = json.loads(test_url)
        if "ParsedResults" in parsed_response and len(parsed_response["ParsedResults"]) > 0:
            return SuccessResponse(
                status="True",
                randydev={
                    "text": parsed_response["ParsedResults"][0]["ParsedText"]
                }
            )
        else:
            return {"status": "false", "message": "Error response."}
    except (json.JSONDecodeError, KeyError):
        return "Error parsing the OCR response."

@app.get("/ryuzaki/nochatgpt", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def no_chatgpt(query: str=None):
    try:
        url = "http://216.98.10.228:5000"
        api_method = f"{url}/gpt?ask={query}"
        response = requests.get(api_method)
        if response.status_code != 200:
            return SuccessResponse(status="False", randydev={"message": contact_support})
        return SuccessResponse(status="True", randydev={"message": response.text})
    except requests.exceptions.ConnectTimeout:
        return SuccessResponse(status="False", randydev={"message": contact_support})
    except Exception as e:
        return SuccessResponse(status="False", randydev={"message": contact_support})

@app.post("/ryuzaki/chatgpt-old", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def chatgpt_olds(item: ChatgptCustom):
    try:
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Accept-Language": "en",
            "Connection": "keep-alive",
            "Origin": "https://remix.ethereum.org/",
            "Referer": "https://remix.ethereum.org/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134"
        }
        payload = {"prompt": item.query}
        type_urls = "openai-gpt"
        url = f"https://{type_urls}.remixproject.org"
        response = requests.post(url, data=json.dumps(payload), headers=headers, timeout=50000)
        if response.status_code != 200:
            return SuccessResponse(status="False", randydev={"message": contact_support})
        return SuccessResponse(status="True", randydev={"message": response.json()["choices"][0]["message"]["content"]})
    except requests.exceptions.ConnectTimeout:
        return SuccessResponse(status="False", randydev={"message": contact_support})
    except Exception as e:
        return SuccessResponse(status="False", randydev={"message": contact_support})

@app.get("/ryuzaki/freechatgpt-beta", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def free_chatgpt4_beta(item: ChatgptCustom):
    try:
        response = RendyDevChat(item.query).get_response_beta(joke=True)
        return SuccessResponse(status="True", randydev={"message": response})
    except:
        return SuccessResponse(status="False", randydev={"message": contact_support})

@app.get("/ryuzaki/freechatgpt-bing", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def free_chatgpt4_bing(item: ChatgptCustom):
    try:
        response = RendyDevChat(item.query).get_response_bing(bing=True)
        return SuccessResponse(status="True", randydev={"message": response})
    except:
        return SuccessResponse(status="False", randydev={"message": contact_support})

@app.post("/ryuzaki/ai", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def ryuzaki_ai(
    item: RyuzakiAi,
    api_key: None = Depends(validate_api_key)
):
    try:
        response_data = code.ryuzaki_ai_text(item.text)

        if isinstance(response_data, list) and len(response_data) > 0:
            first_result = response_data[0]
            if "generated_text" in first_result:
                message = first_result["generated_text"]
                return SuccessResponse(status="True", randydev={"ryuzaki_text": message})
        return SuccessResponse(status="False", randydev={"message": contact_support})
    except Exception:
        return SuccessResponse(status="False", randydev={"message": contact_support})


BingImages = BingClient()

@app.post("/ryuzaki/dall-e-3")
def bing_dalle(item: BingDalle, api_key: None = Depends(validate_api_key)):
    try:        
        set_cookies(
            ".bing.com",
            {
                "_U": item.cookie
            },
        )
    except requests.exceptions.RequestException:
        raise HTTPException(status_code=500, detail="Invalid cookie string, check your cookie string and try again")

    try:
        response = BingImages.images.generate(
            prompt=item.prompt,
            model=item.model,
        )
        return SuccessResponse(status="True", randydev={"data": response.data[0].url})

    except BaseException as e:
        return SuccessResponse(status="False", randydev={"data": f"Error: {e}"})

def get_image_urls(query):
    headers = {"accept":"application/json", "Content-Type": "application/json"}
    response = requests.get("https://ufoptg-ufop-api.hf.space/dall-e-3/prompt=" + query, headers=headers).json()
    return [response[f"S{i}-Image"] for i in range(1, 5)]

@app.post("/ryuzaki/dalle3xl")
def dalle_3xl(
    item: Dalle3XL,
    api_key: None = Depends(validate_api_key)
):
    try:
        x_image = get_image_urls(item.query)
    except Exception:
        raise HTTPException(
            status_code=500,
            detail=contact_support
        )
    if x_image:
        return SuccessResponse(
            status="True",
            randydev={"url": x_image})
    else:
        return SuccessResponse(status="False", randydev={"data": contact_support})

@app.post("/ryuzaki/opendalle")
def open_dalle(
    item: OpenDalle,
    api_key: None = Depends(validate_api_key)
):
    API_URL = SOURCE_OPENDALLE_URL
    try:
        payload = {"inputs": item.query}
        headers = {"Authorization": f"Bearer {HUGGING_TOKEN}"}
        response = requests.post(API_URL, headers=headers, json=payload)
        response.raise_for_status()
    except requests.exceptions.RequestException:
        raise HTTPException(
            status_code=500,
            detail=internal_error
        )
    try:
        encoded_string = base64.b64encode(response.content).decode("utf-8")
    except Exception:
        raise HTTPException(
            status_code=500,
            detail=contact_support
        )
    if encoded_string:
        return SuccessResponse(status="True", randydev={"data": encoded_string})
    else:
        return SuccessResponse(status="False", randydev={"data": contact_support})

@app.post("/ryuzaki/picsart-pro")
def Picsart_Pro(
    item: Picsart,
    api_key: None = Depends(validate_api_key)
):
    API_URL = SOURCE_PICSART_URL
    try:
        if not os.path.exists(item.image_path):
            raise HTTPException(status_code=400, detail="Image file not found")

        files = {"image": ("brosur.png", open(item.image_path, "rb"), "image/png")}
        payload = {"format": "PNG", "output_type": "cutout"}
        headers = {"accept": "application/json", "x-picsart-api-key": PICSART_API_KEY}

        with requests.post(url, headers=headers, data=payload, files=files) as response:
            response.raise_for_status()
            response_data = response.json()
            urls = response_data["data"]["url"]
    except requests.exceptions.RequestException as e:
        logger.error(f"Error in Picsart request: {e}")
        raise HTTPException(
            status_code=500,
            detail=internal_error
        )

    try:
        response_two = requests.get(urls)
        response_two.raise_for_status()

        encoded_string = base64.b64encode(response_two.content).decode("utf-8")
    except requests.exceptions.RequestException as e:
        logger.error(f"Error in Picsart image retrieval: {e}")
        raise HTTPException(
            status_code=500,
            detail=contact_support
        )

    if encoded_string:
        return SuccessResponse(status="True", randydev={"data": encoded_string})
    else:
        return SuccessResponse(status="False", randydev={"data": contact_support})

@app.post("/ryuzaki/anime-styled")
def Anime_Styled(
    item: AnimeStyled,
    api_key: None = Depends(validate_api_key)
):
    API_URL = SOURCE_ANIME_STYLED_URL
    try:
        payload = {"inputs": item.query}
        headers = {"Authorization": f"Bearer {HUGGING_TOKEN}"}
        response = requests.post(API_URL, headers=headers, json=payload)
        response.raise_for_status()
    except requests.exceptions.RequestException:
        raise HTTPException(
            status_code=500,
            detail=internal_error
        )
    try:
        encoded_string = base64.b64encode(response.content).decode("utf-8")
    except Exception:
        raise HTTPException(
            status_code=500,
            detail=contact_support
        )
    if encoded_string:
        return SuccessResponse(status="True", randydev={"data": encoded_string})
    else:
        return SuccessResponse(status="False", randydev={"data": contact_support})

@app.post("/ryuzaki/unsplash")
def image_unsplash(item: GetImageUnsplash):
    url = SOURCE_UNSPLASH_URL
    image_url = f"{url}/?{item.query}/{item.size}"
    try:
        response = requests.get(image_url)
        response.raise_for_status()
    except requests.exceptions.RequestException:
        raise HTTPException(
            status_code=500,
            detail=internal_error
        )
    try:
        encoded_string = base64.b64encode(response.content).decode("utf-8")
    except Exception:
        raise HTTPException(
            status_code=500,
            detail=contact_support
        )
    if encoded_string:
        return SuccessResponse(status="True", randydev={"data": encoded_string})
    else:
        return SuccessResponse(status="False", randydev={"data": "Not found image data"})

@app.post("/ryuzaki/chatgpt-model", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def chatgpt_model(item: ChatgptModel):
    url = "https://lexica.qewertyy.me/models"
    if item.is_models:
        params = {"model_id": item.model_id, "prompt": item.query}
        response = requests.post(url, params=params)
        if response.status_code != 200:
            return SuccessResponse(status="False", randydev={"message": contact_support})
        check_response = response.json()
        answer = check_response.get("content")
        return SuccessResponse(status="True", randydev={"message": answer})
    else:
        params = {"model_id": 5, "prompt": item.query}
        response = requests.post(url, params=params)
        if response.status_code != 200:
            return SuccessResponse(status="False", randydev={"message": contact_support})
        check_response = response.json()
        answer = check_response.get("content")
        return SuccessResponse(status="True", randydev={"message": answer})

@app.post("/ryuzaki/chatgpt3-turbo", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def chatgpt3_turbo(
    item: Chatgpt3Texts,
    user_id: int=None,
    api_key: None = Depends(validate_api_key)
):
    if item.is_openai_original:
        try:
            GPTbase = SOURCE_OPENAI_ACCESS_URL
            response = OpenAiToken(api_key=item.api_key, api_base=GPTbase).chat_message_turbo(
                query=item.query,
                model=item.model,
                user_id=user_id,
                is_stream=item.is_stream
            )
            answer = response[0]
            continue_chat = response[1]
            return SuccessResponse(
                status="True",
                randydev={
                    "message": answer,
                    "chat_history": continue_chat
                }
            )
        except Exception:
            return SuccessResponse(status="False", randydev={"message": contact_support})
    else:
        url = "https://lexica.qewertyy.me/models"
        params = {"model_id": 5, "prompt": item.query}
        response = requests.post(url, params=params)
        if response.status_code != 200:
            return SuccessResponse(status="False", randydev={"message": contact_support})
        check_response = response.json()
        answer = check_response.get("content")
        return SuccessResponse(status="True", randydev={"message": answer})

@app.post("/ryuzaki/chatgpt4-turbo", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def chatgpt4_turbo(
    item: OpenaiTexts,
    api_key: None = Depends(validate_api_key)
):
    try:
        GPTbase = SOURCE_OPENAI_ACCESS_URL
        response = OpenAiToken(api_key=item.api_key, api_base=GPTbase).chat_message_turbo(
            query=item.query,
            model=item.model,
            is_stream=item.is_stream
        )
        answer = response[0]
        continue_chat = response[1]
        return SuccessResponse(
            status="True",
            randydev={
                "message": answer,
                "chat_history": continue_chat
            }
        )
    except Exception:
        return SuccessResponse(status="False", randydev={"message": contact_support})

@app.post("/ryuzaki/google-ai", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def v1beta3_google_ai(
    item: ChatgptCustom,
    api_key: None = Depends(validate_api_key)
):
    url = SOURCE_ASSISTANT_GOOGLE_AI
    token = ASSISTANT_GOOGLE_API_KEYS
    api_url = f"{SOURCE_ASSISTANT_GOOGLE_AI}/v1beta3/models/text-bison-001:generateText?key={ASSISTANT_GOOGLE_API_KEYS}"
    try:
        headers = {"Content-Type": "application/json"}
        data = {
            "prompt": {
                "text": item.query
            }
        }
        response = requests.post(api_url, headers=headers, json=data)
        response_str = response.json()
        answer = response_str["candidates"]
        for results in answer:
            message = results.get("output")
        return SuccessResponse(status="True", randydev={"message": message})
    except:
        return SuccessResponse(status="False", randydev={"message": internal_error})

@app.post("/ryuzaki/beta-rag", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def beta_rag(item: BetaRags):
    try:
        rag = BetaRag(
            token=HUGGING_TOKEN,
            user_id=item.user_id,
            mongo_url=item.mongo_url
        )
        cybersecuritydb(item.user_id, item.mongo_url)
        answer = rag.rag_chat(item.query)
        return SuccessResponse(
            status="True",
                randydev={"message": answer}
        )
    except Exception as e:
        return SuccessResponse(status="False", randydev={"message": str(e)})

@app.post("/ryuzaki/gemini-ai-pro", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def gemini_pro(item: GeminiPro):
    owner_base = f"""
    Your name is Randy Dev. A kind and friendly AI assistant that answers in
    a short and concise answer. Give short step-by-step reasoning if required.

    Today is {dt.now():%A %d %B %Y %H:%M}
    """
    if item.is_multi_chat:
        selected_api_key = ASSISTANT_GOOGLE_API_KEYS or item.gemini_api_key
        try:
            geni = GeminiLatest(
                api_keys=selected_api_key,
                mongo_url=item.mongo_url,
                user_id=item.user_id
            )
            cybersecuritydb(item.user_id, item.mongo_url)
            answer, gemini_chat = geni._GeminiLatest__get_response_gemini(item.query)
            return SuccessResponse(
                status="True",
                randydev={
                    "message": answer,
                    "chat_history": gemini_chat
                }
            )
        except Exception:
            return SuccessResponse(status="False", randydev={"message": contact_support})
    else:
        if item.is_login:
            token = item.bard_api_key
        else:
            token = COOKIE_BARD_TOKEN
        try:
            session = requests.Session()
            session.headers = {
                "Host": "bard.google.com",
                "X-Same-Domain": "1",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
                "Origin": "https://bard.google.com",
                "Referer": "https://bard.google.com/"
            }
            session.cookies.set("__Secure-1PSID", token)
            bard = Bard(token=token, session=session, timeout=30)
            bard.get_answer(owner_base)["content"]
            message = bard.get_answer(item.query)["content"]
            return SuccessResponse(status="True", randydev={"message": message})
        except:
            return SuccessResponse(status="False", randydev={"message": contact_support})

@app.post("/ryuzaki/v1beta2-google-ai", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def v1beta2_google_ai(
    item: ChatgptCustom,
    api_key: None = Depends(validate_api_key)
):
    url = SOURCE_ASSISTANT_GOOGLE_AI
    token = ASSISTANT_GOOGLE_API_KEYS
    api_url = f"{SOURCE_ASSISTANT_GOOGLE_AI}/v1beta2/models/chat-bison-001:generateMessage?key={ASSISTANT_GOOGLE_API_KEYS}"
    try:
        headers = {"Content-Type": "application/json"}
        data = {
            "prompt": {
                "messages": [{"content": item.query}]}
        }
        response = requests.post(api_url, headers=headers, json=data)
        response_str = response.json()
        answer = response_str["candidates"]
        for results in answer:
            message = results.get("content")
        return SuccessResponse(status="True", randydev={"message": message})
    except:
        return SuccessResponse(status="False", randydev={"message": internal_error})

@app.post("/ryuzaki/new-monitor", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def new_monitor(
    item: NewMonitor,
    api_key: None = Depends(validate_api_key)
):
    urls = SOURCE_MONITOR_URL
    token = MONITOR_API_KEYS
    api_url = f"{urls}/newMonitor"
    try:
        headers = {
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache"
        }
        payload = {
            "api_key": token,
            "format": "json",
            "type": item.type,
            "url": item.url,
            "friendly_name": item.friendly_name
        }
        response = requests.post(api_url, data=payload, headers=headers)
        response_str = response.json()
        status_ok = response_str["stat"]
        monitor_id = response_str["monitor"].get("id")
        monitor_status = response_str["monitor"].get("status")
        return {
            "status": "true",
            "randydev":{
                "status_ok": status_ok,
                "monitor_id": monitor_id,
                "monitor_status": monitor_status
            }
        }
    except:
        return {"status": "false", "message": "Error response."}

@app.post("/ryuzaki/get-monitors", response_model=SuccessResponse, responses={422: {"model": ErrorResponse}})
def getMonitors(
    item: GetMonitorLogs,
    api_key: None = Depends(validate_api_key)
):
    url = SOURCE_MONITOR_URL
    token = MONITOR_API_KEYS
    api_url = f"{url}/getMonitors"
    try:
        headers = {
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache"
        }
        payload = {
            "api_key": token,
            "format": "json",
            "logs": item.logs
        }
        response = requests.post(api_url, data=payload, headers=headers)
        response_str = response.json()
        data = response_str["monitors"]
        url_list = []
        for x in data:
            url = x.get("url")
            if url:
                url_list.append(url)
        return {
            "status": "true",
            "randydev":{
                "url": url_list,
            }
        }
    except:
        return {"status": "false", "message": "Error response."}

async def get_data(username):
    base_msg = ""
    async with AsyncClient() as gpx:
        req = (await gpx.get(f"https://api.github.com/users/{username}")).json()
        try:
            avatar = req["avatar_url"]
            twitter = req['twitter_username']
            base_msg += "**❆ Gitub Information ❆** \n\n"
            base_msg += f"**Profile Url:** {req['html_url']} \n"
            base_msg += f"**Name:** `{req['name']}` \n"
            base_msg += f"**Username:** `{req['login']}` \n"
            base_msg += f"**User ID:** `{req['id']}` \n"
            base_msg += f"**Location:** `{req['location']}` \n"
            base_msg += f"**Company:** `{req['company']}` \n"
            base_msg += f"**Blog:** `{req['name']}` \n"
            base_msg += f"**Twitter:** `{f'https://twitter.com/{twitter}' if twitter else 'None'}` \n"
            base_msg += f"**Bio:** `{req['bio']}` \n"
            base_msg += f"**Public Repos:** `{req['public_repos']}` \n"
            base_msg += f"**Public Gists:** `{req['public_gists']}` \n"
            base_msg += f"**Followers:** `{req['followers']}` \n"
            base_msg += f"**Following:** `{req['following']}` \n"
            base_msg += f"**Created At:** `{req['created_at']}` \n"
            base_msg += f"**Update At:** `{req['updated_at']}` \n"
            return [base_msg, avatar]
        except Exception as e:
            base_msg += f"**An error occured while parsing the data!** \n\n**Traceback:** \n `{e}` \n\n`Make sure that you've sent the command with the correct username!`"
            return [base_msg, "https://telegra.ph//file/32f69c18190666ea96553.jpg"]

@app.get("/ryuzaki/github", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
async def github(item: GithubUsernames):
    try:
        details = await get_data(item.username)
        return {
            "status": "true",
            "randydev":{
                "avatar": details[1],
                "results": details[0]
            }
        }
    except:
        return {"status": "false", "message": "Error response."}

@app.get("/ryuzaki/webshot", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def webshot(item: Webshot):
    try:
        required_url = f"https://mini.s-shot.ru/{item.quality}/{item.type_mine}/{item.pixels}/{item.cast}/?{item.url}"
        return {
            "status": "true",
            "randydev":{
                "image_url": required_url
            }
        }
    except:
        return {"status": "false", "message": "Error response."}

@app.get("/ryuzaki/chatbot", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def chatbot(item: ChatBots):
    api_url = b64decode("aHR0cHM6Ly9hcGkuc2Fmb25lLmRldi9jaGF0Ym90").decode("utf-8")
    params = {
        "query": item.query,
        "user_id": item.user_id,
        "bot_name": item.bot_name,
        "bot_master": item.bot_username
    }
    x = requests.get(f"{api_url}", params=params)
    if x.status_code != 200:
        return "Error api request"
    try:
        y = x.json()
        response = y["response"]
        return {
            "status": "true",
            "randydev":{
                "message": response
            }
        }
    except:
        return {"status": "false", "message": "Error response."}

@app.get("/ryuzaki/llama", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}})
def get_llama(item: ChatgptCustom):
    api_url = SOURCE_WHAT_GAY_URL
    params = {"query": item.query}
    x = requests.get(f"{api_url}/llama", params=params)
    if x.status_code != 200:
        return SuccessResponse(status="False", randydev={"message": contact_support})
    try:
        y = x.json()
        response = y["answer"]
        return SuccessResponse(status="True", randydev={"message": response})
    except:
        return SuccessResponse(status="False", randydev={"message": contact_support})

@app.get("/ryuzaki/waifu", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def waifu_pics(item: WaifuPics):
    waifu_api = f"{SOURCE_WAIFU_URL}/{item.types}"
    waifu_param = f"{waifu_api}/{item.category}"

    response = requests.get(waifu_param)

    if response.status_code != 200:
        return "Sorry, there was an error processing your request. Please try again later"
    data_waifu = response.json()
    try:
        waifu_image_url = data_waifu["url"]
    except Exception as e:
        return f"Error request {e}"
    if waifu_image_url:
        if item.is_bytes:
            try:
                response_two = requests.get(waifu_image_url)
                response_two.raise_for_status()
            except requests.exceptions.RequestException:
                raise HTTPException(status_code=500, detail="Internal server error")
            return StreamingResponse(BytesIO(response_two.content), media_type=item.media_type)
        else:
            return {
                "status": "true",
                "randydev":{
                    "image_url": waifu_image_url
                }
            }
    else:
        return {"status": "false", "message": "Error response."}

@app.get("/ryuzaki/rayso", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def make_rayso(item: MakeRayso):
    trans = SyncTranslator()
    api_url = b64decode("aHR0cHM6Ly9hcGkuc2Fmb25lLm1lL3JheXNv").decode("utf-8")
    if item.auto_translate:
        source = trans.detect(item.code)
        translation = trans(item.code, sourcelang=source, targetlang=item.setlang)
        code = translation.text
    else:
        code = item.code
    if item.ryuzaki_dark:
        x = requests.post(
            f"{api_url}",
            json={
                "code": code,
                "title": item.title,
                "theme": item.theme,
                "darkMode": True
            }
        )
        if x.status_code != 200:
            return "Error api Gay"
        data = x.json()
        try:
            image_data = base64.b64decode(data["image"])
            return {
                "status": "true",
                "data":{
                    "image": image_data
                }
            }
        except:
            return {"status": "false", "message": "Error response"}
    else:
        x = requests.post(
            f"{api_url}",
            json={
                "code": code,
                "title": item.title,
                "theme": item.theme,
                "darkMode": False
            }
        )
        if x.status_code != 200:
            return "Error api Gay"
        data = x.json()
        try:
            image_data = base64.b64decode(data["image"])
            return {
                "status": "true",
                "data":{
                    "image": image_data
                }
            }
        except:
            return {"status": "false", "message": "Error response"}

@app.get("/ryuzaki/ipcheck")
def whois_ip_address(ip_address: str=None):
    apikey = kc("M0QwN0UyRUFBRjU1OTQwQUY0NDczNEMzRjJBQzdDMUE=").decode("utf-8")
    location_link = "https"
    location_api = "api.ip2location.io"
    location_key = f"key={apikey}"
    location_search = f"ip={ip_address}"
    location_param = (
        f"{location_link}://{location_api}/?{location_key}&{location_search}"
    )
    response = requests.get(location_param)
    if response.status_code != 200:
        return "Sorry, there was an error processing your request. Please try again later"
    data_location = response.json()
    try:
        location_ip = data_location["ip"]
        location_code = data_location["country_code"]
        location_name = data_location["country_name"]
        location_region = data_location["region_name"]
        location_city = data_location["city_name"]
        location_zip = data_location["zip_code"]
        location_zone = data_location["time_zone"]
        location_card = data_location["as"]
    except Exception as e:
        return f"error {e}"
    if (
        location_ip
        and location_code
        and location_name
        and location_region
        and location_city
        and location_zip
        and location_zone
        and location_card
    ):
        return {
            "ip_address": location_ip,
            "country_code": location_code,
            "region_name": location_region,
            "city_name": location_city,
            "zip_code": location_zip,
            "time_zone": location_zone,
            "as": location_card
        }
    else:
        return {"status": "false", "message": "Invalid ip address"}

@app.get("/ryuzaki/tiktok_douyin", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def tiktok_douyin(item: TiktokDownloader):
    response = requests.get(f"{SOURCE_TIKTOK_WTF_URL}={item.tiktok_url}")
    if response.status_code != 200:
        return "Internal server error"
    try:
        download_video = response.json()["aweme_list"][0]["video"]["play_addr"]["url_list"][0]
        download_audio = response.json()["aweme_list"][0]["music"]["play_url"]["url_list"][0]
        description = response.json()["aweme_list"][0]["desc"]
        author = response.json()["aweme_list"][0]["author"]["nickname"]
        request = response.json()["aweme_list"][0]["author"]["signature"]
        return {
            "status": "true",
            "randydev": {
                "video_url": download_video,
                "music_url": download_audio,
                "description": description,
                "author": author,
                "request": request
            }
        }
    except:
        return {"status": "false", "message": "Error request"}

@app.get("/ryuzaki/tiktok", response_model=SuccessResponse, responses={422: {"model": ErrorStatus}})
def tiktok_downloader(item: TiktokBeta):
    api_devs = SOURCE_TIKTOK_TECH_URL
    parameter = f"tiktok?url={item.tiktok_url}"
    api_url = f"{api_devs}/{parameter}"
    response = requests.get(api_url)

    if response.status_code != 200:
        return "Error: Unable to fetch data from the TikTok API"
    try:
        results = response.json()
        caption = results.get("result", {}).get("desc", "")
        if item.only_video:
            video_url = results.get("result", {}).get("withoutWaterMarkVideo", "")
            if video_url:
                return {
                    "download_url": video_url,
                    "caption": caption
                }
        else:
            music_mp3 = results.get("result", {}).get("music", "")
            if music_mp3:
                return {
                    "music_url": music_mp3,
                    "caption": caption
                }
        return "Error: TikTok data not found or unsupported format"
    except:
        return {"status": "false", "message": "Invalid Link"}

@app.get("/ryuzaki/mediafire")
def mediafire(item: DownloadLink):
    try:
        down_link = str(item.link)
        mid = down_link.split('/', 5)
        if mid[3] == "view":
            mid[3] = "file"
            down_link = '/'.join(mid)
        r = requests.get(down_link)
        soup = BeautifulSoup(r.content, "html.parser")
        a_href = soup.find("a", {"class": "input popsok"}).get("href")
        a = str(a_href)
        id = link.split('/', 5)[4]
        a_byte = soup.find("a", {"class": "input popsok"}).get_text()
        a_name = soup.find("div", {"class": "dl-btn-label"}).get_text()
        details = soup.find("ul", {"class": "details"})
        li_items = details.find_all('li')[1]
        some = li_items.find_all("span")[0].get_text().split()
        dat = list(some)
        down = a_byte.replace(" ", "").strip()
        time = dat[1]
        date = dat[0]
        byte = down.split("(", 1)[1].split(")", 1)[0]
        name = a_name.replace(" ", "").strip()
        return SuccessResponse(
            status="True",
            randydev={
                "directDownload": a,
                "original": item.link,
                "id": id,
                "name": name,
                "readable": byte,
                "time": byte,
                "date": date
            }
        )
    except:
        return {'status': 'false', 'message': 'Invalid Link'}

@app.get("/ryuzaki/gdrive")
def gdrive(item: DownloadLink):
    try:
        down = link.split('/', 6)
        url = f'https://drive.google.com/uc?export=download&id={down[5]}'
        session = requests.Session()
        response = session.get(url, stream=True)
        headers = response.headers
        content_disp = headers.get('content-disposition')
        filename = None
        if content_disp:
            match = re.search(r'filename="(.+)"', content_disp)
            if match:
                filename = match.group(1)
        content_length = headers.get('content-length')
        last_modified = headers.get('last-modified')
        content_type = headers.get('content-type')
        return SuccessResponse(
            status="True",
            randydev={
                "directDownload": url,
                "original": item.link,
                "id": down[5],
                "name": filename if filename else "No filename provided by the server.",
                "readable": f"{round(int(content_length) / (1024 * 1024), 2)} MB" if content_length else "No content length provided by the server.",
                "type": content_type if content_type else "No content type provided by the server.",
                "DateAndTime": last_modified if last_modified else "No last modified date provided by the server."
            }
        )
    except:
        return {'status': 'false', 'message': 'Invalid Link'}

@app.get("/ryuzaki/anonfiles")
def anonfiles(item: DownloadLink):
    try:
        r = requests.get(item.link)
        soup = BeautifulSoup(r.content, "html.parser")
        a_href = soup.find("a", {"id": "download-url"}).get("href")
        a = str(a_href)
        id = link.split('/', 4)[3]
        jsondata = requests.get(f'https://api.anonfiles.com/v2/file/{id}/info').json()
        jsondata['data']['file']['url']['directDownload'] = a
        del jsondata['data']['file']['url']['full']
        return jsondata
    except:
        return "{'status': 'false', 'message': 'Invalid Link'}"

@app.get("/ryuzaki/filechan")
def filechan(item: DownloadLink):
    try:
        r = requests.get(item.link)
        soup = BeautifulSoup(r.content, "html.parser")
        a_href = soup.find("a", {"id": "download-url"}).get("href")
        a = str(a_href)
        id = link.split('/', 4)[3]
        jsondata = requests.get(f'https://api.filechan.org/v2/file/{id}/info').json()
        jsondata['data']['file']['url']['directDownload'] = a
        del jsondata['data']['file']['url']['full']
        return jsondata
    except:
        return {'status': 'false', 'message': 'Invalid Link'}

@app.get("/ryuzaki/letsupload")
def letsupload(item: DownloadLink):
    try:
        r = requests.get(item.link)
        soup = BeautifulSoup(r.content, "html.parser")
        a_href = soup.find("a", {"id": "download-url"}).get("href")
        a = str(a_href)
        id = link.split('/', 4)[3]
        jsondata = requests.get(f'https://api.letsupload.cc/v2/file/{id}/info').json()
        jsondata['data']['file']['url']['directDownload'] = a
        del jsondata['data']['file']['url']['full']
        return jsondata
    except:
        return {'status': 'false', 'message': 'Invalid Link'}

@app.get("/ryuzaki/megaupload")
def megaupload(item: DownloadLink):
    try:
        r = requests.get(item.link)
        soup = BeautifulSoup(r.content, "html.parser")
        a_href = soup.find("a", {"id": "download-url"}).get("href")
        a = str(a_href)
        id = link.split('/', 4)[3]
        jsondata = requests.get(f'https://api.megaupload.nz/v2/file/{id}/info').json()
        jsondata['data']['file']['url']['directDownload'] = a
        del jsondata['data']['file']['url']['full']
        return jsondata
    except:
        return {'status': 'false', 'message': 'Invalid Link'}

@app.get("/ryuzaki/myfile")
def myfile(item: DownloadLink):
    try:
        r = requests.get(item.link)
        soup = BeautifulSoup(r.content, "html.parser")
        a_href = soup.find("a", {"id": "download-url"}).get("href")
        a = str(a_href)
        id = link.split('/', 4)[3]
        jsondata = requests.get(f'https://api.myfile.is/v2/file/{id}/info').json()
        jsondata['data']['file']['url']['directDownload'] = a
        del jsondata['data']['file']['url']['full']
        return jsondata
    except:
        return {'status': 'false', 'message': 'Invalid Link'}

description = """
- Ryuzaki Library: [Library Here](https://github.com/TeamKillerX/RyuzakiLib)

•Developed by [@xtdevs](https://t.me/xtdevs)
"""

def custom_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
    error_detail = [{"error": str(exc.detail)}]
    custom_error_model = CustomErrorResponseModel(detail=error_detail)

    return JSONResponse(
        status_code=exc.status_code,
        content=custom_error_model.dict(),
        headers=exc.headers,
    )

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="RyuzakiLib API",
        version="3.3.0",
        summary="Use It Only For Personal Project Else I Need To Delete The Api",
        description=description,
        routes=app.routes,
    )
    openapi_schema["info"]["x-logo"] = {
        "url": "https://github-production-user-asset-6210df.s3.amazonaws.com/90479255/289277800-f26513f7-cdf4-44ee-9a08-f6b27e6b99f7.jpg"
    }
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

app.add_exception_handler(HTTPException, custom_exception_handler)