File size: 57,652 Bytes
ddaefda
 
 
bae67bf
79bb4ee
ffd6919
c31239d
3ae260c
8e3da9c
6740b78
 
 
ae8d22c
bae67bf
ba8e699
4d3fe36
6be1fe2
9da74a0
6be1fe2
ddaefda
4078885
4d3fe36
e5dce64
 
ba8e699
c31239d
bae67bf
16b7f0b
 
989684f
 
c31239d
 
50f1e91
 
ba8e699
1211b2c
 
 
 
 
91ee28f
 
 
8e3da9c
 
 
 
84eaeb7
bae67bf
84eaeb7
bae67bf
 
84eaeb7
 
bae67bf
 
 
db69584
76f9b1e
e5dce64
72588b7
bae67bf
84eaeb7
 
bae67bf
22197b0
 
 
6b0a5df
7206b9b
 
 
182b468
 
 
7206b9b
 
e5dce64
 
 
 
 
 
 
 
 
22197b0
 
 
 
 
 
 
 
 
00407d4
22197b0
c31239d
e5dce64
6b0a5df
 
e5dce64
22197b0
 
 
 
e5dce64
6b0a5df
 
 
 
 
fa5b8a0
22197b0
50f1e91
8ea742a
45a91e1
8ca184b
e52da11
989684f
c31239d
50f1e91
d155e37
8ea742a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5f2e9b
8ea742a
22197b0
00407d4
22197b0
 
 
 
 
 
fa5b8a0
22197b0
45a91e1
d155e37
 
 
 
fa5b8a0
d155e37
 
6b0a5df
22197b0
00407d4
22197b0
c31239d
22197b0
6711564
45a91e1
22197b0
 
45a91e1
fa5b8a0
 
 
 
 
 
 
50f1e91
 
 
 
 
 
 
 
9fae181
50f1e91
 
 
 
 
 
 
 
 
fa5b8a0
 
 
c31239d
 
50f1e91
 
c31239d
 
 
 
 
 
 
 
 
 
22197b0
 
 
 
 
 
 
 
 
45a91e1
c31239d
 
 
 
22197b0
 
 
 
c31239d
50f1e91
 
 
7206b9b
 
50f1e91
7206b9b
e5dce64
84eaeb7
ddaefda
22197b0
 
 
91ee28f
ddaefda
 
22197b0
 
 
 
e5dce64
ddaefda
 
22197b0
 
 
 
 
 
 
 
 
 
 
 
 
 
91ee28f
 
 
 
 
 
22197b0
 
 
91ee28f
 
 
 
 
 
 
 
e5dce64
91ee28f
 
 
 
e5dce64
 
 
 
 
91ee28f
22197b0
 
ba8e699
 
 
 
e5dce64
ddaefda
bae67bf
8d91d51
91ee28f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c31239d
ba8e699
 
 
 
 
 
 
 
22197b0
 
 
 
 
ba8e699
 
22197b0
 
 
 
 
 
 
 
 
ba8e699
 
 
 
22197b0
 
 
 
ba8e699
 
22197b0
 
 
 
ba8e699
 
2f8cff3
 
 
 
 
 
 
 
ba8e699
2f8cff3
ba8e699
91ee28f
ba8e699
22197b0
 
ba8e699
 
22197b0
 
 
 
 
ba8e699
 
 
22197b0
 
 
 
 
ba8e699
 
 
 
91ee28f
 
 
 
 
c31239d
91ee28f
 
 
 
22197b0
 
 
91ee28f
 
 
 
 
 
22197b0
 
91ee28f
 
6001b99
c31239d
91ee28f
 
 
c31239d
91ee28f
c31239d
91ee28f
6001b99
91ee28f
6001b99
91ee28f
6001b99
ba8e699
09735d0
 
22197b0
 
09735d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bae67bf
84eaeb7
22197b0
 
bae67bf
16b7f0b
 
8e3da9c
 
 
 
 
 
 
 
 
 
 
 
16b7f0b
76f9b1e
 
 
22197b0
 
 
 
 
 
 
 
 
 
 
 
 
91ee28f
 
 
 
 
 
 
22197b0
 
 
 
91ee28f
c31239d
22197b0
 
 
 
 
 
 
91ee28f
22197b0
 
 
 
 
 
 
 
91ee28f
c31239d
22197b0
 
 
 
 
 
 
91ee28f
c31239d
22197b0
 
 
 
 
 
 
91ee28f
22197b0
4078885
22197b0
76f9b1e
 
6740b78
 
 
 
 
76f9b1e
6740b78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fccd514
09735d0
 
ba8e699
 
 
 
 
22197b0
 
6740b78
 
22197b0
91ee28f
ba8e699
 
c31239d
22197b0
 
 
 
 
 
 
 
3ae260c
ba8e699
 
 
 
7191bab
6740b78
 
 
 
 
 
 
 
7191bab
6740b78
 
3ae260c
6740b78
 
 
 
c31239d
 
 
 
 
22197b0
 
4078885
22197b0
c31239d
 
 
 
22197b0
 
 
4078885
c31239d
 
b34c36b
 
 
 
c31239d
 
 
 
 
 
 
 
 
 
 
 
 
4497eab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47be5c2
6740b78
 
3a2edd7
6740b78
 
 
3a2edd7
6740b78
 
3a2edd7
 
 
 
 
 
 
 
 
 
16a257b
 
 
3a2edd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9da74a0
3a2edd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a257b
3a2edd7
d9647ee
 
 
 
 
 
 
 
 
 
99a5694
d9647ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4078885
d9647ee
 
 
 
4078885
d9647ee
 
99a5694
d9647ee
 
 
 
 
 
 
4078885
d9647ee
 
 
 
 
 
 
 
 
4078885
d9647ee
 
 
 
 
 
 
 
 
4078885
d9647ee
 
 
 
6740b78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b918005
 
6740b78
3a2edd7
b918005
3a2edd7
 
 
 
 
 
 
 
 
 
16a257b
 
 
3a2edd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6740b78
3a2edd7
 
 
16a257b
3a2edd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a257b
3a2edd7
 
6740b78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4078885
6740b78
 
4078885
6740b78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4078885
6740b78
 
 
 
 
 
 
 
 
 
16a257b
6740b78
16a257b
6740b78
 
 
3a2edd7
16a257b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4078885
16a257b
 
6740b78
16a257b
6740b78
 
 
 
 
 
 
 
 
 
 
 
4078885
6740b78
 
4078885
6740b78
 
 
 
 
 
 
 
 
 
 
 
9d7a899
6740b78
 
 
 
 
 
 
 
4078885
6740b78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4078885
6740b78
 
 
 
99a5694
16a257b
 
4078885
16a257b
6740b78
b918005
 
 
df482ac
b918005
6740b78
df482ac
 
b918005
4497eab
861a23a
3a2edd7
 
6740b78
 
df482ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6740b78
 
 
 
 
3a2edd7
6740b78
df482ac
 
 
 
 
 
 
6740b78
 
df482ac
4078885
6740b78
df482ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6740b78
df482ac
 
 
 
 
 
 
 
6740b78
 
3a2edd7
df482ac
 
 
 
 
 
 
b918005
4078885
3a2edd7
99a5694
bae67bf
6001b99
4078885
db69584
ba8e699
 
 
 
 
22197b0
4078885
22197b0
16b7f0b
 
4078885
db69584
ba8e699
4078885
ba8e699
22197b0
 
 
 
3c0d2e2
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
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
import os
import time
import logging
import requests
import json
import random
import uuid
import concurrent.futures
import threading
import base64
import io
from PIL import Image
from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, request, jsonify, Response, stream_with_context

os.environ['TZ'] = 'Asia/Shanghai'
time.tzset()

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

API_ENDPOINT = "https://api.siliconflow.cn/v1/user/info"
TEST_MODEL_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions"
MODELS_ENDPOINT = "https://api.siliconflow.cn/v1/models"
EMBEDDINGS_ENDPOINT = "https://api.siliconflow.cn/v1/embeddings"

app = Flask(__name__)

text_models = []
free_text_models = []
embedding_models = []
free_embedding_models = []
image_models = []
free_image_models = []

invalid_keys_global = []
free_keys_global = []
unverified_keys_global = []
valid_keys_global = []

executor = concurrent.futures.ThreadPoolExecutor(max_workers=20)
model_key_indices = {}

request_timestamps = []
token_counts = []
data_lock = threading.Lock()

def get_credit_summary(api_key):
    """
    使用 API 密钥获取额度信息。
    """
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    try:
        response = requests.get(API_ENDPOINT, headers=headers)
        response.raise_for_status()
        data = response.json().get("data", {})
        total_balance = data.get("totalBalance", 0)
        return {"total_balance": float(total_balance)}
    except requests.exceptions.RequestException as e:
        logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}")
        return None

FREE_MODEL_TEST_KEY = (
    "sk-bmjbjzleaqfgtqfzmcnsbagxrlohriadnxqrzfocbizaxukw"
)

FREE_IMAGE_LIST = [
    "stabilityai/stable-diffusion-3-5-large",
    "black-forest-labs/FLUX.1-schnell",
    "stabilityai/stable-diffusion-3-medium",
    "stabilityai/stable-diffusion-xl-base-1.0",
    "stabilityai/stable-diffusion-2-1"
]

def test_model_availability(api_key, model_name):
    """
    测试指定的模型是否可用。
    """
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    try:
        response = requests.post(
            TEST_MODEL_ENDPOINT,
            headers=headers,
            json={
                "model": model_name,
                "messages": [{"role": "user", "content": "hi"}],
                "max_tokens": 5,
                "stream": False
            },
            timeout=5
        )
        if response.status_code == 429 or response.status_code == 200:
            return True
        else:
            return False
    except requests.exceptions.RequestException as e:
        logging.error(
            f"测试模型 {model_name} 可用性失败,"
            f"API Key:{api_key},错误信息:{e}"
        )
        return False

def refresh_models():
    """
    刷新模型列表和免费模型列表。
    """
    global text_models, free_text_models
    global embedding_models, free_embedding_models
    global image_models, free_image_models

    text_models = get_all_models(FREE_MODEL_TEST_KEY, "chat")
    embedding_models = get_all_models(FREE_MODEL_TEST_KEY, "embedding")
    image_models = get_all_models(FREE_MODEL_TEST_KEY, "text-to-image")
    free_text_models = []
    free_embedding_models = []
    free_image_models = []

    ban_models_str = os.environ.get("BAN_MODELS")
    ban_models = []
    if ban_models_str:
        try:
            ban_models = json.loads(ban_models_str)
            if not isinstance(ban_models, list):
                logging.warning(
                    "环境变量 BAN_MODELS 格式不正确,应为 JSON 数组。"
                )
                ban_models = []
        except json.JSONDecodeError:
            logging.warning(
                "环境变量 BAN_MODELS JSON 解析失败,请检查格式。"
            )
            ban_models = []
    
    text_models = [model for model in text_models if model not in ban_models]
    embedding_models = [model for model in embedding_models if model not in ban_models]
    image_models = [model for model in image_models if model not in ban_models]

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=100
    ) as executor:
        future_to_model = {
            executor.submit(
                test_model_availability,
                FREE_MODEL_TEST_KEY,
                model
            ): model for model in text_models
        }
        for future in concurrent.futures.as_completed(future_to_model):
            model = future_to_model[future]
            try:
                is_free = future.result()
                if is_free:
                    free_text_models.append(model)
            except Exception as exc:
                logging.error(f"模型 {model} 测试生成异常: {exc}")

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=100
    ) as executor:
        future_to_model = {
            executor.submit(
                test_embedding_model_availability,
                FREE_MODEL_TEST_KEY, model
            ): model for model in embedding_models
        }
        for future in concurrent.futures.as_completed(future_to_model):
            model = future_to_model[future]
            try:
                is_free = future.result()
                if is_free:
                    free_embedding_models.append(model)
            except Exception as exc:
                logging.error(f"模型 {model} 测试生成异常: {exc}")
                
    with concurrent.futures.ThreadPoolExecutor(
        max_workers=100
    ) as executor:
        future_to_model = {
            executor.submit(
                test_image_model_availability,
                FREE_MODEL_TEST_KEY, model
            ): model for model in image_models
        }
        for future in concurrent.futures.as_completed(future_to_model):
            model = future_to_model[future]
            try:
                is_free = future.result()
                if is_free:
                    free_image_models.append(model)
            except Exception as exc:
                logging.error(f"模型 {model} 测试生成异常: {exc}")

    logging.info(f"所有文本模型列表:{text_models}")
    logging.info(f"免费文本模型列表:{free_text_models}")
    logging.info(f"所有向量模型列表:{embedding_models}")
    logging.info(f"免费向量模型列表:{free_embedding_models}")
    logging.info(f"所有生图模型列表:{image_models}")
    logging.info(f"免费生图模型列表:{free_image_models}")

def test_embedding_model_availability(api_key, model_name):
    """
    测试指定的向量模型是否可用。
    """
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    try:
        response = requests.post(
            EMBEDDINGS_ENDPOINT,
            headers=headers,
            json={
                "model": model_name,
                "input": ["hi"],
            },
            timeout=10
        )
        if response.status_code == 429 or response.status_code == 200:
            return True
        else:
            return False
    except requests.exceptions.RequestException as e:
        logging.error(
            f"测试向量模型 {model_name} 可用性失败,"
            f"API Key:{api_key},错误信息:{e}"
        )
        return False
        
def test_image_model_availability(api_key, model_name):
    """
    测试指定的图像模型是否在 FREE_IMAGE_LIST 中。
    如果在列表中,返回 True,否则返回 False。
    """
    return model_name in FREE_IMAGE_LIST

def load_keys():
    """
    从环境变量中加载 keys,进行去重,
    并根据额度和模型可用性进行分类,
    然后记录到日志中。
    使用线程池并发处理每个 key。
    """
    keys_str = os.environ.get("KEYS")
    test_model = os.environ.get(
        "TEST_MODEL",
        "Pro/google/gemma-2-9b-it"
    )

    if keys_str:
        keys = [key.strip() for key in keys_str.split(',')]
        unique_keys = list(set(keys))
        keys_str = ','.join(unique_keys) 
        os.environ["KEYS"] = keys_str

        logging.info(f"加载的 keys:{unique_keys}")

        with concurrent.futures.ThreadPoolExecutor(
            max_workers=20
        ) as executor:
            future_to_key = {
                executor.submit(
                    process_key, key, test_model
                ): key for key in unique_keys
            }

            invalid_keys = []
            free_keys = []
            unverified_keys = []
            valid_keys = []

            for future in concurrent.futures.as_completed(
                future_to_key
            ):
                key = future_to_key[future]
                try:
                    key_type = future.result()
                    if key_type == "invalid":
                        invalid_keys.append(key)
                    elif key_type == "free":
                        free_keys.append(key)
                    elif key_type == "unverified":
                        unverified_keys.append(key)
                    elif key_type == "valid":
                        valid_keys.append(key)
                except Exception as exc:
                    logging.error(f"处理 KEY {key} 生成异常: {exc}")

        logging.info(f"无效 KEY:{invalid_keys}")
        logging.info(f"免费 KEY:{free_keys}")
        logging.info(f"未实名 KEY:{unverified_keys}")
        logging.info(f"有效 KEY:{valid_keys}")

        global invalid_keys_global, free_keys_global
        global unverified_keys_global, valid_keys_global
        invalid_keys_global = invalid_keys
        free_keys_global = free_keys
        unverified_keys_global = unverified_keys
        valid_keys_global = valid_keys

    else:
        logging.warning("环境变量 KEYS 未设置。")

def process_key(key, test_model):
    """
    处理单个 key,判断其类型。
    """
    credit_summary = get_credit_summary(key)
    if credit_summary is None:
        return "invalid"
    else:
        total_balance = credit_summary.get("total_balance", 0)
        if total_balance <= 0:
            return "free"
        else:
            if test_model_availability(key, test_model):
                return "valid"
            else:
                return "unverified"

def get_all_models(api_key, sub_type):
    """
    获取所有模型列表。
    """
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    try:
        response = requests.get(
            MODELS_ENDPOINT,
            headers=headers,
            params={"sub_type": sub_type}
        )
        response.raise_for_status()
        data = response.json()
        if (
            isinstance(data, dict) and
            'data' in data and
            isinstance(data['data'], list)
        ):
            return [
                model.get("id") for model in data["data"]
                if isinstance(model, dict) and "id" in model
            ]
        else:
            logging.error("获取模型列表失败:响应数据格式不正确")
            return []
    except requests.exceptions.RequestException as e:
        logging.error(
            f"获取模型列表失败,"
            f"API Key:{api_key},错误信息:{e}"
        )
        return []
    except (KeyError, TypeError) as e:
        logging.error(
            f"解析模型列表失败,"
            f"API Key:{api_key},错误信息:{e}"
        )
        return []

def determine_request_type(model_name, model_list, free_model_list):
    """
    根据用户请求的模型判断请求类型。
    """
    if model_name in free_model_list:
        return "free"
    elif model_name in model_list:
        return "paid"
    else:
        return "unknown"

def select_key(request_type, model_name):
    """
    根据请求类型和模型名称选择合适的 KEY,
    并实现轮询和重试机制。
    """
    if request_type == "free":
        available_keys = (
            free_keys_global +
            unverified_keys_global +
            valid_keys_global
        )
    elif request_type == "paid":
        available_keys = unverified_keys_global + valid_keys_global
    else:
        available_keys = (
            free_keys_global +
            unverified_keys_global +
            valid_keys_global
        )

    if not available_keys:
        return None

    current_index = model_key_indices.get(model_name, 0)

    for _ in range(len(available_keys)):
        key = available_keys[current_index % len(available_keys)]
        current_index += 1

        if key_is_valid(key, request_type):
            model_key_indices[model_name] = current_index
            return key
        else:
            logging.warning(
                f"KEY {key} 无效或达到限制,尝试下一个 KEY"
            )

    model_key_indices[model_name] = 0
    return None

def key_is_valid(key, request_type):
    """
    检查 KEY 是否有效,
    根据不同的请求类型进行不同的检查。
    """
    if request_type == "invalid":
        return False

    credit_summary = get_credit_summary(key)
    if credit_summary is None:
        return False

    total_balance = credit_summary.get("total_balance", 0)

    if request_type == "free":
        return True
    elif request_type == "paid" or request_type == "unverified":
        return total_balance > 0
    else:
        return False

def check_authorization(request):
    """
    检查请求头中的 Authorization 字段
    是否匹配环境变量 AUTHORIZATION_KEY。
    """
    authorization_key = os.environ.get("AUTHORIZATION_KEY")
    if not authorization_key:
        logging.warning("环境变量 AUTHORIZATION_KEY 未设置,请设置后重试。")
        return False

    auth_header = request.headers.get('Authorization')
    if not auth_header:
        logging.warning("请求头中缺少 Authorization 字段。")
        return False

    if auth_header != f"Bearer {authorization_key}":
        logging.warning(f"无效的 Authorization 密钥:{auth_header}")
        return False

    return True

scheduler = BackgroundScheduler()
scheduler.add_job(load_keys, 'interval', hours=1)
scheduler.remove_all_jobs()
scheduler.add_job(refresh_models, 'interval', hours=1)

@app.route('/')
def index():
    current_time = time.time()
    one_minute_ago = current_time - 60

    with data_lock:
        while request_timestamps and request_timestamps[0] < one_minute_ago:
            request_timestamps.pop(0)
            token_counts.pop(0)

        rpm = len(request_timestamps)
        tpm = sum(token_counts)

    return jsonify({"rpm": rpm, "tpm": tpm})

@app.route('/check_tokens', methods=['POST'])
def check_tokens():
    tokens = request.json.get('tokens', [])
    test_model = os.environ.get(
        "TEST_MODEL",
        "Pro/google/gemma-2-9b-it"
    )

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=20
    ) as executor:
        future_to_token = {
            executor.submit(
                process_key, token, test_model
            ): token for token in tokens
        }

        results = []
        for future in concurrent.futures.as_completed(future_to_token):
            token = future_to_token[future]
            try:
                key_type = future.result()
                credit_summary = get_credit_summary(token)
                balance = (
                    credit_summary.get("total_balance", 0)
                    if credit_summary else 0
                )
                if key_type == "invalid":
                    results.append(
                        {
                            "token": token,
                            "type": "无效 KEY",
                            "balance": balance,
                            "message": "无法获取额度信息"
                        }
                    )
                elif key_type == "free":
                    results.append(
                        {
                            "token": token,
                            "type": "免费 KEY",
                            "balance": balance,
                            "message": "额度不足"
                        }
                    )
                elif key_type == "unverified":
                    results.append(
                        {
                            "token": token,
                            "type": "未实名 KEY",
                            "balance": balance,
                            "message": "无法使用指定模型"
                        }
                    )
                elif key_type == "valid":
                    results.append(
                        {
                            "token": token,
                            "type": "有效 KEY",
                            "balance": balance,
                            "message": "可以使用指定模型"
                        }
                    )
            except Exception as exc:
                logging.error(
                    f"处理 Token {token} 生成异常: {exc}"
                )

    return jsonify(results)
            
@app.route('/handsome/v1/models', methods=['GET'])
def list_models():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    detailed_models = []
    
    for model in text_models:
        detailed_models.append({
            "id": model,
            "object": "model",
            "created": 1678888888,
            "owned_by": "openai",
            "permission": [
                {
                    "id": f"modelperm-{uuid.uuid4().hex}",
                    "object": "model_permission",
                    "created": 1678888888,
                    "allow_create_engine": False,
                    "allow_sampling": True,
                    "allow_logprobs": True,
                    "allow_search_indices": False,
                    "allow_view": True,
                    "allow_fine_tuning": False,
                    "organization": "*",
                    "group": None,
                    "is_blocking": False
                }
            ],
            "root": model,
            "parent": None
        })

    for model in embedding_models:
        detailed_models.append({
            "id": model,
            "object": "model",
            "created": 1678888888,
            "owned_by": "openai",
            "permission": [
                {
                    "id": f"modelperm-{uuid.uuid4().hex}",
                    "object": "model_permission",
                    "created": 1678888888,
                    "allow_create_engine": False,
                    "allow_sampling": True,
                    "allow_logprobs": True,
                    "allow_search_indices": False,
                    "allow_view": True,
                    "allow_fine_tuning": False,
                    "organization": "*",
                    "group": None,
                    "is_blocking": False
                }
            ],
            "root": model,
            "parent": None
        })
    
    for model in image_models:
        detailed_models.append({
            "id": model,
            "object": "model",
            "created": 1678888888,
            "owned_by": "openai",
            "permission": [
                {
                    "id": f"modelperm-{uuid.uuid4().hex}",
                    "object": "model_permission",
                    "created": 1678888888,
                    "allow_create_engine": False,
                    "allow_sampling": True,
                    "allow_logprobs": True,
                    "allow_search_indices": False,
                    "allow_view": True,
                    "allow_fine_tuning": False,
                    "organization": "*",
                    "group": None,
                    "is_blocking": False
                }
            ],
            "root": model,
            "parent": None
        })

    return jsonify({
        "success": True,
        "data": detailed_models
    })

def get_billing_info():
    keys = valid_keys_global + unverified_keys_global
    total_balance = 0

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=20
    ) as executor:
        futures = [
            executor.submit(get_credit_summary, key) for key in keys
        ]

        for future in concurrent.futures.as_completed(futures):
            try:
                credit_summary = future.result()
                if credit_summary:
                    total_balance += credit_summary.get(
                        "total_balance",
                        0
                    )
            except Exception as exc:
                logging.error(f"获取额度信息生成异常: {exc}")

    return total_balance

@app.route('/handsome/v1/dashboard/billing/usage', methods=['GET'])
def billing_usage():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)

    daily_usage = []
    current_date = start_date
    while current_date <= end_date:
        daily_usage.append({
            "timestamp": int(current_date.timestamp()),
            "daily_usage": 0
        })
        current_date += timedelta(days=1)

    return jsonify({
        "object": "list",
        "data": daily_usage,
        "total_usage": 0
    })

@app.route('/handsome/v1/dashboard/billing/subscription', methods=['GET'])
def billing_subscription():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    total_balance = get_billing_info()

    return jsonify({
        "object": "billing_subscription",
        "has_payment_method": False,
        "canceled": False,
        "canceled_at": None,
        "delinquent": None,
        "access_until": int(datetime(9999, 12, 31).timestamp()),
        "soft_limit": 0,
        "hard_limit": total_balance,
        "system_hard_limit": total_balance,
        "soft_limit_usd": 0,
        "hard_limit_usd": total_balance,
        "system_hard_limit_usd": total_balance,
        "plan": {
            "name": "SiliconFlow API",
            "id": "siliconflow-api"
        },
        "account_name": "SiliconFlow User",
        "po_number": None,
        "billing_email": None,
        "tax_ids": [],
        "billing_address": None,
        "business_address": None
    })

@app.route('/handsome/v1/embeddings', methods=['POST'])
def handsome_embeddings():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    data = request.get_json()
    if not data or 'model' not in data:
        return jsonify({"error": "Invalid request data"}), 400

    model_name = data['model']
    request_type = determine_request_type(
        model_name,
        embedding_models,
        free_embedding_models
    )
    api_key = select_key(request_type, model_name)

    if not api_key:
        return jsonify(
            {
                "error": (
                    "No available API key for this "
                    "request type or all keys have "
                    "reached their limits"
                )
            }
        ), 429

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    try:
        start_time = time.time()
        response = requests.post(
            EMBEDDINGS_ENDPOINT,
            headers=headers,
            json=data,
            timeout=120
        )

        if response.status_code == 429:
            return jsonify(response.json()), 429

        response.raise_for_status()
        end_time = time.time()
        response_json = response.json()
        total_time = end_time - start_time

        try:
            prompt_tokens = response_json["usage"]["prompt_tokens"]
            embedding_data = response_json["data"]
        except (KeyError, ValueError, IndexError) as e:
            logging.error(
                f"解析响应 JSON 失败: {e}, "
                f"完整内容: {response_json}"
            )
            prompt_tokens = 0
            embedding_data = []

        logging.info(
            f"使用的key: {api_key}, "
            f"提示token: {prompt_tokens}, "
            f"总共用时: {total_time:.4f}秒, "
            f"使用的模型: {model_name}"
        )

        with data_lock:
            request_timestamps.append(time.time())
            token_counts.append(prompt_tokens)
        
        return jsonify({
            "object": "list",
            "data": embedding_data,
            "model": model_name,
            "usage": {
                "prompt_tokens": prompt_tokens,
                "total_tokens": prompt_tokens
            }
        })

    except requests.exceptions.RequestException as e:
        return jsonify({"error": str(e)}), 500

@app.route('/handsome/v1/images/generations', methods=['POST'])
def handsome_images_generations():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    data = request.get_json()
    if not data or 'model' not in data:
        return jsonify({"error": "Invalid request data"}), 400

    model_name = data.get('model')
    
    request_type = determine_request_type(
        model_name,
        image_models,
        free_image_models
    )
    
    api_key = select_key(request_type, model_name)

    if not api_key:
         return jsonify(
             {
                 "error": (
                     "No available API key for this "
                     "request type or all keys have "
                     "reached their limits"
                 )
             }
         ), 429
    
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    response_data = {}
    
    if "stable-diffusion" in model_name or model_name in ["black-forest-labs/FLUX.1-schnell", "Pro/black-forest-labs/FLUX.1-schnell","black-forest-labs/FLUX.1-dev", "black-forest-labs/FLUX.1-pro"]:
        siliconflow_data = {
            "model": model_name,
            "prompt": data.get("prompt"),
            
        }
        
        if model_name == "black-forest-labs/FLUX.1-pro":
            siliconflow_data["width"] = data.get("width", 1024)
            siliconflow_data["height"] = data.get("height", 768)
            siliconflow_data["prompt_upsampling"] = data.get("prompt_upsampling", False)
            siliconflow_data["image_prompt"] = data.get("image_prompt")
            siliconflow_data["steps"] = data.get("steps", 20)
            siliconflow_data["guidance"] = data.get("guidance", 3)
            siliconflow_data["safety_tolerance"] = data.get("safety_tolerance", 2)
            siliconflow_data["interval"] = data.get("interval", 2)
            siliconflow_data["output_format"] = data.get("output_format", "png")
            seed = data.get("seed")
            if isinstance(seed, int) and 0 < seed < 9999999999:
                siliconflow_data["seed"] = seed

            if siliconflow_data["width"] < 256 or siliconflow_data["width"] > 1440 or siliconflow_data["width"] % 32 != 0:
                siliconflow_data["width"] = 1024
            if siliconflow_data["height"] < 256 or siliconflow_data["height"] > 1440 or siliconflow_data["height"] % 32 != 0:
                 siliconflow_data["height"] = 768

            if siliconflow_data["steps"] < 1 or siliconflow_data["steps"] > 50:
                siliconflow_data["steps"] = 20
            if siliconflow_data["guidance"] < 1.5 or siliconflow_data["guidance"] > 5:
                 siliconflow_data["guidance"] = 3
            if siliconflow_data["safety_tolerance"] < 0 or siliconflow_data["safety_tolerance"] > 6:
                siliconflow_data["safety_tolerance"] = 2
            if siliconflow_data["interval"] < 1 or siliconflow_data["interval"] > 4 :
                 siliconflow_data["interval"] = 2
        else:    
            siliconflow_data["image_size"] = data.get("image_size", "1024x1024") 
            siliconflow_data["prompt_enhancement"] = data.get("prompt_enhancement", False)
            seed = data.get("seed")
            if isinstance(seed, int) and 0 < seed < 9999999999:
                siliconflow_data["seed"] = seed
        
            if model_name not in ["black-forest-labs/FLUX.1-schnell", "Pro/black-forest-labs/FLUX.1-schnell"]:
                siliconflow_data["batch_size"] = data.get("n", 1)
                siliconflow_data["num_inference_steps"] = data.get("steps", 20)
                siliconflow_data["guidance_scale"] = data.get("guidance_scale", 7.5)
                siliconflow_data["negative_prompt"] = data.get("negative_prompt")
                if siliconflow_data["batch_size"] < 1:
                    siliconflow_data["batch_size"] = 1
                if siliconflow_data["batch_size"] > 4:
                    siliconflow_data["batch_size"] = 4

                if siliconflow_data["num_inference_steps"] < 1:
                    siliconflow_data["num_inference_steps"] = 1
                if siliconflow_data["num_inference_steps"] > 50:
                    siliconflow_data["num_inference_steps"] = 50
                    
                if siliconflow_data["guidance_scale"] < 0:
                    siliconflow_data["guidance_scale"] = 0
                if siliconflow_data["guidance_scale"] > 100:
                    siliconflow_data["guidance_scale"] = 100

        if "image_size" in siliconflow_data and siliconflow_data["image_size"] not in ["1024x1024", "512x1024", "768x512", "768x1024", "1024x576", "576x1024","960x1280", "720x1440", "720x1280"]:
            siliconflow_data["image_size"] = "1024x1024"

        try:
            start_time = time.time()
            response = requests.post(
                "https://api.siliconflow.cn/v1/images/generations",
                headers=headers,
                json=siliconflow_data,
                timeout=120
            )

            if response.status_code == 429:
                return jsonify(response.json()), 429

            response.raise_for_status()
            end_time = time.time()
            response_json = response.json()
            total_time = end_time - start_time
            
            try:
                images = response_json.get("images", [])
                openai_images = []
                for item in images:
                    if isinstance(item, dict) and "url" in item:
                        image_url = item["url"]
                        print(f"image_url: {image_url}")
                        if data.get("response_format") == "b64_json":
                           try:
                                image_data = requests.get(image_url, stream=True).raw
                                image = Image.open(image_data)
                                buffered = io.BytesIO()
                                image.save(buffered, format="PNG")
                                img_str = base64.b64encode(buffered.getvalue()).decode()
                                openai_images.append({"b64_json": img_str})
                           except Exception as e:
                                logging.error(f"图片转base64失败: {e}")
                                openai_images.append({"url": image_url})
                        else:
                            openai_images.append({"url": image_url})
                    else:
                        logging.error(f"无效的图片数据: {item}")
                        openai_images.append({"url": item})


                response_data = {
                    "created": int(time.time()),
                    "data": openai_images
                }
            except (KeyError, ValueError, IndexError) as e:
                logging.error(
                    f"解析响应 JSON 失败: {e}, "
                    f"完整内容: {response_json}"
                )
                response_data = {
                    "created": int(time.time()),
                    "data": []
                }

            logging.info(
                f"使用的key: {api_key}, "
                f"总共用时: {total_time:.4f}秒, "
                f"使用的模型: {model_name}"
            )

            with data_lock:
                request_timestamps.append(time.time())
                token_counts.append(0)

            return jsonify(response_data)

        except requests.exceptions.RequestException as e:
            logging.error(f"请求转发异常: {e}")
            return jsonify({"error": str(e)}), 500
    else:
        return jsonify({"error": "Unsupported model"}), 400

@app.route('/handsome/v1/chat/completions', methods=['POST'])
def handsome_chat_completions():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    data = request.get_json()
    if not data or 'model' not in data:
        return jsonify({"error": "Invalid request data"}), 400

    model_name = data['model']
    
    request_type = determine_request_type(
        model_name,
        text_models + image_models,
        free_text_models + free_image_models
    )
    
    api_key = select_key(request_type, model_name)

    if not api_key:
        return jsonify(
            {
                "error": (
                    "No available API key for this "
                    "request type or all keys have "
                    "reached their limits"
                )
            }
        ), 429

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    if model_name in image_models:
        user_content = ""
        messages = data.get("messages", [])
        for message in messages:
            if message["role"] == "user":
                if isinstance(message["content"], str):
                    user_content += message["content"] + " "
                elif isinstance(message["content"], list):
                    for item in message["content"]:
                        if (
                            isinstance(item, dict) and
                            item.get("type") == "text"
                        ):
                            user_content += (
                                item.get("text", "") +
                                " "
                            )
        user_content = user_content.strip()

        siliconflow_data = {
            "model": model_name,
            "prompt": user_content,
            
        }
        if model_name == "black-forest-labs/FLUX.1-pro":
            siliconflow_data["width"] = data.get("width", 1024)
            siliconflow_data["height"] = data.get("height", 768)
            siliconflow_data["prompt_upsampling"] = data.get("prompt_upsampling", False)
            siliconflow_data["image_prompt"] = data.get("image_prompt")
            siliconflow_data["steps"] = data.get("steps", 20)
            siliconflow_data["guidance"] = data.get("guidance", 3)
            siliconflow_data["safety_tolerance"] = data.get("safety_tolerance", 2)
            siliconflow_data["interval"] = data.get("interval", 2)
            siliconflow_data["output_format"] = data.get("output_format", "png")
            seed = data.get("seed")
            if isinstance(seed, int) and 0 < seed < 9999999999:
                siliconflow_data["seed"] = seed
            if siliconflow_data["width"] < 256 or siliconflow_data["width"] > 1440 or siliconflow_data["width"] % 32 != 0:
                siliconflow_data["width"] = 1024
            if siliconflow_data["height"] < 256 or siliconflow_data["height"] > 1440 or siliconflow_data["height"] % 32 != 0:
                 siliconflow_data["height"] = 768

            if siliconflow_data["steps"] < 1 or siliconflow_data["steps"] > 50:
                siliconflow_data["steps"] = 20
            if siliconflow_data["guidance"] < 1.5 or siliconflow_data["guidance"] > 5:
                 siliconflow_data["guidance"] = 3
            if siliconflow_data["safety_tolerance"] < 0 or siliconflow_data["safety_tolerance"] > 6:
                siliconflow_data["safety_tolerance"] = 2
            if siliconflow_data["interval"] < 1 or siliconflow_data["interval"] > 4 :
                 siliconflow_data["interval"] = 2
        else:
            siliconflow_data["image_size"] = "1024x1024"
            siliconflow_data["batch_size"] = 1
            siliconflow_data["num_inference_steps"] = 20
            siliconflow_data["guidance_scale"] = 7.5
            siliconflow_data["prompt_enhancement"] = False
        
            if data.get("size"):
                siliconflow_data["image_size"] = data.get("size")
            if data.get("n"):
                siliconflow_data["batch_size"] = data.get("n")
            if data.get("steps"):
                siliconflow_data["num_inference_steps"] = data.get("steps")
            if data.get("guidance_scale"):
               siliconflow_data["guidance_scale"] = data.get("guidance_scale")
            if data.get("negative_prompt"):
               siliconflow_data["negative_prompt"] = data.get("negative_prompt")
            if data.get("seed"):
               siliconflow_data["seed"] = data.get("seed")
            if data.get("prompt_enhancement"):
               siliconflow_data["prompt_enhancement"] = data.get("prompt_enhancement")

            if siliconflow_data["batch_size"] < 1:
                siliconflow_data["batch_size"] = 1
            if siliconflow_data["batch_size"] > 4:
                siliconflow_data["batch_size"] = 4

            if siliconflow_data["num_inference_steps"] < 1:
                siliconflow_data["num_inference_steps"] = 1
            if siliconflow_data["num_inference_steps"] > 50:
                siliconflow_data["num_inference_steps"] = 50
                
            if siliconflow_data["guidance_scale"] < 0:
                siliconflow_data["guidance_scale"] = 0
            if siliconflow_data["guidance_scale"] > 100:
                siliconflow_data["guidance_scale"] = 100
            
            if siliconflow_data["image_size"] not in ["1024x1024", "512x1024", "768x512", "768x1024", "1024x576", "576x1024", "960x1280", "720x1440", "720x1280"]:
                siliconflow_data["image_size"] = "1024x1024"

        try:
            start_time = time.time()
            response = requests.post(
                "https://api.siliconflow.cn/v1/images/generations",
                headers=headers,
                json=siliconflow_data,
                timeout=120,
                stream=data.get("stream", False)
            )
           
            if response.status_code == 429:
                return jsonify(response.json()), 429

            if data.get("stream", False):
                def generate():
                    first_chunk_time = None
                    full_response_content = ""
                    try:
                        response.raise_for_status()
                        end_time = time.time()
                        response_json = response.json()
                        total_time = end_time - start_time
                    
                        images = response_json.get("images", [])
                        
                        image_url = ""
                        if images and isinstance(images[0], dict) and "url" in images[0]:
                            image_url = images[0]["url"]
                            logging.info(f"Extracted image URL: {image_url}")
                        elif images and isinstance(images[0], str):
                            image_url = images[0]
                            logging.info(f"Extracted image URL: {image_url}")
                        
                        markdown_image_link = f"![image]({image_url})"
                        if image_url:
                            chunk_data = {
                                "id": f"chatcmpl-{uuid.uuid4()}",
                                "object": "chat.completion.chunk",
                                "created": int(time.time()),
                                "model": model_name,
                                "choices": [
                                    {
                                        "index": 0,
                                        "delta": {
                                            "role": "assistant",
                                            "content": markdown_image_link
                                        },
                                        "finish_reason": None
                                    }
                                ]
                            }
                            yield f"data: {json.dumps(chunk_data)}\n\n".encode('utf-8')
                            full_response_content = markdown_image_link
                        else:
                            chunk_data = {
                                "id": f"chatcmpl-{uuid.uuid4()}",
                                "object": "chat.completion.chunk",
                                "created": int(time.time()),
                                "model": model_name,
                                "choices": [
                                    {
                                        "index": 0,
                                        "delta": {
                                            "role": "assistant",
                                            "content": "Failed to generate image"
                                        },
                                        "finish_reason": None
                                    }
                                ]
                            }
                            yield f"data: {json.dumps(chunk_data)}\n\n".encode('utf-8')
                            full_response_content = "Failed to generate image"
                        
                        end_chunk_data = {
                            "id": f"chatcmpl-{uuid.uuid4()}",
                            "object": "chat.completion.chunk",
                            "created": int(time.time()),
                            "model": model_name,
                            "choices": [
                                {
                                    "index": 0,
                                    "delta": {},
                                    "finish_reason": "stop"
                                }
                            ]
                        }
                        yield f"data: {json.dumps(end_chunk_data)}\n\n".encode('utf-8')
                        with data_lock:
                            request_timestamps.append(time.time())
                            token_counts.append(0)
                    except requests.exceptions.RequestException as e:
                        logging.error(f"请求转发异常: {e}")
                        error_chunk_data = {
                            "id": f"chatcmpl-{uuid.uuid4()}",
                            "object": "chat.completion.chunk",
                            "created": int(time.time()),
                            "model": model_name,
                            "choices": [
                                {
                                    "index": 0,
                                    "delta": {
                                        "role": "assistant",
                                        "content": f"Error: {str(e)}"
                                    },
                                    "finish_reason": None
                                }
                            ]
                        }
                        yield f"data: {json.dumps(error_chunk_data)}\n\n".encode('utf-8')
                        end_chunk_data = {
                                "id": f"chatcmpl-{uuid.uuid4()}",
                                "object": "chat.completion.chunk",
                                "created": int(time.time()),
                                "model": model_name,
                                "choices": [
                                    {
                                        "index": 0,
                                        "delta": {},
                                        "finish_reason": "stop"
                                    }
                                ]
                            }
                        yield f"data: {json.dumps(end_chunk_data)}\n\n".encode('utf-8')
                    logging.info(
                        f"使用的key: {api_key}, "
                        f"使用的模型: {model_name}"
                    )
                    yield "data: [DONE]\n\n".encode('utf-8')
                return Response(stream_with_context(generate()), content_type='text/event-stream')

            else:
                response.raise_for_status()
                end_time = time.time()
                response_json = response.json()
                total_time = end_time - start_time
            
                try:
                    images = response_json.get("images", [])
                    
                    image_url = ""
                    if images and isinstance(images[0], dict) and "url" in images[0]:
                        image_url = images[0]["url"]
                        logging.info(f"Extracted image URL: {image_url}")
                    elif images and isinstance(images[0], str):
                        image_url = images[0]
                        logging.info(f"Extracted image URL: {image_url}")
                    
                    markdown_image_link = f"![image]({image_url})"
                    response_data = {
                        "id": f"chatcmpl-{uuid.uuid4()}",
                        "object": "chat.completion",
                        "created": int(time.time()),
                        "model": model_name,
                        "choices": [
                            {
                            "index": 0,
                            "message": {
                                "role": "assistant",
                                "content": markdown_image_link if image_url else "Failed to generate image",
                            },
                            "finish_reason": "stop",
                            }
                        ],
                    }
                except (KeyError, ValueError, IndexError) as e:
                    logging.error(
                        f"解析响应 JSON 失败: {e}, "
                        f"完整内容: {response_json}"
                    )
                    response_data = {
                        "id": f"chatcmpl-{uuid.uuid4()}",
                        "object": "chat.completion",
                        "created": int(time.time()),
                        "model": model_name,
                        "choices": [
                            {
                            "index": 0,
                            "message": {
                                "role": "assistant",
                                "content": "Failed to process image data",
                            },
                            "finish_reason": "stop",
                            }
                        ],
                    }

                logging.info(
                    f"使用的key: {api_key}, "
                    f"总共用时: {total_time:.4f}秒, "
                    f"使用的模型: {model_name}"
                )
                with data_lock:
                    request_timestamps.append(time.time())
                    token_counts.append(0)
                return jsonify(response_data)

        except requests.exceptions.RequestException as e:
            logging.error(f"请求转发异常: {e}")
            return jsonify({"error": str(e)}), 500
    else:
        try:
            start_time = time.time()
            response = requests.post(
                TEST_MODEL_ENDPOINT,
                headers=headers,
                json=data,
                stream=data.get("stream", False),
                timeout=60
            )

            if response.status_code == 429:
                return jsonify(response.json()), 429

            if data.get("stream", False):
                def generate():
                    first_chunk_time = None
                    full_response_content = ""
                    for chunk in response.iter_content(chunk_size=1024):
                        if chunk:
                            if first_chunk_time is None:
                                first_chunk_time = time.time()
                            full_response_content += chunk.decode("utf-8")
                            yield chunk

                    end_time = time.time()
                    first_token_time = (
                        first_chunk_time - start_time
                        if first_chunk_time else 0
                    )
                    total_time = end_time - start_time

                    prompt_tokens = 0
                    completion_tokens = 0
                    response_content = ""
                    for line in full_response_content.splitlines():
                        if line.startswith("data:"):
                            line = line[5:].strip()
                            if line == "[DONE]":
                                continue
                            try:
                                response_json = json.loads(line)

                                if (
                                    "usage" in response_json and
                                    "completion_tokens" in response_json["usage"]
                                ):
                                    completion_tokens = response_json[
                                        "usage"
                                    ]["completion_tokens"]

                                if (
                                    "choices" in response_json and
                                    len(response_json["choices"]) > 0 and
                                    "delta" in response_json["choices"][0] and
                                    "content" in response_json[
                                        "choices"
                                    ][0]["delta"]
                                ):
                                    response_content += response_json[
                                        "choices"
                                    ][0]["delta"]["content"]

                                if (
                                    "usage" in response_json and
                                    "prompt_tokens" in response_json["usage"]
                                ):
                                    prompt_tokens = response_json[
                                        "usage"
                                    ]["prompt_tokens"]

                            except (
                                KeyError,
                                ValueError,
                                IndexError
                            ) as e:
                                logging.error(
                                    f"解析流式响应单行 JSON 失败: {e}, "
                                    f"行内容: {line}"
                                )

                    user_content = ""
                    messages = data.get("messages", [])
                    for message in messages:
                        if message["role"] == "user":
                            if isinstance(message["content"], str):
                                user_content += message["content"] + " "
                            elif isinstance(message["content"], list):
                                for item in message["content"]:
                                    if (
                                        isinstance(item, dict) and
                                        item.get("type") == "text"
                                    ):
                                        user_content += (
                                            item.get("text", "") +
                                            " "
                                        )

                    user_content = user_content.strip()

                    user_content_replaced = user_content.replace(
                        '\n', '\\n'
                    ).replace('\r', '\\n')
                    response_content_replaced = response_content.replace(
                        '\n', '\\n'
                    ).replace('\r', '\\n')

                    logging.info(
                        f"使用的key: {api_key}, "
                        f"提示token: {prompt_tokens}, "
                        f"输出token: {completion_tokens}, "
                        f"首字用时: {first_token_time:.4f}秒, "
                        f"总共用时: {total_time:.4f}秒, "
                        f"使用的模型: {model_name}, "
                        f"用户的内容: {user_content_replaced}, "
                        f"输出的内容: {response_content_replaced}"
                    )

                    with data_lock:
                        request_timestamps.append(time.time())
                        token_counts.append(prompt_tokens+completion_tokens)

                return Response(
                    stream_with_context(generate()),
                    content_type=response.headers['Content-Type']
                )
            else:
                response.raise_for_status()
                end_time = time.time()
                response_json = response.json()
                total_time = end_time - start_time

                try:
                    prompt_tokens = response_json["usage"]["prompt_tokens"]
                    completion_tokens = response_json[
                        "usage"
                    ]["completion_tokens"]
                    response_content = response_json[
                        "choices"
                    ][0]["message"]["content"]
                except (KeyError, ValueError, IndexError) as e:
                    logging.error(
                        f"解析非流式响应 JSON 失败: {e}, "
                        f"完整内容: {response_json}"
                    )
                    prompt_tokens = 0
                    completion_tokens = 0
                    response_content = ""

                user_content = ""
                messages = data.get("messages", [])
                for message in messages:
                    if message["role"] == "user":
                        if isinstance(message["content"], str):
                            user_content += message["content"] + " "
                        elif isinstance(message["content"], list):
                            for item in message["content"]:
                                if (
                                    isinstance(item, dict) and
                                    item.get("type") == "text"
                                ):
                                    user_content += (
                                        item.get("text", "") + " "
                                    )

                user_content = user_content.strip()

                user_content_replaced = user_content.replace(
                    '\n', '\\n'
                ).replace('\r', '\\n')
                response_content_replaced = response_content.replace(
                    '\n', '\\n'
                ).replace('\r', '\\n')

                logging.info(
                    f"使用的key: {api_key}, "
                    f"提示token: {prompt_tokens}, "
                    f"输出token: {completion_tokens}, "
                    f"首字用时: 0, "
                    f"总共用时: {total_time:.4f}秒, "
                    f"使用的模型: {model_name}, "
                    f"用户的内容: {user_content_replaced}, "
                    f"输出的内容: {response_content_replaced}"
                )
                with data_lock:
                    request_timestamps.append(time.time())
                    if "prompt_tokens" in response_json["usage"] and "completion_tokens" in response_json["usage"]:
                        token_counts.append(response_json["usage"]["prompt_tokens"] + response_json["usage"]["completion_tokens"])
                    else:
                        token_counts.append(0)

                return jsonify(response_json)

        except requests.exceptions.RequestException as e:
            logging.error(f"请求转发异常: {e}")
            return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    import json
    logging.info(f"环境变量:{os.environ}")

    invalid_keys_global = []
    free_keys_global = []
    unverified_keys_global = []
    valid_keys_global = []

    load_keys()
    logging.info("程序启动时首次加载 keys 已执行")

    scheduler.start()

    logging.info("首次加载 keys 已手动触发执行")

    refresh_models()
    logging.info("首次刷新模型列表已手动触发执行")

    app.run(
        debug=False,
        host='0.0.0.0',
        port=int(os.environ.get('PORT', 7860))
    )