File size: 65,179 Bytes
8889bbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
# Copyright: DAMO Academy, Alibaba Group
# By Xuan Phi Nguyen at DAMO Academy, Alibaba Group

# Description:
"""
VLLM-based demo script to launch Language chat model for Southeast Asian Languages
"""


import os
import numpy as np
import argparse
import torch
import gradio as gr
from typing import Any, Iterator
from typing import Iterator, List, Optional, Tuple
import filelock
import glob
import json
import time
from gradio.routes import Request
from gradio.utils import SyncToAsyncIterator, async_iteration
from gradio.helpers import special_args
import anyio
from typing import AsyncGenerator, Callable, Literal, Union, cast

from gradio_client.documentation import document, set_documentation_group

from typing import List, Optional, Union, Dict, Tuple
from tqdm.auto import tqdm
from huggingface_hub import snapshot_download


# @@ environments ================

DEBUG = bool(int(os.environ.get("DEBUG", "1")))

# List of languages to block
BLOCK_LANGS = str(os.environ.get("BLOCK_LANGS", ""))
BLOCK_LANGS = [x.strip() for x in BLOCK_LANGS.strip().split(";")] if len(BLOCK_LANGS.strip()) > 0 else []

# for lang block, wether to block in history too
LANG_BLOCK_HISTORY = bool(int(os.environ.get("LANG_BLOCK_HISTORY", "0")))
TENSOR_PARALLEL = int(os.environ.get("TENSOR_PARALLEL", "1"))
DTYPE = os.environ.get("DTYPE", "bfloat16")

# ! (no debug) whether to download HF_MODEL_NAME and save to MODEL_PATH
DOWNLOAD_SNAPSHOT = bool(int(os.environ.get("DOWNLOAD_SNAPSHOT", "0")))
LOG_RESPONSE = bool(int(os.environ.get("LOG_RESPONSE", "0")))
# ! show model path in the demo page, only for internal
DISPLAY_MODEL_PATH = bool(int(os.environ.get("DISPLAY_MODEL_PATH", "1")))

# ! uploaded model path, will be downloaded to MODEL_PATH
HF_MODEL_NAME = os.environ.get("HF_MODEL_NAME", "DAMO-NLP-SG/seal-13b-chat-a")
# ! if model is private, need HF_TOKEN to access the model
HF_TOKEN = os.environ.get("HF_TOKEN", None)
# ! path where the model is downloaded, either on ./ or persistent disc
MODEL_PATH = os.environ.get("MODEL_PATH", "./seal-13b-chat-a")

# ! log path
LOG_PATH = os.environ.get("LOG_PATH", "").strip()
LOG_FILE = None
SAVE_LOGS = LOG_PATH is not None and LOG_PATH != ''
if SAVE_LOGS:
    if os.path.exists(LOG_PATH):
        print(f'LOG_PATH exist: {LOG_PATH}')
    else:
        LOG_DIR = os.path.dirname(LOG_PATH)
        os.makedirs(LOG_DIR, exist_ok=True)

# ! get LOG_PATH as aggregated outputs in log
GET_LOG_CMD = os.environ.get("GET_LOG_CMD", "").strip()

print(f'SAVE_LOGS: {SAVE_LOGS} | {LOG_PATH}')
# print(f'GET_LOG_CMD: {GET_LOG_CMD}')

# ! !! Whether to delete the folder, ONLY SET THIS IF YOU WANT TO DELETE SAVED MODEL ON PERSISTENT DISC
DELETE_FOLDER = os.environ.get("DELETE_FOLDER", "")
IS_DELETE_FOLDER = DELETE_FOLDER is not None and os.path.exists(DELETE_FOLDER)
print(f'DELETE_FOLDER: {DELETE_FOLDER} | {DOWNLOAD_SNAPSHOT=}')

# ! list of keywords to disabled as security measures to comply with local regulation
KEYWORDS = os.environ.get("KEYWORDS", "").strip()
KEYWORDS = KEYWORDS.split(";") if len(KEYWORDS) > 0 else []
KEYWORDS = [x.lower() for x in KEYWORDS]

# bypass
BYPASS_USERS = os.environ.get("BYPASS_USERS", "").strip()
BYPASS_USERS = BYPASS_USERS.split(";") if len(BYPASS_USERS) > 0 else []

# gradio config
PORT = int(os.environ.get("PORT", "7860"))
# how many iterations to yield response
STREAM_YIELD_MULTIPLE = int(os.environ.get("STREAM_YIELD_MULTIPLE", "1"))
# how many iterations to perform safety check on response
STREAM_CHECK_MULTIPLE = int(os.environ.get("STREAM_CHECK_MULTIPLE", "0"))

# whether to enable to popup accept user
ENABLE_AGREE_POPUP = bool(int(os.environ.get("ENABLE_AGREE_POPUP", "0")))

# self explanatory
MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "2048"))
TEMPERATURE = float(os.environ.get("TEMPERATURE", "0.1"))
FREQUENCE_PENALTY = float(os.environ.get("FREQUENCE_PENALTY", "0.1"))
PRESENCE_PENALTY = float(os.environ.get("PRESENCE_PENALTY", "0.0"))
gpu_memory_utilization = float(os.environ.get("gpu_memory_utilization", "0.9"))

# whether to enable quantization, currently not in use
QUANTIZATION = str(os.environ.get("QUANTIZATION", ""))


# Batch inference file upload
ENABLE_BATCH_INFER = bool(int(os.environ.get("ENABLE_BATCH_INFER", "1")))
BATCH_INFER_MAX_ITEMS = int(os.environ.get("BATCH_INFER_MAX_ITEMS", "100"))
BATCH_INFER_MAX_FILE_SIZE = int(os.environ.get("BATCH_INFER_MAX_FILE_SIZE", "500"))
BATCH_INFER_MAX_PROMPT_TOKENS = int(os.environ.get("BATCH_INFER_MAX_PROMPT_TOKENS", "4000"))
BATCH_INFER_SAVE_TMP_FILE = os.environ.get("BATCH_INFER_SAVE_TMP_FILE", "./tmp/pred.json")

# 
DATA_SET_REPO_PATH = str(os.environ.get("DATA_SET_REPO_PATH", ""))
DATA_SET_REPO = None

"""
Internal instructions of how to configure the DEMO

1. Upload SFT model as a model to huggingface: hugginface/models/seal_13b_a
2. If the model weights is private, set HF_TOKEN=<your private hf token> in https://huggingface.co/spaces/????/?????/settings
3. space config env: `HF_MODEL_NAME=SeaLLMs/seal-13b-chat-a` or the underlining model
4. If enable persistent storage: set
HF_HOME=/data/.huggingface
MODEL_PATH=/data/.huggingface/seal-13b-chat-a
if not:
MODEL_PATH=./seal-13b-chat-a


HF_HOME=/data/.huggingface
MODEL_PATH=/data/ckpt/seal-13b-chat-a
DELETE_FOLDER=/data/

"""

# ==============================
print(f'DEBUG mode: {DEBUG}')
print(f'Torch version: {torch.__version__}')
try:
    print(f'Torch CUDA version: {torch.version.cuda}')
except Exception as e:
    print(f'Failed to print cuda version: {e}')

try:
    compute_capability = torch.cuda.get_device_capability()
    print(f'Torch CUDA compute_capability: {compute_capability}')
except Exception as e:
    print(f'Failed to print compute_capability version: {e}')


# @@ constants ================

DTYPES = {
    'float16': torch.float16,
    'bfloat16': torch.bfloat16
}

llm = None
demo = None


BOS_TOKEN = '<s>'
EOS_TOKEN = '</s>'


SYSTEM_PROMPT_1 = """You are a helpful, respectful, honest and safe AI assistant built by Alibaba Group."""



# ######### RAG PREPARE
RAG_CURRENT_FILE, RAG_EMBED, RAG_CURRENT_VECTORSTORE = None, None, None

# RAG_EMBED_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
RAG_EMBED_MODEL_NAME = "sentence-transformers/LaBSE"


def load_embeddings():
    global RAG_EMBED
    if RAG_EMBED is None:
        from langchain_community.embeddings import HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings
        print(f'LOading embeddings: {RAG_EMBED_MODEL_NAME}')
        RAG_EMBED = HuggingFaceEmbeddings(model_name=RAG_EMBED_MODEL_NAME, model_kwargs={'trust_remote_code':True, "device": "cpu"})
    else:
        print(f'RAG_EMBED ALREADY EXIST: {RAG_EMBED_MODEL_NAME}: {RAG_EMBED=}')
    return RAG_EMBED


def get_rag_embeddings():
    return load_embeddings()

_ = get_rag_embeddings()

RAG_CURRENT_VECTORSTORE = None

def load_document_split_vectorstore(file_path):
    global RAG_CURRENT_FILE, RAG_EMBED, RAG_CURRENT_VECTORSTORE
    from langchain.text_splitter import RecursiveCharacterTextSplitter
    from langchain_community.embeddings import HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings
    from langchain_community.vectorstores import Chroma, FAISS
    from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
    # assert RAG_EMBED is not None
    splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=50)
    if file_path.endswith('.pdf'):
        loader = PyPDFLoader(file_path)
    elif file_path.endswith('.docx'):
        loader = Docx2txtLoader(file_path)
    elif file_path.endswith('.txt'):
        loader = TextLoader(file_path)
    splits = loader.load_and_split(splitter)
    RAG_CURRENT_VECTORSTORE = FAISS.from_texts(texts=[s.page_content for s in splits], embedding=get_rag_embeddings())
    return RAG_CURRENT_VECTORSTORE


def docs_to_rag_context(docs: List[str]):
    contexts = "\n".join([d.page_content for d in docs])
    context = f"""Answer the following query exclusively based on the information provided in the document above. \
If the information is not found, please say so instead of making up facts! Remember to answer the question in the same language as the user query!
###
{contexts}
###


"""
    return context

def maybe_get_doc_context(message, file_input, rag_num_docs: Optional[int] = 3):
    global RAG_CURRENT_FILE, RAG_EMBED, RAG_CURRENT_VECTORSTORE
    doc_context = None
    if file_input is not None:
        assert os.path.exists(file_input), f"not found: {file_input}"
        if file_input == RAG_CURRENT_FILE:
            # reuse
            vectorstore = RAG_CURRENT_VECTORSTORE
            print(f'Reuse vectorstore: {file_input}')
        else:
            vectorstore = load_document_split_vectorstore(file_input)
            print(f'New vectorstore: {RAG_CURRENT_FILE} {file_input}')
            RAG_CURRENT_FILE = file_input
        docs = vectorstore.similarity_search(message, k=rag_num_docs)
        doc_context = docs_to_rag_context(docs)
    return doc_context

# ######### RAG PREPARE


# ============ CONSTANT ============
# https://github.com/gradio-app/gradio/issues/884
MODEL_NAME = "SeaLLM-7B"
MODEL_NAME = str(os.environ.get("MODEL_NAME", "SeaLLM-7B"))

MODEL_TITLE = """
<div class="container" style="
    align-items: center;
    justify-content: center;
    display: flex;
">  
    <div class="image" >
        <img src="file/seal_logo.png" style="
            max-width: 10em;
            max-height: 5%;
            height: 3em;
            width: 3em;
            float: left;
            margin-left: auto;
        ">
    </div>
    <div class="text" style="
        padding-left: 20px;
        padding-top: 1%;
        float: left;
    ">
        <h1 style="font-size: xx-large">SeaLLMs - Large Language Models for Southeast Asia</h1>
    </div>
</div>
"""

MODEL_TITLE = """
<img src="file/seal_logo.png" style="
    max-width: 10em;
    max-height: 5%;
    height: 3em;
    width: 3em;
">
<div class="text" style="
loat: left;
padding-bottom: 2%;
">
SeaLLMs - Large Language Models for Southeast Asia
</div>
"""

"""
Somehow cannot add image here
<div class="image" >
    <img src="file/seal_logo.png" style="
        max-width: 10em;
        max-height: 5%;
        height: 3em;
        width: 3em;
        float: left;
        margin-left: auto;
    ">
</div>
"""

MODEL_DESC = f"""
<div style='display:flex; gap: 0.25rem; '>
<a href='https://github.com/damo-nlp-sg/seallms'><img src='https://img.shields.io/badge/Github-Code-success'></a>
<a href='https://huggingface.co/spaces/SeaLLMs/SeaLLM-7B'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a> 
<a href='https://huggingface.co/SeaLLMs/SeaLLM-7B-v2'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Model-blue'></a> 
<a href='https://arxiv.org/pdf/2312.00738.pdf'><img src='https://img.shields.io/badge/Paper-PDF-red'></a>
</div>
<span style="font-size: larger">
<a href="https://huggingface.co/SeaLLMs/SeaLLM-7B-v2" target="_blank">{MODEL_NAME}-v2</a> - a helpful assistant for Southeast Asian Languages  🇬🇧 🇻🇳 🇮🇩 🇹🇭 🇲🇾 🇰🇭 🇱🇦 🇵🇭 🇲🇲.
Explore <a href="https://huggingface.co/SeaLLMs/SeaLLM-7B-v2" target="_blank">our article</a> for more.
</span>
<br>
<span>
<span style="color: red">NOTE: The chatbot may produce false and harmful content and does not have up-to-date knowledge.</span> 
By using our service, you are required to agree to our <a href="https://huggingface.co/SeaLLMs/SeaLLM-Chat-13b/blob/main/LICENSE" target="_blank" style="color: red">Terms Of Use</a>, which includes 
not to use our service to generate any harmful, inappropriate or illegal content. 
The service collects user dialogue data for testing and improvement under 
<a href="https://creativecommons.org/licenses/by/4.0/">(CC-BY)</a> or similar license. So do not enter any personal information!
</span>
""".strip()


cite_markdown = """
## Citation
If you find our project useful, hope you can star our repo and cite our paper as follows:
```
@article{damonlpsg2023seallm,
  author = {Xuan-Phi Nguyen*, Wenxuan Zhang*, Xin Li*, Mahani Aljunied*, Zhiqiang Hu, Chenhui Shen^, Yew Ken Chia^, Xingxuan Li, Jianyu Wang, Qingyu Tan, Liying Cheng, Guanzheng Chen, Yue Deng, Sen Yang, Chaoqun Liu, Hang Zhang, Lidong Bing},
  title = {SeaLLMs - Large Language Models for Southeast Asia},
  year = 2023,
}
```
"""

path_markdown = """
#### Model path:
{model_path}
"""



# ! ==================================================================

set_documentation_group("component")


RES_PRINTED = False


@document()
class ChatBot(gr.Chatbot):
    def _postprocess_chat_messages(
        self, chat_message
    ):
        x = super()._postprocess_chat_messages(chat_message)
        # if isinstance(x, str):
        #     x = x.strip().replace("\n", "<br>")
        return x


from gradio.components import Button
from gradio.events import Dependency, EventListenerMethod

# replace events so that submit button is disabled during generation, if stop_btn not found
# this prevent weird behavior
def _setup_stop_events(
    self, event_triggers: list[EventListenerMethod], event_to_cancel: Dependency
) -> None:
    from gradio.components import State
    event_triggers = event_triggers if isinstance(event_triggers, (list, tuple)) else [event_triggers]
    if self.stop_btn and self.is_generator:
        if self.submit_btn:
            for event_trigger in event_triggers:
                event_trigger(
                    lambda: (
                        Button(visible=False),
                        Button(visible=True),
                    ),
                    None,
                    [self.submit_btn, self.stop_btn],
                    api_name=False,
                    queue=False,
                )
            event_to_cancel.then(
                lambda: (Button(visible=True), Button(visible=False)),
                None,
                [self.submit_btn, self.stop_btn],
                api_name=False,
                queue=False,
            )
        else:
            for event_trigger in event_triggers:
                event_trigger(
                    lambda: Button(visible=True),
                    None,
                    [self.stop_btn],
                    api_name=False,
                    queue=False,
                )
            event_to_cancel.then(
                lambda: Button(visible=False),
                None,
                [self.stop_btn],
                api_name=False,
                queue=False,
            )
        self.stop_btn.click(
            None,
            None,
            None,
            cancels=event_to_cancel,
            api_name=False,
        )
    else:
        if self.submit_btn:
            for event_trigger in event_triggers:
                event_trigger(
                    lambda: Button(interactive=False),
                    None,
                    [self.submit_btn],
                    api_name=False,
                    queue=False,
                )
            event_to_cancel.then(
                lambda: Button(interactive=True),
                None,
                [self.submit_btn],
                api_name=False,
                queue=False,
            )
    # upon clear, cancel the submit event as well
    if self.clear_btn:
        self.clear_btn.click(
            lambda: ([], [], None, Button(interactive=True)),
            None,
            [self.chatbot, self.chatbot_state, self.saved_input, self.submit_btn],
            queue=False,
            api_name=False,
            cancels=event_to_cancel,
        )

# TODO: reconfigure clear button as stop and clear button
def _setup_events(self) -> None:
    from gradio.components import State
    has_on = False
    try:
        from gradio.events import Dependency, EventListenerMethod, on
        has_on = True
    except ImportError as ie:
        has_on = False
    submit_fn = self._stream_fn if self.is_generator else self._submit_fn

    def update_time(c_time, chatbot_state):
        # if chatbot_state is empty, register a new conversaion with the current timestamp
        # assert len(chatbot_state) > 0, f'empty chatbot state'
        if len(chatbot_state) <= 1:
            return gr.Number(value=time.time(), label='current_time', visible=False), chatbot_state
        # elif len(chatbot_state) == 1:
        #     # assert chatbot_state[-1][-1] is None, f'invalid [[message, None]] , got {chatbot_state}'
        #     return gr.Number(value=time.time(), label='current_time', visible=False), chatbot_state
        else:
            return c_time, chatbot_state

    if has_on:
        # new version
        submit_triggers = (
            [self.textbox.submit, self.submit_btn.click]
            if self.submit_btn
            else [self.textbox.submit]
        )
        submit_event = (
            on(
                submit_triggers,
                self._clear_and_save_textbox,
                [self.textbox],
                [self.textbox, self.saved_input],
                api_name=False,
                queue=False,
            )
            .then(
                self._display_input,
                [self.saved_input, self.chatbot_state],
                [self.chatbot, self.chatbot_state],
                api_name=False,
                queue=False,
            )
            .then(
                update_time,
                [self.additional_inputs[-1], self.chatbot_state],
                [self.additional_inputs[-1], self.chatbot_state],
                api_name=False,
                queue=False,
            )
            .then(
                submit_fn,
                [self.saved_input, self.chatbot_state] + self.additional_inputs,
                [self.chatbot, self.chatbot_state],
                api_name=False,
            )
        )
        self._setup_stop_events(submit_triggers, submit_event)
    else:
        raise ValueError(f'Better install new gradio version than 3.44.0')

    if self.retry_btn:
        retry_event = (
            self.retry_btn.click(
                self._delete_prev_fn,
                [self.chatbot_state],
                [self.chatbot, self.saved_input, self.chatbot_state],
                api_name=False,
                queue=False,
            )
            .then(
                self._display_input,
                [self.saved_input, self.chatbot_state],
                [self.chatbot, self.chatbot_state],
                api_name=False,
                queue=False,
            )
            .then(
                submit_fn,
                [self.saved_input, self.chatbot_state] + self.additional_inputs,
                [self.chatbot, self.chatbot_state],
                api_name=False,
            )
        )
        self._setup_stop_events([self.retry_btn.click], retry_event)

    if self.undo_btn:
        self.undo_btn.click(
            self._delete_prev_fn,
            [self.chatbot_state],
            [self.chatbot, self.saved_input, self.chatbot_state],
            api_name=False,
            queue=False,
        ).then(
            lambda x: x,
            [self.saved_input],
            [self.textbox],
            api_name=False,
            queue=False,
        )

    # Reconfigure clear_btn to stop and clear text box


def _display_input(
        self, message: str, history: List[List[Union[str, None]]]
    ) -> Tuple[List[List[Union[str, None]]], List[List[list[Union[str, None]]]]]:
    if message is not None and message.strip() != "":
        history.append([message, None])
    return history, history


async def _stream_fn(
    self,
    message: str,
    history_with_input,
    request: Request,
    *args,
) -> AsyncGenerator:
    history = history_with_input[:-1]
    inputs, _, _ = special_args(
        self.fn, inputs=[message, history, *args], request=request
    )

    if self.is_async:
        generator = self.fn(*inputs)
    else:
        generator = await anyio.to_thread.run_sync(
            self.fn, *inputs, limiter=self.limiter
        )
        generator = SyncToAsyncIterator(generator, self.limiter)
    try:
        first_response = await async_iteration(generator)
        update = history + [[message, first_response]]
        yield update, update
    except StopIteration:
        update = history + [[message, None]]
        yield update, update
    except Exception as e:
        yield history, history
        raise e

    try:
        async for response in generator:
            update = history + [[message, response]]
            yield update, update
    except Exception as e:
        # if "invalid" in str(e):
        #     yield history, history
        #     raise e
        # else:
        #     raise e
        yield history, history
        raise e




# replace
gr.ChatInterface._setup_stop_events = _setup_stop_events
gr.ChatInterface._setup_events = _setup_events
gr.ChatInterface._display_input = _display_input
gr.ChatInterface._stream_fn = _stream_fn


@document()
class CustomTabbedInterface(gr.Blocks):
    def __init__(
        self,
        interface_list: list[gr.Interface],
        tab_names: Optional[list[str]] = None,
        title: Optional[str] = None,
        description: Optional[str] = None,
        theme: Optional[gr.Theme] = None,
        analytics_enabled: Optional[bool] = None,
        css: Optional[str] = None,
    ):
        """
        Parameters:
            interface_list: a list of interfaces to be rendered in tabs.
            tab_names: a list of tab names. If None, the tab names will be "Tab 1", "Tab 2", etc.
            title: a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window.
            analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
            css: custom css or path to custom css file to apply to entire Blocks
        Returns:
            a Gradio Tabbed Interface for the given interfaces
        """
        super().__init__(
            title=title or "Gradio",
            theme=theme,
            analytics_enabled=analytics_enabled,
            mode="tabbed_interface",
            css=css,
        )
        self.description = description
        if tab_names is None:
            tab_names = [f"Tab {i}" for i in range(len(interface_list))]
        with self:
            if title:
                gr.Markdown(
                    f"<h1 style='text-align: center; margin-bottom: 1rem'>{title}</h1>"
                )
            if description:
                gr.Markdown(description)
            with gr.Tabs():
                for interface, tab_name in zip(interface_list, tab_names):
                    with gr.Tab(label=tab_name):
                        interface.render()


def vllm_abort(self):
    sh = self.llm_engine.scheduler
    for g in (sh.waiting + sh.running + sh.swapped):
        sh.abort_seq_group(g.request_id)
    from vllm.sequence import SequenceStatus
    scheduler = self.llm_engine.scheduler
    for state_queue in [scheduler.waiting, scheduler.running, scheduler.swapped]:
        for seq_group in state_queue:
            # if seq_group.request_id == request_id:
            # Remove the sequence group from the state queue.
            state_queue.remove(seq_group)
            for seq in seq_group.seqs:
                if seq.is_finished():
                    continue
                scheduler.free_seq(seq, SequenceStatus.FINISHED_ABORTED)


def _vllm_run_engine(self: Any, use_tqdm: bool = False) -> Dict[str, Any]:
    from vllm.outputs import RequestOutput
    # Initialize tqdm.
    if use_tqdm:
        num_requests = self.llm_engine.get_num_unfinished_requests()
        pbar = tqdm(total=num_requests, desc="Processed prompts")
    # Run the engine.
    outputs: Dict[str, RequestOutput] = {}
    while self.llm_engine.has_unfinished_requests():
        step_outputs = self.llm_engine.step()
        for output in step_outputs:
            outputs[output.request_id] = output
        if len(outputs) > 0:
            yield outputs



def vllm_generate_stream(
    self: Any,
    prompts: Optional[Union[str, List[str]]] = None,
    sampling_params: Optional[Any] = None,
    prompt_token_ids: Optional[List[List[int]]] = None,
    use_tqdm: bool = False,
) -> Dict[str, Any]:
    """Generates the completions for the input prompts.

    NOTE: This class automatically batches the given prompts, considering
    the memory constraint. For the best performance, put all of your prompts
    into a single list and pass it to this method.

    Args:
        prompts: A list of prompts to generate completions for.
        sampling_params: The sampling parameters for text generation. If
            None, we use the default sampling parameters.
        prompt_token_ids: A list of token IDs for the prompts. If None, we
            use the tokenizer to convert the prompts to token IDs.
        use_tqdm: Whether to use tqdm to display the progress bar.

    Returns:
        A list of `RequestOutput` objects containing the generated
        completions in the same order as the input prompts.
    """
    from vllm import LLM, SamplingParams
    if prompts is None and prompt_token_ids is None:
        raise ValueError("Either prompts or prompt_token_ids must be "
                            "provided.")
    if isinstance(prompts, str):
        # Convert a single prompt to a list.
        prompts = [prompts]
    if prompts is not None and prompt_token_ids is not None:
        if len(prompts) != len(prompt_token_ids):
            raise ValueError("The lengths of prompts and prompt_token_ids "
                                "must be the same.")
    if sampling_params is None:
        # Use default sampling params.
        sampling_params = SamplingParams()

    # Add requests to the engine.
    if prompts is not None:
        num_requests = len(prompts)
    else:
        num_requests = len(prompt_token_ids)
    for i in range(num_requests):
        prompt = prompts[i] if prompts is not None else None
        if prompt_token_ids is None:
            token_ids = None
        else:
            token_ids = prompt_token_ids[i]
        self._add_request(prompt, sampling_params, token_ids)
    # return self._run_engine(use_tqdm)
    yield from _vllm_run_engine(self, use_tqdm)



# ! avoid saying 
# LANG_BLOCK_MESSAGE = """Sorry, the language you have asked is currently not supported. If you have questions in other supported languages, I'll be glad to help. \
# Please also consider clearing the chat box for a better experience."""

# KEYWORD_BLOCK_MESSAGE = "Sorry, I cannot fulfill your request. If you have any unrelated question, I'll be glad to help."

LANG_BLOCK_MESSAGE = """Unsupported language."""

KEYWORD_BLOCK_MESSAGE = "Invalid request."


def _detect_lang(text):
    # Disable language that may have safety risk
    from langdetect import detect as detect_lang
    dlang = None
    try:
        dlang = detect_lang(text)
    except Exception as e:
        if "No features in text." in str(e):
            return "en"
        else:
            return "zh"
    return dlang


def block_lang(
    message: str, 
    history: List[Tuple[str, str]] = None,
) -> str:
    # relieve history base block
    if len(BLOCK_LANGS) == 0:
        return False
    
    if LANG_BLOCK_HISTORY and history is not None and any((LANG_BLOCK_MESSAGE in x[1].strip()) for x in history):
        return True
    else:
        _lang = _detect_lang(message)
        if _lang in BLOCK_LANGS:
            print(f'Detect blocked {_lang}: {message}')
            return True
        else:
            return False


def safety_check(text, history=None, ) -> Optional[str]:
    """
    Despite our effort in safety tuning and red teaming, our models may still generate harmful or illegal content.
    This provides an additional security measure to enhance safety and compliance with local regulations.
    """
    if len(KEYWORDS) > 0 and any(x in text.lower() for x in KEYWORDS):
        return KEYWORD_BLOCK_MESSAGE
    
    if len(BLOCK_LANGS) > 0:
        if block_lang(text, history):
            return LANG_BLOCK_MESSAGE

    return None



TURN_TEMPLATE = "<|im_start|>{role}\n{content}</s>"
TURN_PREFIX = "<|im_start|>{role}\n"


def chatml_chat_convo_format(conversations, add_assistant_prefix: bool, default_system=SYSTEM_PROMPT_1):
    if conversations[0]['role'] != 'system':
        conversations = [{"role": "system", "content": default_system}] + conversations
    text = ''
    for turn_id, turn in enumerate(conversations):
        prompt = TURN_TEMPLATE.format(role=turn['role'], content=turn['content'])
        text += prompt
    if add_assistant_prefix:
        prompt = TURN_PREFIX.format(role='assistant')
        text += prompt    
    return text


def chatml_format(message, history=None, system_prompt=None):
    conversations = []
    system_prompt = system_prompt or "You are a helpful assistant."
    if history is not None and len(history) > 0:
        for i, (prompt, res) in enumerate(history):
            conversations.append({"role": "user", "content": prompt.strip()})
            conversations.append({"role": "assistant", "content": res.strip()})
    conversations.append({"role": "user", "content": message.strip()})
    return chatml_chat_convo_format(conversations, True, default_system=system_prompt)


def debug_chat_response_stream_multiturn(message, history):
    message_safety = safety_check(message, history=history)
    if message_safety is not None:
        # yield message_safety
        raise gr.Error(message_safety)
    
    message = "This is a debugging message"
    for i in range(len(message)):
        time.sleep(0.05)
        yield message[:i]



def chat_response_stream_multiturn(
    message: str, 
    history: List[Tuple[str, str]], 
    temperature: float, 
    max_tokens: int, 
    frequency_penalty: float,
    presence_penalty: float,
    system_prompt: Optional[str] = SYSTEM_PROMPT_1,
    current_time: Optional[float] = None,
    # profile: Optional[gr.OAuthProfile] = None,
) -> str:
    """
    gr.Number(value=temperature, label='Temperature (higher -> more random)'), 
            gr.Number(value=max_tokens, label='Max generated tokens (increase if want more generation)'), 
            gr.Number(value=frequence_penalty, label='Frequency penalty (> 0 encourage new tokens over repeated tokens)'), 
            gr.Number(value=presence_penalty, label='Presence penalty (> 0 encourage new tokens, < 0 encourage existing tokens)'), 
            gr.Textbox(value=sys_prompt, label='System prompt', lines=8, interactive=False),
            gr.Number(value=0, label='current_time', visible=False), 
    """
    global LOG_FILE, LOG_PATH
    if DEBUG:
        yield from debug_chat_response_stream_multiturn(message, history)
        return
    from vllm import LLM, SamplingParams
    """Build multi turn

    message is incoming prompt
    history don't have the current messauge
    """
    global llm, RES_PRINTED
    assert llm is not None
    assert system_prompt.strip() != '', f'system prompt is empty'
    # is_by_pass = False if profile is None else profile.username in BYPASS_USERS
    is_by_pass = False
    
    tokenizer = llm.get_tokenizer()
    # force removing all 
    vllm_abort(llm)

    temperature = float(temperature)
    frequency_penalty = float(frequency_penalty)
    max_tokens = int(max_tokens)

    message = message.strip()

    if GET_LOG_CMD != "" and message.strip() == GET_LOG_CMD:
        print_log_file()
        yield "Finish printed log. Please clear the chatbox now."
        return 

    if len(message) == 0:
        raise gr.Error("The message cannot be empty!")

    message_safety = safety_check(message, history=history)
    if message_safety is not None and not is_by_pass:
        # yield message_safety
        raise gr.Error(message_safety)

    # history will be appended with message later on
    
    full_prompt = chatml_format(message.strip(), history=history, system_prompt=system_prompt)
    print(full_prompt)

    if len(tokenizer.encode(full_prompt)) >= 4050:
        raise gr.Error(f"Conversation or prompt is too long, please clear the chatbox or try shorter input.")

    sampling_params = SamplingParams(
        temperature=temperature, 
        max_tokens=max_tokens,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        # stop=['<s>', '</s>', '<<SYS>>', '<</SYS>>', '[INST]', '[/INST]'],
        stop=['<s>', '</s>', '<|im_start|>', '<|im_end|>'],
    )
    cur_out = None

    for j, gen in enumerate(vllm_generate_stream(llm, full_prompt, sampling_params)):
        if cur_out is not None and (STREAM_YIELD_MULTIPLE < 1 or j % STREAM_YIELD_MULTIPLE == 0) and j > 0:
            # cur_out = cur_out.replace("\\n", "\n")
            
            # optionally check safety, and respond
            if STREAM_CHECK_MULTIPLE > 0 and j % STREAM_CHECK_MULTIPLE == 0:
                message_safety = safety_check(cur_out, history=None)
                if message_safety is not None and not is_by_pass:
                    # yield message_safety
                    raise gr.Error(message_safety)
                    # return

            yield cur_out
        assert len(gen) == 1, f'{gen}'
        item = next(iter(gen.values()))
        cur_out = item.outputs[0].text
        #cur_out = "Our system is under maintenance, will be back soon!"
        if j >= max_tokens - 2:
            gr.Warning(f'The response hits limit of {max_tokens} tokens. Consider increase the max tokens parameter in the Additional Inputs.')
    
    # TODO: use current_time to register conversations, accoriding history and cur_out
    history_str = format_conversation(history + [[message, cur_out]])
    print(f'@@@@@@@@@@\n{history_str}\n##########\n')

    maybe_log_conv_file(current_time, history, message, cur_out, temperature=temperature, frequency_penalty=frequency_penalty)
    
    if cur_out is not None and "\\n" in cur_out:
        print(f'double slash-n in cur_out:\n{cur_out}')
        cur_out = cur_out.replace("\\n", "\n")

    if cur_out is not None:
        yield cur_out
    
    message_safety = safety_check(cur_out, history=None)
    if message_safety is not None and not is_by_pass:
        # yield message_safety
        raise gr.Error(message_safety)
        # return
    


def chat_response_stream_rag_multiturn(
    message: str, 
    history: List[Tuple[str, str]], 
    file_input: str,
    temperature: float,
    max_tokens: int,
    # frequency_penalty: float,
    # presence_penalty: float,
    system_prompt: Optional[str] = SYSTEM_PROMPT_1,
    current_time: Optional[float] = None,
    rag_num_docs: Optional[int] = 3,
):
    message = message.strip()
    frequency_penalty = FREQUENCE_PENALTY
    presence_penalty = PRESENCE_PENALTY
    if len(message) == 0:
        raise gr.Error("The message cannot be empty!")
    doc_context = maybe_get_doc_context(message, file_input, rag_num_docs=rag_num_docs)
    if doc_context is not None:
        message = f"{doc_context}\n\n{message}"
    yield from chat_response_stream_multiturn(
        message, history, temperature, max_tokens, frequency_penalty,
        presence_penalty, system_prompt, current_time
    )


def debug_generate_free_form_stream(message):
    output = " This is a debugging message...."
    for i in range(len(output)):
        time.sleep(0.05)
        yield message + output[:i]


def generate_free_form_stream(
    message: str, 
    temperature: float, 
    max_tokens: int, 
    frequency_penalty: float,
    presence_penalty: float,
    stop_strings: str = '<s>,</s>,<|im_start|>,<|im_end|>',
    current_time: Optional[float] = None,
) -> str:
    global LOG_FILE, LOG_PATH
    if DEBUG:
        yield from debug_generate_free_form_stream(message)
        return
    from vllm import LLM, SamplingParams
    """Build multi turn
    """
    global llm, RES_PRINTED
    assert llm is not None
    tokenizer = llm.get_tokenizer()
    # force removing all 
    vllm_abort(llm)

    temperature = float(temperature)
    frequency_penalty = float(frequency_penalty)
    max_tokens = int(max_tokens)

    stop_strings = [x.strip() for x in stop_strings.strip().split(",")]
    stop_strings = list(set(stop_strings + ['</s>', '<|im_start|>']))

    sampling_params = SamplingParams(
        temperature=temperature, 
        max_tokens=max_tokens,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        stop=stop_strings,
        # ignore_eos=True,
    )

    # full_prompt = message
    if len(message) == 0:
        raise gr.Error("The message cannot be empty!")
    
    message_safety = safety_check(message)
    if message_safety is not None:
        raise gr.Error(message_safety)

    if len(tokenizer.encode(message)) >= 4050:
        raise gr.Error(f"Prompt is too long!")
    
    cur_out = None
    for j, gen in enumerate(vllm_generate_stream(llm, message, sampling_params)):
        if cur_out is not None and (STREAM_YIELD_MULTIPLE < 1 or j % STREAM_YIELD_MULTIPLE == 0) and j > 0:
            # optionally check safety, and respond
            if STREAM_CHECK_MULTIPLE > 0 and j % STREAM_CHECK_MULTIPLE == 0:
                message_safety = safety_check(cur_out, history=None)
                if message_safety is not None:
                    raise gr.Error(message_safety)
            yield message + cur_out
        assert len(gen) == 1, f'{gen}'
        item = next(iter(gen.values()))
        cur_out = item.outputs[0].text
        #cur_out = "Our system is under maintenance, will be back soon!"
        if j >= max_tokens - 2:
            gr.Warning(f'The response hits limit of {max_tokens} tokens. Consider increase the max tokens parameter in the Additional Inputs.')

    if cur_out is not None:
        yield message + cur_out
    
    message_safety = safety_check(message + cur_out, history=None)
    if message_safety is not None:
        raise gr.Error(message_safety)




def maybe_log_conv_file(current_time, history, message, response, **kwargs):
    global LOG_FILE
    if LOG_FILE is not None:
        my_history = history + [[message, response]]
        obj = {
            'key': str(current_time),
            'history': my_history
        }
        for k, v in kwargs.items():
            obj[k] = v
        log_ = json.dumps(obj, ensure_ascii=False)
        LOG_FILE.write(log_ + "\n")
        LOG_FILE.flush()
        print(f'Wrote {obj["key"]} to {LOG_PATH}')


def format_conversation(history):
    _str = '\n'.join([
        (
            f'<<<User>>> {h[0]}\n'
            f'<<<Asst>>> {h[1]}'
        )
        for h in history
    ])
    return _str


def aggregate_convos():
    from datetime import datetime
    global LOG_FILE, DATA_SET_REPO_PATH, SAVE_LOGS
    assert os.path.exists(LOG_PATH), f'{LOG_PATH} not found'
    convos = None
    irregular_count = 1
    with open(LOG_PATH, 'r', encoding='utf-8') as f:
        convos = {}
        for i, l in enumerate(f):
            if l:
                item = json.loads(l)
                key = item['key']
                try:
                    key = float(key)
                except Exception as e:
                    key = -1
                if key > 0.0:
                    item_key = datetime.fromtimestamp(key).strftime("%Y-%m-%d %H:%M:%S")
                else:
                    key = item_key = f'e{irregular_count}'
                    irregular_count += 1
                item['key'] = item_key
                convos[key] = item
    return convos

def maybe_upload_to_dataset():
    from datetime import datetime
    global LOG_FILE, DATA_SET_REPO_PATH, SAVE_LOGS
    if SAVE_LOGS and os.path.exists(LOG_PATH) and DATA_SET_REPO_PATH != "":
        convos = aggregate_convos()
        AGG_LOG_PATH = LOG_PATH + ".agg.json"
        with open(AGG_LOG_PATH, 'w', encoding='utf-8') as fo:
            json.dump(convos, fo, indent=4, ensure_ascii=False)
        print(f'Saved aggregated json to {AGG_LOG_PATH}')
        try:
            from huggingface_hub import upload_file
            print(f'upload {AGG_LOG_PATH} to {DATA_SET_REPO_PATH}')
            upload_file(
                path_or_fileobj=AGG_LOG_PATH,
                path_in_repo=os.path.basename(AGG_LOG_PATH),
                repo_id=DATA_SET_REPO_PATH,
                token=HF_TOKEN,
                repo_type="dataset",
                create_pr=True
            )
        except Exception as e:
            print(f'Failed to save to repo: {DATA_SET_REPO_PATH}|{str(e)}')


def print_log_file():
    global LOG_FILE, LOG_PATH
    if SAVE_LOGS and os.path.exists(LOG_PATH):
        with open(LOG_PATH, 'r', encoding='utf-8') as f:
            convos = aggregate_convos()
            print(f'Printing log from {LOG_PATH}')
            items = list(convos.items())
            for k, v in items[-10:]:
                history = v.pop('history')
                print(f'######--{v}--#####')
                _str = format_conversation(history)
                print(_str)
        maybe_upload_to_dataset()


def debug_chat_response_echo(
    message: str, 
    history: List[Tuple[str, str]], 
    temperature: float = 0.0, 
    max_tokens: int = 4096, 
    frequency_penalty: float = 0.4,
    presence_penalty: float = 0.0,
    current_time: Optional[float] = None,
    system_prompt: str = SYSTEM_PROMPT_1,
) -> str:
    global LOG_FILE
    import time
    time.sleep(0.5)

    if message.strip() == GET_LOG_CMD:
        print_log_file()
        yield "Finish printed log."
        return 

    for i in range(len(message)):
        yield f"repeat: {current_time} {message[:i + 1]}"
    
    cur_out = f"repeat: {current_time} {message}"
    maybe_log_conv_file(current_time, history, message, cur_out, temperature=temperature, frequency_penalty=frequency_penalty)


def check_model_path(model_path) -> str:
    assert os.path.exists(model_path), f'{model_path} not found'
    ckpt_info = "None"
    if os.path.isdir(model_path):
        if os.path.exists(f'{model_path}/info.txt'):
            with open(f'{model_path}/info.txt', 'r') as f:
                ckpt_info = f.read()
                print(f'Checkpoint info:\n{ckpt_info}\n-----')
        else:
            print(f'info.txt not found in {model_path}')
        print(f'model path dir: {list(os.listdir(model_path))}')
    
    return ckpt_info


def maybe_delete_folder():
    if IS_DELETE_FOLDER and DOWNLOAD_SNAPSHOT:
        import shutil
        print(f'DELETE ALL FILES IN {DELETE_FOLDER}')
        for filename in os.listdir(DELETE_FOLDER):
            file_path = os.path.join(DELETE_FOLDER, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print('Failed to delete %s. Reason: %s' % (file_path, e))


AGREE_POP_SCRIPTS = """
async () => {
    alert("To use our service, you are required to agree to the following terms:\\nYou must not use our service to generate any harmful, unethical or illegal content that violates local and international laws, including but not limited to hate speech, violence and deception.\\nThe service may collect user dialogue data for performance improvement, and reserves the right to distribute it under CC-BY or similar license. So do not enter any personal information!");
}
"""

def debug_file_function(
        files: Union[str, List[str]],
        prompt_mode: str,
        temperature: float, 
        max_tokens: int, 
        frequency_penalty: float,
        presence_penalty: float,
        stop_strings: str = "[STOP],<s>,</s>",
        current_time: Optional[float] = None,          
):
    """This is only for debug purpose"""
    files = files if isinstance(files, list) else [files]
    print(files)
    filenames = [f.name for f in files]
    all_items = []
    for fname in filenames:
        print(f'Reading {fname}')
        with open(fname, 'r', encoding='utf-8') as f:
            items = json.load(f)
        assert isinstance(items, list), f'invalid items from {fname} not list'
        all_items.extend(items)
    print(all_items)
    print(f'{prompt_mode} / {temperature} / {max_tokens}, {frequency_penalty}, {presence_penalty}')
    save_path = "./test.json"
    with open(save_path, 'w', encoding='utf-8') as f:
        json.dump(all_items, f, indent=4, ensure_ascii=False)

    for x in all_items:
        x['response'] = "Return response"
    
    print_items = all_items[:1]
    # print_json = json.dumps(print_items, indent=4, ensure_ascii=False)
    return save_path, print_items


def validate_file_item(filename, index, item: Dict[str, str]):
    """
    check safety for items in files
    """
    message = item['prompt'].strip()

    if len(message) == 0:
        raise gr.Error(f'Prompt {index} empty')
    
    message_safety = safety_check(message, history=None)
    if message_safety is not None:
        raise gr.Error(f'Prompt {index} invalid: {message_safety}')
    
    tokenizer = llm.get_tokenizer() if llm is not None else None
    if tokenizer is None or len(tokenizer.encode(message)) >= BATCH_INFER_MAX_PROMPT_TOKENS:
        raise gr.Error(f"Prompt {index} too long, should be less than {BATCH_INFER_MAX_PROMPT_TOKENS} tokens")


def read_validate_json_files(files: Union[str, List[str]]):
    files = files if isinstance(files, list) else [files]
    filenames = [f.name for f in files]
    all_items = []
    for fname in filenames:
        # check each files
        print(f'Reading {fname}')
        with open(fname, 'r', encoding='utf-8') as f:
            items = json.load(f)
        assert isinstance(items, list), f'Data {fname} not list'
        assert all(isinstance(x, dict) for x in items), f'item in input file not list'
        assert all("prompt" in x for x in items), f'key prompt should be in dict item of input file'

        for i, x in enumerate(items):
            validate_file_item(fname, i, x)

        all_items.extend(items)

    if len(all_items) > BATCH_INFER_MAX_ITEMS:
        raise gr.Error(f"Num samples {len(all_items)} > {BATCH_INFER_MAX_ITEMS} allowed.")
    
    return all_items, filenames


def remove_gradio_cache(exclude_names=None):
    """remove gradio cache to avoid flooding"""
    import shutil
    for root, dirs, files in os.walk('/tmp/gradio/'):
        for f in files:
            # if not any(f in ef for ef in except_files):
            if exclude_names is None or not any(ef in f for ef in exclude_names):
                print(f'Remove: {f}')
                os.unlink(os.path.join(root, f))
        # for d in dirs:
        #     # if not any(d in ef for ef in except_files):
        #     if exclude_names is None or not any(ef in d for ef in exclude_names):
        #         print(f'Remove d: {d}')
        #         shutil.rmtree(os.path.join(root, d))


def maybe_upload_batch_set(pred_json_path):
    global LOG_FILE, DATA_SET_REPO_PATH, SAVE_LOGS

    if SAVE_LOGS and DATA_SET_REPO_PATH != "":
        try:
            from huggingface_hub import upload_file
            path_in_repo = "misc/" + os.path.basename(pred_json_path).replace(".json", f'.{time.time()}.json')
            print(f'upload {pred_json_path} to {DATA_SET_REPO_PATH}//{path_in_repo}')
            upload_file(
                path_or_fileobj=pred_json_path,
                path_in_repo=path_in_repo,
                repo_id=DATA_SET_REPO_PATH,
                token=HF_TOKEN,
                repo_type="dataset",
                create_pr=True
            )
        except Exception as e:
            print(f'Failed to save to repo: {DATA_SET_REPO_PATH}|{str(e)}')


def free_form_prompt(prompt, history=None, system_prompt=None):
    return prompt

def batch_inference(
        files: Union[str, List[str]], 
        prompt_mode: str,
        temperature: float, 
        max_tokens: int, 
        frequency_penalty: float,
        presence_penalty: float,
        stop_strings: str = "[STOP],<s>,</s>,<|im_start|>",
        current_time: Optional[float] = None,
        system_prompt: Optional[str] = SYSTEM_PROMPT_1
):
    """
    Handle file upload batch inference
    
    """
    global LOG_FILE, LOG_PATH, DEBUG, llm, RES_PRINTED
    if DEBUG:
        return debug_file_function(
            files, prompt_mode, temperature, max_tokens, 
            presence_penalty, stop_strings, current_time)
    
    from vllm import LLM, SamplingParams
    assert llm is not None
    # assert system_prompt.strip() != '', f'system prompt is empty'

    stop_strings = [x.strip() for x in stop_strings.strip().split(",")]
    tokenizer = llm.get_tokenizer()
    # force removing all 
    # NOTE: need to make sure all cached items are removed!!!!!!!!!
    vllm_abort(llm)

    temperature = float(temperature)
    frequency_penalty = float(frequency_penalty)
    max_tokens = int(max_tokens)

    all_items, filenames = read_validate_json_files(files)

    # remove all items in /tmp/gradio/
    remove_gradio_cache(exclude_names=['upload_chat.json', 'upload_few_shot.json'])

    if prompt_mode == 'chat':
        prompt_format_fn = chatml_format
    elif prompt_mode == 'few-shot':
        from functools import partial
        # prompt_format_fn = partial(
        #     chatml_format, include_end_instruct=False
        # )
        prompt_format_fn = free_form_prompt 
    else:
        raise gr.Error(f'Wrong mode {prompt_mode}')

    full_prompts = [
        prompt_format_fn(
            x['prompt'], [], sys_prompt=system_prompt
        )
        for i, x in enumerate(all_items)
    ]
    print(f'{full_prompts[0]}\n')
    
    if any(len(tokenizer.encode(x)) >= 4090 for x in full_prompts):
        raise gr.Error(f"Some prompt is too long!")

    stop_seq = list(set(['<s>', '</s>', '<<SYS>>', '<</SYS>>', '[INST]', '[/INST]'] + stop_strings))
    sampling_params = SamplingParams(
        temperature=temperature, 
        max_tokens=max_tokens,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        stop=stop_seq
    )

    generated = llm.generate(full_prompts, sampling_params, use_tqdm=False)
    responses = [g.outputs[0].text for g in generated]
    #responses = ["Our system is under maintenance, will be back soon!" for g in generated]
    if len(responses) != len(all_items):
        raise gr.Error(f'inconsistent lengths {len(responses)} != {len(all_items)}')

    for res, item in zip(responses, all_items):
        item['response'] = res

    save_path = BATCH_INFER_SAVE_TMP_FILE
    os.makedirs(os.path.dirname(save_path), exist_ok=True)
    with open(save_path, 'w', encoding='utf-8') as f:
        json.dump(all_items, f, indent=4, ensure_ascii=False)

    # You need to upload save_path as a new timestamp file.
    maybe_upload_batch_set(save_path)
    
    print_items = all_items[:2]
    # print_json = json.dumps(print_items, indent=4, ensure_ascii=False)
    return save_path, print_items
    

# BATCH_INFER_MAX_ITEMS
FILE_UPLOAD_DESCRIPTION = f"""Upload JSON file as list of dict with < {BATCH_INFER_MAX_ITEMS} items, \
each item has `prompt` key. We put guardrails to enhance safety, so do not input any harmful content or personal information! Re-upload the file after every submit. See the examples below.
```
[ {{"id": 0, "prompt": "Hello world"}} ,  {{"id": 1, "prompt": "Hi there?"}}]
```
"""

CHAT_EXAMPLES = [
    ["Hãy giải thích thuyết tương đối rộng."],
    ["Tolong bantu saya menulis email ke lembaga pemerintah untuk mencari dukungan finansial untuk penelitian AI."],
    ["แนะนำ 10 จุดหมายปลายทางในกรุงเทพฯ"],
]


# performance items

def create_free_form_generation_demo():
    global short_model_path
    max_tokens = MAX_TOKENS
    temperature = TEMPERATURE
    frequence_penalty = FREQUENCE_PENALTY
    presence_penalty = PRESENCE_PENALTY

    introduction = """
### Free-form | Put any context string (like few-shot prompts)
    """

    with gr.Blocks() as demo_free_form:
        gr.Markdown(introduction)

        with gr.Row():
            txt = gr.Textbox(
                scale=4,
                lines=16,
                show_label=False,
                placeholder="Enter any free form text and submit",
                container=False,
            )
        with gr.Row():
            free_submit_button = gr.Button('Submit')
        with gr.Row():
            temp = gr.Number(value=temperature, label='Temperature', info="Higher -> more random")
            length = gr.Number(value=max_tokens, label='Max tokens', info='Increase if want more generation')
            freq_pen = gr.Number(value=frequence_penalty, label='Frequency penalty', info='> 0 encourage new tokens over repeated tokens')
            pres_pen = gr.Number(value=presence_penalty, label='Presence penalty', info='> 0 encourage new tokens, < 0 encourage existing tokens')
            stop_strings = gr.Textbox(value="<s>,</s>,<|im_start|>", label='Stop strings', info='Comma-separated string to stop generation only in FEW-SHOT mode', lines=1)

        free_submit_button.click(
            generate_free_form_stream, 
            [txt, temp, length, freq_pen, pres_pen, stop_strings], 
            txt
        )
    return demo_free_form



def create_file_upload_demo():
    temperature = TEMPERATURE
    frequence_penalty = FREQUENCE_PENALTY
    presence_penalty = PRESENCE_PENALTY
    max_tokens = MAX_TOKENS
    demo_file_upload = gr.Interface(
        batch_inference,
        inputs=[
            gr.File(file_count='single', file_types=['json']),
            gr.Radio(["chat", "few-shot"], value='chat', label="Chat or Few-shot mode", info="Chat's output more user-friendly, Few-shot's output more consistent with few-shot patterns."),
            gr.Number(value=temperature, label='Temperature', info="Higher -> more random"), 
            gr.Number(value=max_tokens, label='Max tokens', info='Increase if want more generation'), 
            gr.Number(value=frequence_penalty, label='Frequency penalty', info='> 0 encourage new tokens over repeated tokens'), 
            gr.Number(value=presence_penalty, label='Presence penalty', info='> 0 encourage new tokens, < 0 encourage existing tokens'), 
            gr.Textbox(value="<s>,</s>,<|im_start|>", label='Stop strings', info='Comma-separated string to stop generation only in FEW-SHOT mode', lines=1),
            gr.Number(value=0, label='current_time', visible=False), 
        ],
        outputs=[
            # "file",
            gr.File(label="Generated file"),
            # "json"
            gr.JSON(label='Example outputs (display 2 samples)')
        ],
        description=FILE_UPLOAD_DESCRIPTION,
        allow_flagging=False,
        examples=[
            ["upload_chat.json", "chat", 0.2, 1024, 0.5, 0, "<s>,</s>,<|im_start|>"],
            ["upload_few_shot.json", "few-shot", 0.2, 128, 0.5, 0, "<s>,</s>,<|im_start|>,\\n"]
        ],
        cache_examples=False,
    )
    return demo_file_upload


def create_chat_demo(title=None, description=None):
    sys_prompt = SYSTEM_PROMPT_1
    max_tokens = MAX_TOKENS
    temperature = TEMPERATURE
    frequence_penalty = FREQUENCE_PENALTY
    presence_penalty = PRESENCE_PENALTY

    demo_chat = gr.ChatInterface(
        chat_response_stream_multiturn,
        chatbot=ChatBot(
            label=MODEL_NAME,
            bubble_full_width=False,
            latex_delimiters=[
                { "left": "$", "right": "$", "display": False},
                { "left": "$$", "right": "$$", "display": True},
            ],
            show_copy_button=True,
        ),
        textbox=gr.Textbox(placeholder='Type message', lines=1, max_lines=128, min_width=200),
        submit_btn=gr.Button(value='Submit', variant="primary", scale=0),
        # ! consider preventing the stop button
        # stop_btn=None,
        title=title,
        description=description,
        additional_inputs=[
            gr.Number(value=temperature, label='Temperature (higher -> more random)'), 
            gr.Number(value=max_tokens, label='Max generated tokens (increase if want more generation)'), 
            gr.Number(value=frequence_penalty, label='Frequency penalty (> 0 encourage new tokens over repeated tokens)'), 
            gr.Number(value=presence_penalty, label='Presence penalty (> 0 encourage new tokens, < 0 encourage existing tokens)'), 
            gr.Textbox(value=sys_prompt, label='System prompt', lines=4, interactive=False),
            gr.Number(value=0, label='current_time', visible=False), 
            # ! Remove the system prompt textbox to avoid jailbreaking
        ], 
        examples=CHAT_EXAMPLES,
        cache_examples=False
    )
    return demo_chat


def upload_file(file):
    # file_paths = [file.name for file in files]
    # return file_paths
    return file.name


RAG_DESCRIPTION = """
* Upload a doc below to answer question about it (RAG).
* Every question must be explicit and self-contained! Because each prompt will invoke a new RAG retrieval without considering previous conversations. 
(E.g: Dont prompt "Answer my previous question in details.")
"""

def create_chat_demo_rag(title=None, description=None):
    sys_prompt = SYSTEM_PROMPT_1
    max_tokens = MAX_TOKENS
    temperature = TEMPERATURE
    frequence_penalty = FREQUENCE_PENALTY
    presence_penalty = PRESENCE_PENALTY
    description = description or RAG_DESCRIPTION

    # with gr.Blocks(title="RAG") as rag_demo:
    additional_inputs = [
        gr.File(label='Upload Document', file_count='single', file_types=['pdf', 'docx', 'txt', 'json']),
        # gr.Textbox(value=None, label='Document path', lines=1, interactive=False),
        gr.Number(value=temperature, label='Temperature (higher -> more random)'), 
        gr.Number(value=max_tokens, label='Max generated tokens (increase if want more generation)'), 
        # gr.Number(value=frequence_penalty, label='Frequency penalty (> 0 encourage new tokens over repeated tokens)'), 
        # gr.Number(value=presence_penalty, label='Presence penalty (> 0 encourage new tokens, < 0 encourage existing tokens)'), 
        gr.Textbox(value=sys_prompt, label='System prompt', lines=1, interactive=False),
        gr.Number(value=0, label='current_time', visible=False), 
    ]
    
    demo_rag_chat = gr.ChatInterface(
        chat_response_stream_rag_multiturn,
        chatbot=gr.Chatbot(
            label=MODEL_NAME + "-RAG",
            bubble_full_width=False,
            latex_delimiters=[
                { "left": "$", "right": "$", "display": False},
                { "left": "$$", "right": "$$", "display": True},
            ],
            show_copy_button=True,
        ),
        textbox=gr.Textbox(placeholder='Type message', lines=1, max_lines=128, min_width=200),
        submit_btn=gr.Button(value='Submit', variant="primary", scale=0),
        # ! consider preventing the stop button
        # stop_btn=None,
        title=title,
        description=description,
        additional_inputs=additional_inputs, 
        additional_inputs_accordion=gr.Accordion("Additional Inputs", open=True),
        # examples=CHAT_EXAMPLES,
        cache_examples=False
    )
    # with demo_rag_chat:
    #     upload_button = gr.UploadButton("Click to Upload document", file_types=['pdf', 'docx', 'txt', 'json'], file_count="single")
    #     upload_button.upload(upload_file, upload_button, additional_inputs[0])

    # return demo_chat
    return demo_rag_chat



def launch_demo():
    global demo, llm, DEBUG, LOG_FILE
    model_desc = MODEL_DESC
    model_path = MODEL_PATH
    model_title = MODEL_TITLE
    hf_model_name = HF_MODEL_NAME
    tensor_parallel = TENSOR_PARALLEL
    assert tensor_parallel > 0 , f'{tensor_parallel} invalid'
    dtype = DTYPE
    sys_prompt = SYSTEM_PROMPT_1
    max_tokens = MAX_TOKENS
    temperature = TEMPERATURE
    frequence_penalty = FREQUENCE_PENALTY
    presence_penalty = PRESENCE_PENALTY
    ckpt_info = "None"

    print(
        f'Launch config: '
        f'\n| model_title=`{model_title}` '
        f'\n| max_tokens={max_tokens} '
        f'\n| dtype={dtype} '
        f'\n| tensor_parallel={tensor_parallel} '
        f'\n| IS_DELETE_FOLDER={IS_DELETE_FOLDER} '
        f'\n| STREAM_YIELD_MULTIPLE={STREAM_YIELD_MULTIPLE} '
        f'\n| STREAM_CHECK_MULTIPLE={STREAM_CHECK_MULTIPLE} '
        f'\n| DISPLAY_MODEL_PATH={DISPLAY_MODEL_PATH} '
        f'\n| LANG_BLOCK_HISTORY={LANG_BLOCK_HISTORY} '
        f'\n| frequence_penalty={frequence_penalty} '
        f'\n| presence_penalty={presence_penalty} '
        f'\n| temperature={temperature} '
        # f'\n| hf_model_name={hf_model_name} '
        f'\n| model_path={model_path} '
        f'\n| DOWNLOAD_SNAPSHOT={DOWNLOAD_SNAPSHOT} '
        f'\n| gpu_memory_utilization={gpu_memory_utilization} '
        f'\n| LOG_PATH={LOG_PATH} | SAVE_LOGS={SAVE_LOGS} '
        f'\n| Desc={model_desc}'
    )

    if DEBUG:
        model_desc += "\n<br>!!!!! This is in debug mode, responses will copy original"
        # response_fn = debug_chat_response_echo
        response_fn = chat_response_stream_multiturn
        print(f'Creating in DEBUG MODE')
        if SAVE_LOGS:
            LOG_FILE = open(LOG_PATH, 'a', encoding='utf-8')
    else:
        # ! load the model
        maybe_delete_folder()

        if DOWNLOAD_SNAPSHOT:
            print(f'Downloading from HF_MODEL_NAME={hf_model_name} -> {model_path}')
            if HF_TOKEN is not None:
                print(f'Load with HF_TOKEN: {HF_TOKEN}')
                snapshot_download(hf_model_name, local_dir=model_path, use_auth_token=True, token=HF_TOKEN)
            else:
                snapshot_download(hf_model_name, local_dir=model_path)

        import vllm
        from vllm import LLM

        print(F'VLLM: {vllm.__version__}')
        ckpt_info = check_model_path(model_path)

        print(f'Load path: {model_path} | {ckpt_info}')

        if QUANTIZATION == 'awq':
            print(F'Load model in int4 quantization')
            llm = LLM(model=model_path, dtype="float16", tensor_parallel_size=tensor_parallel, gpu_memory_utilization=gpu_memory_utilization, quantization="awq", max_model_len=8192)
        else:
            llm = LLM(model=model_path, dtype=dtype, tensor_parallel_size=tensor_parallel, gpu_memory_utilization=gpu_memory_utilization, max_model_len=8192)

        try:
            print(llm.llm_engine.workers[0].model)
        except Exception as e:
            print(f'Cannot print model worker: {e}')

        try:
            llm.llm_engine.scheduler_config.max_model_len = 8192
            llm.llm_engine.scheduler_config.max_num_batched_tokens = 8192
            # llm.llm_engine.tokenizer.add_special_tokens = False
        except Exception as e:
            print(f'Cannot set parameters: {e}')

        print(f'Use system prompt:\n{sys_prompt}')

        response_fn = chat_response_stream_multiturn
        print(F'respond: {response_fn}')

        if SAVE_LOGS:
            LOG_FILE = open(LOG_PATH, 'a', encoding='utf-8')

    if ENABLE_BATCH_INFER:

        # demo_file_upload = create_file_upload_demo()

        demo_free_form = create_free_form_generation_demo()
        
        demo_chat = create_chat_demo()
        demo_chat_rag = create_chat_demo_rag(description=RAG_DESCRIPTION)
        descriptions = model_desc
        if DISPLAY_MODEL_PATH:
            descriptions += f"<br> {path_markdown.format(model_path=model_path)}"

        demo = CustomTabbedInterface(
            interface_list=[
                demo_chat, 
                demo_chat_rag,
                demo_free_form,
                # demo_file_upload, 
            ],
            tab_names=[
                "Chat Interface", 
                "RAG Chat Interface",
                "Text completion",
                # "Batch Inference", 
            ],
            title=f"{model_title}",
            description=descriptions,
        )
    else:
        descriptions = model_desc
        if DISPLAY_MODEL_PATH:
            descriptions += f"<br> {path_markdown.format(model_path=model_path)}"

        demo = create_chat_demo(title=f"{model_title}", description=descriptions)
    demo.title = MODEL_NAME
    
    with demo:
        if DATA_SET_REPO_PATH != "":
            try:
                from performance_plot import attach_plot_to_demo
                attach_plot_to_demo(demo)
            except Exception as e:
                print(f'Fail to load DEMO plot: {str(e)}')
        
        gr.Markdown(cite_markdown)
        if DISPLAY_MODEL_PATH:
            gr.Markdown(path_markdown.format(model_path=model_path))
        
        if ENABLE_AGREE_POPUP:
            demo.load(None, None, None, _js=AGREE_POP_SCRIPTS)

        # login_btn = gr.LoginButton()

    demo.queue(api_open=False)
    return demo


if __name__ == "__main__":
    demo = launch_demo()
    demo.launch(show_api=False, allowed_paths=["seal_logo.png"])