File size: 79,160 Bytes
2806365 c9884ae 2806365 c9884ae 2806365 d5c526e 2806365 8fc8d61 ad8f587 8fc8d61 e356d16 8fc8d61 d96edf7 8fc8d61 e356d16 40525e7 3526dce 40525e7 3526dce 9ed8dbd c06fbaa d5c526e c06fbaa d5c526e 3526dce fdfe1f6 3526dce 5213a74 a64184d 2806365 0dcda79 2806365 7c6713e 2806365 7c6713e 2806365 7c6713e 2806365 7c6713e 2806365 afb41e1 a36ab97 afb41e1 a36ab97 afb41e1 71856c9 1320030 45e10d7 2806365 c631cb8 2806365 d5c526e 2806365 17d5cb0 c631cb8 2806365 e8800a6 17d5cb0 2806365 05e227d 2806365 05e227d 2806365 c19b9bf de5cb28 2806365 de5cb28 da090d0 de5cb28 f36d24a 2806365 9071b5a 17d5cb0 2806365 f36d24a 2806365 a36ab97 2806365 |
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 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 |
import argparse
import os
import spaces
import random
import torchvision.transforms as transforms
from monai.transforms import Compose, RandRotate, RandFlip, ToTensor,EnsureType,RandSpatialCrop,Resize,Orientation, CenterSpatialCrop,ScaleIntensityRange
from torchvision.transforms.functional import InterpolationMode
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from minigpt4.conversation.conversation import Chat, CONV_VISION_Vicuna0, CONV_VISION_LLama2, StoppingCriteriaSub
import pydicom
# imports modules for registration
from minigpt4.datasets.builders import *
from minigpt4.models import *
from minigpt4.processors import *
from minigpt4.runners import *
from minigpt4.tasks import *
import zipfile
import tarfile
import gzip
import nibabel as nib
user_avatar='./icon/robot.png'
# custom_css = """
# .custom-column {
# max-width: 300px; /* 限制列的最大宽度 */
# padding: 5px; /* 列内边距,控制整体间距 */
# box-sizing: border-box; /* 确保 padding 包含在宽度内 */
# }
# .center-title {
# text-align: center !important;
# flex-grow: 1; /* 占据剩余空间 */
# display: flex;
# justify-content: center; /* 居中对齐 */
# align-items: center; /* 垂直居中 */
# height: 60px;
# }
# .gradio-container {
# background-color: #F5F6FA; /* 浅灰色背景 */
# }
# .logo-img {
# max-width: 60px; /* 调整 Logo 宽度 */
# height: auto;
# vertical-align: middle; /* 垂直居中对齐标题 */
# margin-left: 10px; /* 与标题的间距 */
# float: left
# }
# .button.svelte-izfbkb.center.boundedheight.flex button {
# max-height: 98px !important;
# max-width: 60px; !important;
# }
# upload-button button {
# background-color: #2E3192; /* 深蓝色按钮 */
# color: white;
# font-size: 4px;
# height: 20px;
# border-radius: 8px;
# padding: 12px 24px;
# font-weight: bold;
# }
# restart_button button {
# background-color: #D3D3D3; /* 浅灰色次按钮 */
# color: black;
# border-radius: 8px;
# padding: 10px 20px;
# }
# restart_button button:hover {
# background-color: #B0B0B0; /* 悬停加深 */
# }
# .gradio-input input, .gradio-input label {
# color: #333333; /* 输入框文字颜色 */
# border-color: #E0E0E0; /* 输入框边框 */
# }
# .accordion-style {
# background-color: white;
# border: 1px solid #E0E0E0;
# border-radius: 8px;
# padding: 15px;
# margin-top: 20px;
# box-shadow: 0 2px 4px rgba(0,0,0,0.1);
# }
# .message-row img {
# margin: 0px !important;
# }
# .message.bot.message-bubble-border {
# background-color: #f0f8ff; /* 浅蓝背景 */
# border-radius: 10px; /* 圆角 */
# padding: 15px; /* 内边距 */
# margin: 10px 0; /* 外边距 */
# }
# .avatar-container img {
# padding: 0px !important;
# }
# .avatar-image {
# width: 15px;
# height: 15px;
# border-radius: 50%;
# object-fit: cover;
# position: relative;
# top: 0px;
# left: 0px;
# margin: 2px;
# }
# """
custom_css="""
/* ========================================
全局配色方案 - 医学主题
======================================== */
/* 主容器和整体背景 */
body, .gradio-container {
background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%) !important;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
color: #2c3e50 !important;
}
/* 强制 bot 消息占满一行,消除侧边空隙 */
.bot.svelte-1nr59td.message {
width: 100% !important;
max-width: 100% !important;
display: flex !important;
justify-content: flex-start !important; /* 确保整体靠左 */
}
/* 调整内部文字包装层,取消宽度限制 */
.bot.svelte-1nr59td.message .message-wrap {
# width: 100% !important;
width: fit-content !important;
max-width: 85% !important;
flex-grow: 1 !important;
}
/* 如果文字在一个气泡/容器里,去掉它的 margin */
.bot.svelte-1nr59td.message .md {
max-width: 100% !important;
}
/* 1. 取消全宽限制,允许容器根据内容收缩 */
.bot.svelte-1nr59td.message .panel-full-width {
width: fit-content !important;
min-width: unset !important;
max-width: 85% !important; /* 限制最大宽度,防止长文本溢出 */
}
/* 2. 针对消息内容容器,确保其宽度也是自适应的 */
.bot.svelte-1nr59td.message [data-testid="bot"] {
width: fit-content !important;
display: inline-block !important; /* 或者 flex */
}
/* 3. 确保文字排版不会因为收缩而显得拥挤 */
.bot.svelte-1nr59td.message .message-content {
padding-right: 15px !important; /* 给右侧留一点呼吸空间 */
}
/* 关键:调整消息内容的包装器,让其填满左侧 */
.bot.svelte-1nr59td.message > .message-wrap {
margin-left: 0 !important;
padding-left: 0 !important;
}
# .bot.svelte-1nr59td.message,
# .md.svelte-1hf8a14.chatbot.prose {
# width: 100% !important;
# height: 100% !important;
# display: flex !important;
# align-items: stretch !important;
# justify-content: stretch !important;
# box-sizing: border-box !important;
# padding: 15px !important;
# background-color: #f0f8ff !important; /* 或已定义的背景色 */
# border-radius: 10px !important;
# min-height: 60px !important;
# }
# .md.svelte-1hf8a14.chatbot.prose {
# flex: 1 1 auto !important;
# width: 100% !important;
# height: 100% !important;
# display: flex !important;
# align-items: center !important;
# word-break: break-word !important;
# box-sizing: border-box !important;
# }
/* 2. 移除右侧多余滚动条并美化 */
/* 尝试隐藏外层导致双滚动条的溢出 */
div.gradio-container {
overflow: visible !important;
}
/* 针对 Gradio Chatbot 的主容器 */
.svelte-1nr59td.chatbot {
border: none !important; /* 移除边框有时能解决视觉上的滚动条错觉 */
}
/* 隐藏特定的滚动条,只保留主对话区域的滚动功能 */
.svelte-1nr59td.chatbot .wrapper::-webkit-scrollbar {
width: 6px; /* 设置一个很细的滚动条,或者设为 0 完全隐藏 */
}
/* 标题样式 */
h1, h2, h3, h4, h5, h6 {
color: #2E3192 !important;
font-weight: 600 !important;
}
/* 自定义列样式 */
.custom-column {
max-width: 200px !important;
width: 200px !important;
padding: 15px !important;
box-sizing: border-box !important;
background: rgba(255, 255, 255, 0.9) !important;
border-radius: 12px !important;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08) !important;
margin: 10px !important;
border: 1px solid #e0e0e0 !important;
flex-shrink: 0 !important;
}
/* 针对所有可能的列选择器 */
div[data-testid="column"]:first-child,
.gradio-row .gradio-column:first-child,
.gr-row .gr-column:first-child {
max-width: 200px !important;
width: 200px !important;
flex: 0 0 200px !important;
}
div#component-7.block.custom-avatar.svelte-12cmxck {
height: 510px !important;
}
/* ========================================
聊天消息样式 - 医学主题
======================================== */
/* 优化脑肿瘤诊断网站配色方案
- 主色调采用医学相关的蓝绿色,传递专业、安心、清晰的视觉体验
- 突出操作按钮,采用协调的高饱和色,焦点内容保持简洁柔和
- 明确消息区分,加强医生/机器人和用户的消息对比度
*/
/* 全局背景与字体主色 */
body, .main-background {
background: linear-gradient(135deg, #f2fcfc 0%, #eaf3fb 100%) !important;
# color: #22324a !important;
}
/* 主要按钮颜色(医学蓝绿色,操作性高) */
.btn-primary,
.submit-button button,
button#component-20.lg.secondary.svelte-cmf5ev {
background: linear-gradient(90deg, #42a5f5 0%, #26c6da 100%) !important;
color: #fff !important;
border: none !important;
border-radius: 8px !important;
font-weight: bold !important;
box-shadow: 0 4px 18px rgba(38, 198, 218, 0.14) !important;
}
button:hover, .btn-primary:hover, .submit-button button:hover {
background: linear-gradient(90deg, #1e88e5 0%, #00bcd4 100%) !important;
box-shadow: 0 6px 24px rgba(33, 150, 243, 0.22) !important;
}
/* 次要按钮、文件上传/重启等采用辅助绿色或暖色 */
button.upload-button, .btn-secondary, button#component-20.lg.primary.upload-button.svelte-cmf5ev {
background: linear-gradient(90deg, #43e97b 0%, #38f9d7 100%) !important;
color: #fff !important;
}
button.upload-button:hover, .btn-secondary:hover,
button#component-20.lg.primary.upload-button.svelte-cmf5ev:hover {
background: linear-gradient(90deg, #0bab64 0%, #3bb78f 100%) !important;
}
/* 诊断相关内容强调色:高亮医学橙/红色,仅用于提示/错误 */
.diagnosis-highlights, .warning, .error {
color: #f74c4c !important;
background: #ffecec !important;
border-left: 4px solid #f74c4c !important;
border-radius: 6px !important;
padding: 8px 14px !important;
}
/* 聊天区优化——医生/机器人消息(宁静青绿) */
/*
修复:等待 model 回复时,先出现橙色背景再变为绿色——
通过增加 div.message.bot 的权重,确保无论任何加载/刷新顺序下都优先使用绿色背景
建议配合 JS/模板侧确认 message.bot 标记的及时性
*/
div.message.bot, div.message.bot.pending, div.message.bot.incomplete {
background: linear-gradient(135deg, #b9ecfb 0%, #b7e7c7 100%) !important;
# /* color: #198b6c !important; */
border-left: 5px solid #26c6da !important;
font-size: 19px !important;
padding: 14px 20px !important;
border-radius: 18px 18px 18px 8px !important;
margin: 10px 0 !important;
box-shadow: 0 3px 12px rgba(38, 198, 218, 0.18) !important;
width: fit-content !important;
word-break: break-word !important;
display: inline-block !important;
line-height: 1.6 !important;
color: #22324a !important;
}
/* 用户消息(健康橙-暖色调,易辨识且亲切) */
div.message:not(.bot) {
background: linear-gradient(135deg, #b9ecfb 0%, #b7e7c7 100%) !important;
# color: #ff9800 !important;
# border-right: 5px solid #ff9800 !important;
font-size: 19px !important;
padding: 14px 20px !important;
border-radius: 18px 18px 8px 18px !important;
margin-left: auto !important;
margin: 10px 0 !important;
# box-shadow: 0 3px 12px rgba(255, 152, 0, 0.15) !important;
width: fit-content !important;
min-width: 60px !important;
max-width: 85% !important;
word-break: break-word !important;
display: inline-block !important;
line-height: 1.6 !important;
}
/* 重要:防止权重冲突,避免 bot 消息被 !:not(.bot) 规则选中 */
div.message.bot {
color: #22324a !important;
}
/* 输入框及主要交互区域高亮 */
input, textarea, .gradio-input, .gr-input {
background: #f7fcfd !important;
color: #22324a !important;
border: 1.5px solid #26c6da !important;
border-radius: 8px !important;
box-shadow: 0 2px 7px rgba(38, 198, 218, 0.07) !important;
padding: 10px 14px !important;
font-size: 16px !important;
}
input:focus, textarea:focus, .gradio-input:focus, .gr-input:focus {
outline: 2px solid #42a5f5 !important;
border-color: #42a5f5 !important;
}
.header, .navbar, .logo {
background: linear-gradient(90deg, #26c6da, #42a5f5) !important;
color: #fff !important;
border-bottom: 3px solid #fff !important;
}
/* 消息边框样式 */
.message-bubble-border {
border: none !important; /* 移除默认边框 */
background: transparent !important; /* 仅保留文字颜色, 无背景颜色 */
}
/* Chat box 背景样式 */
div#component-13.block.svelte-90oupt.padded {
# background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%) !important;
border-radius: 12px !important;
padding: 20px !important;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
}
/* 针对 svelte 类名的备用方案 */
.svelte-1pjfiar {
background-color: inherit !important;
}
button.svelte-izfbkb.center.boundedheight.flex {
max-height: 110px !important;
# max-width: 60px !important;
content: "请拖拽文件到此区域或点击上传您想要的文件!"; /* 自定义文字 */
}
.gradio-file::before {
content: "请拖拽文件到此区域或点击上传您想要的文件!";
display: block;
color: #2E7D32;
font-size: 14px;
font-weight: 500;
margin: 10px 0;
}
/* 针对输入框的特定类名 */
.scroll-hide.svelte-1f354aw {
width: 100% !important;
height: 40px !important;
resize: none !important;
max-height: 40px !important;
min-height: 40px !important;
overflow: hidden !important;
}
.scroll-hide.svelte-1f354aw textarea {
height: 40px !important;
max-height: 40px !important;
min-height: 40px !important;
resize: none !important;
overflow: hidden !important;
}
/* Textbox 和按钮的包装容器 */
.textbox-with-button {
position: relative !important;
}
/* 提交按钮样式 - 绝对定位在输入框内 */
.submit-button {
position: absolute !important;
top: 50% !important;
right: 8px !important;
transform: translateY(-50%) !important;
z-index: 10 !important;
width: auto !important;
height: auto !important;
}
/* 针对特定 ID 和类名的按钮 */
#component-18.lg.primary.submit-button.svelte-cmf5ev {
position: absolute !important;
top: 50% !important;
right: 8px !important;
transform: translateY(-50%) !important;
z-index: 10 !important;
width: auto !important;
height: auto !important;
}
.submit-button button {
background-color: #2E3192 !important;
color: white !important;
border-radius: 6px !important;
height: 32px !important;
padding: 6px 12px !important;
font-weight: bold !important;
border: none !important;
transition: background-color 0.3s ease !important;
font-size: 14px !important;
min-width: 60px !important;
}
/* 针对特定按钮的样式 */
button#component-10.lg.primary.submit-button.svelte-cmf5ev {
background-color: white !important;
color: #2E3192 !important;
border-radius: 6px !important;
height: 32px !important;
padding: 6px 12px !important;
font-weight: bold !important;
border: none !important;
transition: background-color 0.3s ease !important;
font-size: 14px !important;
min-width: 60px !important;
line-height: 1 !important;
}
.submit-button button:hover {
background-color: #1A1F71 !important;
}
#component-18.lg.primary.submit-button.svelte-cmf5ev button:hover {
background-color: #1A1F71 !important;
}
.submit-button button:disabled {
background-color: #D3D3D3 !important;
color: #666666 !important;
cursor: not-allowed !important;
}
#component-18.lg.primary.submit-button.svelte-cmf5ev button:disabled {
background-color: #D3D3D3 !important;
color: #666666 !important;
cursor: not-allowed !important;
}
/* Upload & Start Chat 按钮样式 (component-6) */
button#component-20.lg.primary.upload-button.svelte-cmf5ev {
background: linear-gradient(135deg, #B0B0B0 0%, #7D7D7D 100%) !important;
color: white !important;
border: none !important;
border-radius: 12px !important;
padding: 12px 24px !important;
font-size: 14px !important;
font-weight: bold !important;
height: 45px !important;
min-width: 100px !important;
box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3) !important;
transition: all 0.3s ease !important;
cursor: pointer !important;
text-transform: uppercase !important;
letter-spacing: 0.5px !important;
}
button#component-20.lg.primary.upload-button.svelte-cmf5ev:hover {
background: linear-gradient(135deg, #7D7D7D 0%, #B0B0B0 100%) !important;
transform: translateY(-2px) !important;
box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4) !important;
}
button#component-20.lg.primary.upload-button.svelte-cmf5ev:active {
transform: translateY(0) !important;
box-shadow: 0 2px 10px rgba(76, 175, 80, 0.3) !important;
}
button#component-20.lg.primary.upload-button.svelte-cmf5ev:disabled {
background: #E0E0E0 !important;
color: #9E9E9E !important;
cursor: not-allowed !important;
transform: none !important;
box-shadow: none !important;
}
/* Restart 按钮样式 (component-7) */
button#component-21.lg.secondary.svelte-cmf5ev {
background: linear-gradient(135deg, #FF7043 0%, #FF5722 100%) !important;
color: white !important;
border: none !important;
border-radius: 12px !important;
padding: 10px 20px !important;
font-size: 14px !important;
font-weight: bold !important;
height: 45px !important;
min-width: 100px !important;
box-shadow: 0 4px 15px rgba(255, 112, 67, 0.3) !important;
transition: all 0.3s ease !important;
cursor: pointer !important;
text-transform: uppercase !important;
letter-spacing: 0.5px !important;
}
#component-21 button:hover {
background: linear-gradient(135deg, #FF5722 0%, #FF7043 100%) !important;
transform: translateY(-2px) !important;
box-shadow: 0 6px 20px rgba(255, 112, 67, 0.4) !important;
}
#component-21 button:active {
transform: translateY(0) !important;
box-shadow: 0 2px 10px rgba(255, 112, 67, 0.3) !important;
}
/* Textbox 样式调整 - 为按钮留出空间 */
.textbox-with-button .scroll-hide.svelte-1f354aw {
padding-right: 80px !important; /* 为按钮留出空间 */
}
.textbox-with-button .scroll-hide.svelte-1f354aw textarea {
padding-right: 80px !important; /* 为按钮留出空间 */
}
.avatar-image.svelte-1pijsyv {
width: 80px !important;
height: 80px !important;
border-radius: 50% !important; /* 保持为圆形 */
border: 4px solid #cde3f9 !important; /* 可自定义边框颜色与粗细 */
box-sizing: border-box !important;
transition: width 0.2s, height 0.2s, border-width 0.2s; /* 平滑变化(可选) */
}
/* 允许父元素动态调整图片和边框大小,增加适应性,如果图片尺寸变化则边框同步变化 */
.avatar-container.svelte-1e1jlin .avatar-image.svelte-1pijsyv {
width: 100% !important;
height: 100% !important;
max-width: 120px !important; /* 限制最大尺寸,可根据需求调整 */
max-height: 120px !important;
}
/* 可选: 父容器控制整体 avatar 尺寸,图片和边框会自适应填充 */
.avatar-container.svelte-1e1jlin {
width: 45px !important;
height: 45px !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
}
/* 取消头像的圆形边框,使图片为常规矩形且无边框 */
.avatar-image.svelte-1pijsyv {
width: 90% !important;
height: 90% !important;
border-radius: 0 !important;
border: none !important;
box-sizing: border-box !important;
transition: width 0.2s, height 0.2s, border-width 0.2s;
}
.avatar-container.svelte-1e1jlin div.avatar-image.svelte-1pijsyv {
width: 55px !important;
height: 55px !important;
}
/* 聊天框背景样式 */
div.bubble-wrap.svelte-1pjfiar {
background: linear-gradient(135deg, #e6f3ff 0%, #f0f8ff 100%) !important;
border-radius: 12px !important;
padding: 20px !important;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
margin: 10px 0 !important;
height: 520px !important;
# overflow-y: auto !important;
}
div.wrapper.svelte-nab2ao {
background: linear-gradient(135deg, #e6f3ff 0%, #f0f8ff 100%) !important;
# border: 2px solid #e3f2fd !important;
height: 510px !important;
}
div#component-6.block.custom-avatar.svelte-90oupt {
height: 500px !important;
}
block#component-7.block.custom-avatar.svelte-12cmxck {
height: 510px !important;
}
div.flex-wrap.bot.svelte-1e1jlin {
border: none !important;
/* 或者若需完全透明边框也可以如下: */
/* border: 1px solid transparent !important; */
box-shadow: none !important;
}
# /* 针对文件上传组件的固定高度与滚动条设置,及使文件上传中始终保持自定义边框样式 */
# #custom-file-upload,
# #custom-file-upload:focus,
# #custom-file-upload:active,
# #custom-file-upload[aria-busy="true"],
# div.custom-file-upload.block.svelte-90oupt,
# div.custom-file-upload.block.svelte-90oupt:focus,
# div.custom-file-upload.block.svelte-90oupt:active,
# div.custom-file-upload.block.svelte-90oupt[aria-busy="true"] {
# max-height: 120px !important; /* 限制最大高度 */
# overflow-y: auto !important; /* 内容超出时显示垂直滚动条 */
# border-style: dashed !important; /* 始终保持虚线边框 */
# border-width: 2px !important;
# border-color: #90caf9 !important;
# box-shadow: none !important;
# }
/* ============================ */
/* 聊天消息主气泡美化-消除双背景分层 */
/* ============================ */
/* 强制_message整体_单一渐变背景&无白色内层 */
div.message.bot, div.message.user,
div.message.bot.pending, div.message.bot.incomplete,
div.message.user.pending, div.message.user.incomplete {
/* 直接应用柔和青绿色医学渐变 */
background: linear-gradient(135deg, #b9ecfb 0%, #b7e7c7 100%) !important;
/* 移除 padding 产生的白色卡层 */
padding: 18px 22px !important;
border-radius: 15px !important;
margin: 12px 0 !important;
/* 阴影更柔和,避免高对比分割 */
box-shadow: 0 2px 12px rgba(41, 141, 150, 0.08) !important;
border: none !important;
}
/* 彻底去掉任何“内层”白色/默认背景:泡泡内容区、Markdown区 */
div.message.bot > div,
div.message.user > div,
div.message.bot .markdown,
div.message.user .markdown,
div.message.bot .bubble-content,
div.message.user .bubble-content
{
background: transparent !important;
box-shadow: none !important;
border: none !important;
}
/* 用户消息气泡同一模式,但偏浅蓝些区分身份 */
div.message.user, div.message.user.pending, div.message.user.incomplete {
background: linear-gradient(135deg, #e3f0fa 0%, #c8e2f7 100%) !important;
}
/* 去除可能附着在底下的多余盒子背景 */
div.svelte-1e1jlin, div.bubble-wrap, div.bubble-content, div.markdown-body {
background: transparent !important;
border: none !important;
box-shadow: none !important;
}
/* 可选:调整文字清晰度、字号与高亮内容 */
div.message.bot, div.message.user {
color: #243e3e !important;
font-size: 1.08em !important;
line-height: 1.55 !important;
font-family: 'Segoe UI', 'Arial', 'PingFang SC', 'Microsoft Yahei', sans-serif !important;
}
div.message.bot strong, div.message.user strong {
color: #1769aa !important;
font-weight: 600 !important;
}
/* ✅ 精简视觉分界,让渐变自然延展到边缘 */
div.message.bot, div.message.user {
border: none !important;
/* 去除双边框 */
outline: none !important;
}
/* 可选:让头像和泡泡贴得更紧凑,不留“白带” */
.avatar-container, .avatar-image {
background: transparent !important;
border: none !important;
box-shadow: none !important;
margin: 0 !important;
padding: 0 !important;
}
# /* 聊天框滚动条样式 */
# div.bubble-wrap.svelte-1pjfiar::-webkit-scrollbar {
# width: 6px !important;
# }
# div.bubble-wrap.svelte-1pjfiar::-webkit-scrollbar-track {
# background: #f1f8ff !important;
# border-radius: 3px !important;
# }
# div.bubble-wrap.svelte-1pjfiar::-webkit-scrollbar-thumb {
# background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%) !important;
# border-radius: 3px !important;
# }
# div.bubble-wrap.svelte-1pjfiar::-webkit-scrollbar-thumb:hover {
# background: linear-gradient(135deg, #45a049 0%, #4CAF50 100%) !important;
# }
.fixed-height-textbox textarea {
resize: none !important;
height: 40px !important;
min-height: 40px !important;
max-height: 40px !important;
}
/*
=== 等待消息(pending/思考中)气泡样式:确保气泡出现在bot头像右侧 ===
重点:当 role="status"(即 bot pending 消息)时,应靠右对齐,并紧贴 bot 头像
兼容用户待发送气泡靠左、bot pending 靠右的“对话气泡”体验
*/
/* 基础样式:pending 状态的消息气泡 */
div.message.pending.svelte-1gpwetz {
display: flex !important;
align-items: center !important;
min-height: 48px !important;
box-shadow: none !important;
border-radius: 14px !important;
margin: 10px 0 !important;
padding: 10px 20px !important;
position: relative;
/* 默认左对齐,但后面有更高优先级的覆盖 */
justify-content: flex-start !important;
background: #f0f7ff !important;
}
/* user(右侧/人类)等待消息:靠右 */
div.message.user.pending.svelte-1gpwetz,
div.message[role="user"].pending.svelte-1gpwetz {
justify-content: flex-end !important;
margin-left: auto !important;
margin-right: 0 !important;
background: #e3f2fd !important;
}
/* bot(左侧/机器人)等待消息:紧贴bot头像+显示bot头像 */
/*
假设 pending message 时 DOM 结构应包含和正常 bot 消息一致的头像区域(avatar-container/avatar-image),
则只需调整 margin & flex 排布,确保pending气泡紧贴头像而不靠最左边。增加头像在pending状态下可见的条件样式。
*/
/*
如何显示avatar的bot头像?
1. 确保 Gradio/前端 DOM 结构中, pending 状态的 bot 消息 (role="status"或role="assistant") DOM 内也包含
<div class="avatar-container"><img class="avatar-image" ...></div> 结构,和正常 bot 消息一致。
2. 样式上,只需保证 pending 泡泡与头像并排显示,不要用 display: none 隐藏头像容器。
3. 可通过如下样式让 pending bot 消息的 bubble 紧贴头像并确保头像显示。
*/
div.message.bot.pending.svelte-1gpwetz,
div.message[role="status"].pending.svelte-1gpwetz,
div.message[role="assistant"].pending.svelte-1gpwetz {
display: flex !important;
align-items: center !important;
/* 让flex内第一个元素是avatar-container,第二个是bubble,则bubble就会紧贴avatar展示 */
/* 如 Gradio DOM 正常包含头像,此样式即可显示bot pending时的头像 */
justify-content: flex-start !important;
margin-left: 20 !important; /* 头像默认有宽度+外边距,无需再留额外边距 */
margin-right: auto !important;
background: #f0f8ff !important;
max-width: 88% !important;
}
/* 移动端适配 */
@media (max-width: 600px) {
div.message.pending.svelte-1gpwetz {
padding: 8px 8px !important;
min-height: 42px !important;
}
}
/* 再确保优先级覆盖,实锤靠右 */
div.message.bot.pending.svelte-1gpwetz,
div.message[role="status"].pending.svelte-1gpwetz,
div.message[role="assistant"].pending.svelte-1gpwetz {
justify-content: flex-end !important;
}
/* 兼容极端情况下 pending 消息内容溢出,保持 bubble 不挤压头像 */
div.message.bot.pending.svelte-1gpwetz,
div.message[role="status"].pending.svelte-1gpwetz,
div.message[role="assistant"].pending.svelte-1gpwetz {
max-width: 88%; /* 留一点空间避免紧贴屏幕右侧,如需更靠近头像可微调 */
}
/* 缩减上传按钮高度(适当减少高度和内侧间距)*/
button.svelte-1x5qevo.center.boundedheight.flex[aria-label="file upload"],
button.svelte-1x5qevo.center.boundedheight.flex,
button.svelte-1x5qevo.center.boundedheight.flex > .wrap.svelte-12ioyct {
min-height: 100px !important;
height: 100px !important; /* 原可能较高,改为较低高度 */
padding-top: 4px !important;
padding-bottom: 4px !important;
box-sizing: border-box !important;
}
button.svelte-1x5qevo.center.boundedheight.flex {
height: 44px !important; /* 按钮整体高度缩减 */
max-height: 48px !important;
}
button.svelte-1x5qevo.center.boundedheight.flex svg {
max-height: 26px !important;
max-width: 26px !important;
}
button.svelte-1x5qevo.center.boundedheight.flex span,
button.svelte-1x5qevo.center.boundedheight.flex .wrap.svelte-12ioyct {
line-height: 1.2 !important;
font-size: 1rem !important;
}
/* 缩小上传按钮内的input高度和间距 */
button.svelte-1x5qevo.center.boundedheight.flex input[type="file"] {
min-height: 40px !important;
height: 40px !important;
padding: 0 !important;
margin: 0 !important;
}
/* 如果 needed: 缩减“将文件拖放到此处 - 或 - 点击上传”的内容垂直边距 */
button.svelte-1x5qevo.center.boundedheight.flex .wrap.svelte-12ioyct {
padding-top: 0 !important;
padding-bottom: 0 !important;
}
/* 兼容边框圆角调整 */
button.svelte-1x5qevo.center.boundedheight.flex {
border-radius: 9px !important;
}
.upload-fixed-height .svelte-1x5qevo.center.boundedheight.flex,
.upload-fixed-height button.svelte-1x5qevo.center.boundedheight.flex {
min-height: 130px !important;
max-height: 130px !important;
height: 130px !important;
box-sizing: border-box !important;
}
.upload-fixed-height {
min-height: 110px !important;
max-height: 110px !important;
height: 110px !important;
overflow-y: auto !important;
box-sizing: border-box !important;
/* 若想四个齿轮按钮/Drag区域完全等高则必须加这个保证外框也一致 */
}
.progress-text.svelte-au1olv.meta-text {
font-size: 1.35rem !important;
font-weight: 600 !important;
}
/* --- 解决气泡不贴合文字 --- */
/* 核心:取消强制全宽类名 */
.panel-full-width.svelte-1nr59td {
width: fit-content !important;
max-width: 90% !important;
min-width: unset !important;
}
/* 确保内部消息内容也是自适应宽度 */
.bot.svelte-1nr59td.message [data-testid="bot"],
.user.svelte-1nr59td.message [data-testid="user"] {
width: fit-content !important;
display: inline-block !important;
}
/* 消息行容器:确保消息靠边对齐而不是撑开 */
.message-row.svelte-1nr59td {
width: 100% !important;
display: flex !important;
}
/* --- 解决多余滚动条 --- */
/* 1. 针对你自定义的 block 容器,隐藏它的滚动条,只保留内部滚动 */
.block.custom-avatar {
overflow: hidden !important;
}
# /* 2. 针对 Gradio 的内部包装器,确保它是唯一的滚动源 */
# .svelte-1wizwbi, .bubble-wrap.svelte-kpz1 {
# overflow-y: auto !important;
# height: 100% !important;
# }
div.svelte-1wizwbi {
# overflow-y: auto !important;
height: 100% !important;
max-height: 600px !important;
}
/* 3. 彻底隐藏浏览器默认滚动条的视觉效果(可选,保持界面清爽) */
.block.custom-avatar::-webkit-scrollbar {
display: none;
}
/* 1. 核心消息容器:取消全宽,改为根据内容收缩 */
.bot.svelte-1nr59td.message {
width: fit-content !important;
max-width: 85% !important; /* 限制最大宽度,防止长文本顶到头 */
display: block !important; /* 确保它不会默认占满整行 */
}
/* 2. 内部包装层:确保它们也是自适应宽度 */
.bot.svelte-1nr59td.message .message-wrap,
.bot.svelte-1nr59td.message .panel-full-width,
.bot.svelte-1nr59td.message [data-testid="bot"] {
width: fit-content !important;
min-width: unset !important;
max-width: 100% !important;
}
/* 3. 消除 Markdown 内容区域的默认最小宽度 */
.bot.svelte-1nr59td.message .prose {
width: fit-content !important;
min-width: unset !important;
}
/* 4. 调整气泡内边距(Padding),让文字和边缘更紧凑 */
div.message.bot {
padding: 8px 14px !important; /* 原来是 14px 20px,缩小后更紧凑 */
line-height: 1.4 !important; /* 稍微收缩行高 */
}
/* 1. 用户消息核心容器:改为自适应宽度并靠右 */
.user.svelte-1nr59td.message {
width: fit-content !important;
max-width: 85% !important;
margin-left: auto !important; /* 关键:推向右侧 */
margin-right: 0 !important;
display: block !important;
}
/* 2. 内部层级处理:消除强制全宽 */
.user.svelte-1nr59td.message .message-wrap,
.user.svelte-1nr59td.message .panel-full-width,
.user.svelte-1nr59td.message [data-testid="user"] {
width: fit-content !important;
min-width: unset !important;
max-width: 100% !important;
margin-left: auto !important; /* 确保内部块也靠右 */
}
/* 3. 针对 Markdown 和气泡外观的微调 */
div.message.user {
padding: 8px 14px !important; /* 紧凑内边距 */
line-height: 1.4 !important;
border-radius: 18px 18px 8px 18px !important; /* 保持用户气泡特有的圆角 */
text-align: left !important; /* 气泡内部文字依然左对齐,方便阅读 */
}
/* 4. 消除可能导致撑开的 prose (Markdown) 最小宽度 */
.user.svelte-1nr59td.message .prose {
width: fit-content !important;
min-width: unset !important;
}
"""
# <div class="message pending svelte-1gpwetz" role="status" aria-label="Loading response" aria-live="polite" style="border-radius: var(--radius-xxl);"><span class="sr-only">Loading content</span> <div class="dot-flashing svelte-1gpwetz"></div>
#
# <div class="dot-flashing svelte-1gpwetz"></div>
#
# <div class="dot-flashing svelte-1gpwetz"></div></div>
# h1 {
# color: #2E3192; /* 标题颜色 */
# }
# p {
# color: #666666; /* 副标题颜色 */
# }
#
# .custom-avatar .avatar {
# width: 40px;
# height: 40px;
# }
#
custom_theme = gr.themes.Default(
primary_hue="blue", # 主色调为蓝色
secondary_hue="gray", # 次色调为灰色
neutral_hue="gray", # 中性色调
text_size="lg", # 文字大小适中
radius_size="md", # 圆角适中
font=["Arial", "sans-serif"], # 使用清晰字体
spacing_size="md" # 间距适中
)
def parse_args():
parser = argparse.ArgumentParser(description="Demo")
parser.add_argument("--cfg-path", default='./eval_configs/minigpt4_eval.yaml', help="path to configuration file.")
parser.add_argument("--gpu-id", type=int, default=0, help="specify the gpu to load the model.")
parser.add_argument(
"--options",
nargs="+",
help="override some settings in the used config, the key-value pair "
"in xxx=yyy format will be merged into config file (deprecate), "
"change to --cfg-options instead.",
)
args = parser.parse_args()
return args
def setup_seeds(config):
seed = config.run_cfg.seed + get_rank()
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
cudnn.benchmark = False
cudnn.deterministic = True
# ========================================
# Model Initialization
# ========================================
conv_dict = {'pretrain_vicuna0': CONV_VISION_Vicuna0,
'pretrain_llama2': CONV_VISION_LLama2}
print('Initializing Chat')
args = parse_args()
cfg = Config(args)
model_config = cfg.model_cfg
model_config.device_8bit = args.gpu_id
model_cls = registry.get_model_class(model_config.arch)
# breakpoint()
# breakpoint()
model = model_cls.from_config(model_config).to('cuda')
import copy
# cfg_model_2 = cfg.model_cfg
# cfg_model_2['ckpt'] = '/home/ynwang/brain_llm/MiniGPT-4/eval_configs/minigpt4_eval_report.yaml'
model_config.ckpt = './checkpoint_1.pth'
model_2 = model_cls.from_config(model_config).to('cuda')
# model_2 = copy.deepcopy(model.to('cpu')).to('cuda:{}'.format(args.gpu_id+1))
# model.to('cuda:{}'.format(args.gpu_id))
# model_2 = model
CONV_VISION = conv_dict[model_config.model_type]
# vis_processor_cfg = cfg.datasets_cfg.radiopediaclass.vis_processor.train
vis_processor = transforms.Compose(
[
transforms.ToTensor(),
transforms.RandomResizedCrop(
224,
scale=(0.5, 1.0),
interpolation=InterpolationMode.BICUBIC,
),
# self.normalize,
]
)
stop_words_ids = [[835], [2277, 29937]]
stop_words_ids = [torch.tensor(ids) for ids in stop_words_ids]
stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)])
# breakpoint()
# model_2.load_state_dict(torch.load('/home/ynwang/brain_llm/MiniGPT-4/minigpt4/ckpt/20250611193/checkpoint_1.pth'),strict=False)
chat = Chat([model,model_2], vis_processor, device='cpu', stopping_criteria=stopping_criteria)
print('Initialization Finished')
# ========================================
# Gradio Setting
# ========================================
def handle_upload(files, chat_state, img_list):
# files 是 gr.File 返回的文件对象列表
img_list = [file.name for file in files] # 获取每个文件的路径
# 提取文件名(不包含路径)
file_names = [os.path.basename(file_path) for file_path in img_list]
chat_state = f"Uploaded {len(file_names)} files: {', '.join(file_names)}"
return chat_state, img_list, [["System", f"Uploaded files: {', '.join(file_names)}"]]
# def gradio_reset(chat_state, img_list):
# # breakpoint()
# if chat_state is not None:
# chat_state.messages = []
# if img_list is not None:
# img_list = []
# return gr.update(value=[]), gr.update(value=None, interactive=True), gr.update(placeholder='Please upload your image first', interactive=False),gr.update(value="Upload & Start Chat", interactive=True), gr.update(interactive=False), chat_state, img_list
# chatbot, image, text_input, upload_button, submit_button, chat_state, img_list
def encode_img(img_list, modalities):
instruction, LR_image_list, HR_image_list, modalities = chat.encode_img(img_list, modalities)
return instruction, LR_image_list, HR_image_list, modalities
def upload_img(chatbot,t1c_ax_file, t1_file, t2_file, fla_file, text_input, chat_state, model_type):
# 允许5个文件输入为None,自动跳过为None的对象
# modalities=['t1c ax','t1 ax','t2 ax','t2f ax','t1c sag']
# 将五个文件list合并成一个新的list
modalities = []
files = []
for file_list in [t1c_ax_file, t1_file, t2_file, fla_file]:
if file_list is not None:
# breakpoint()
# 检查 file_list[0] 是否为压缩文件
new_file_list = []
for file in file_list:
is_compressed = file.endswith('.zip') or file.endswith('.tar') or file.endswith('.tar.gz') or file.endswith('.tgz')
if is_compressed:
modalities.append(file.name.split('/')[-1].split('.')[0])
if file.endswith('.zip'):
extract_dir = file.name.replace('.zip', '_extracted')
with zipfile.ZipFile(file.name, 'r') as zip_ref:
zip_ref.extractall(extract_dir)
new_file_list = [
os.path.join(extract_dir, sub_file)
for sub_file in zip_ref.namelist()
if not sub_file.endswith('/')
and not sub_file.startswith('__MACOSX/')
and not sub_file.endswith('.DS_Store')
and os.path.isfile(os.path.join(extract_dir, sub_file))
and 'dcm' in sub_file.lower() # 排除目录条目
]
# new_file_list.extend(new_file_list)
elif file.endswith('.tar'):
extract_dir = file.name.replace('.tar', '_extracted')
with tarfile.open(file.name, 'r') as tar_ref:
tar_ref.extractall(extract_dir)
# 不能在with语句结束后再使用tar_ref对象;
# tar_ref.getnames()需要在with内部调用并保存,否则with结束后文件被关闭
tar_names = tar_ref.getnames()
new_file_list = [
os.path.join(extract_dir, sub_file)
for sub_file in tar_names
if not sub_file.endswith('/')
and not sub_file.startswith('__MACOSX/')
and not sub_file.endswith('.DS_Store')
and os.path.isfile(os.path.join(extract_dir, sub_file))
and 'dcm' in sub_file.lower() # 排除目录条目
]
# breakpoint()
# file_list = new_file_list
elif file.endswith('.tar.gz'):
extract_dir = file.name.replace('.tar.gz', '_extracted')
with tarfile.open(file.name, 'r') as tar_ref:
tar_ref.extractall(extract_dir)
new_file_list = [
os.path.join(extract_dir, sub_file)
for sub_file in tar_ref.namelist()
if not sub_file.endswith('/')
and not sub_file.startswith('__MACOSX/')
and not sub_file.endswith('.DS_Store')
and os.path.isfile(os.path.join(extract_dir, sub_file))
and 'dcm' in sub_file.lower() # 排除目录条目
]
# new_file_list.extend(new_file_list)
elif file.endswith('.tgz'):
extract_dir = file.name.replace('.tgz', '_extracted')
with tarfile.open(file.name, 'r') as tar_ref:
tar_ref.extractall(extract_dir)
new_file_list = [
os.path.join(extract_dir, sub_file)
for sub_file in tar_ref.namelist()
if not sub_file.endswith('/')
and not sub_file.startswith('__MACOSX/')
and not sub_file.endswith('.DS_Store')
and os.path.isfile(os.path.join(extract_dir, sub_file))
and 'dcm' in sub_file.lower() # 排除目录条目
]
dcm_files = []
dcm_orders=[]
for dcm_file_path in new_file_list:
# print(dcm_file_path)
dcm_data = pydicom.dcmread(dcm_file_path,force=True)
if np.max(dcm_data.pixel_array) > 0:
img = dcm_data.pixel_array
img = ((img - np.min(img)) / (np.max(img) - np.min(img) + 1e-8) * 255).astype(np.uint8)
dcm_files.append(img)
dcm_orders.append(int(dcm_data.InstanceNumber))
if len(dcm_files) > 0:
sorted_indices = np.argsort(dcm_orders)
dcm_files = [dcm_files[i] for i in sorted_indices]
# dcm_orders = [dcm_orders[i] for i in sorted_indices]
dcm_files = np.stack(dcm_files, axis=0)
print('dcm_files.shape',dcm_files.shape)
# np.save('dcm_files.npy',dcm_files)
files.append(dcm_files)
elif file.endswith('.nii.gz'):
modalities.append(file.name.split('/')[-1].split('.')[0])
files.append(nib.load(file).get_fdata().astype(np.uint8))
elif file.endswith('npy'):
modalities.append(file.name.split('/')[-1].split('.')[0])
files.append(np.load(file))
# os.path.join(extract_dir, file)
# for file in zip_ref.namelist()
# if not file.endswith('/')
# and not file.startswith('__MACOSX/')
# and not file.endswith('.DS_Store')
# and os.path.isfile(os.path.join(extract_dir, file))
# and 'dcm' in file.lower() # 排除目录条目及非影像相关
# ]
# file_list = new_file_list
# # breakpoint()
# elif filename.endswith('.tar'):
# extract_dir = file_list[0].name.replace('.tar', '_extracted')
# with tarfile.open(file_list[0].name, 'r') as tar_ref:
# tar_ref.extractall(extract_dir)
# new_file_list = [
# os.path.join(extract_dir, file)
# for file in tar_ref.namelist()
# if not file.endswith('/')
# and not file.startswith('__MACOSX/')
# and not file.endswith('.DS_Store')
# and os.path.isfile(os.path.join(extract_dir, file))
# and 'dcm' in file.lower() # 排除目录条目
# ]
# file_list = new_file_list #
# elif filename.endswith('.tar.gz'):
# extract_dir = file_list[0].name.replace('.tar.gz', '_extracted')
# with tarfile.open(file_list[0].name, 'r') as tar_ref:
# tar_ref.extractall(extract_dir)
# new_file_list = [
# os.path.join(extract_dir, file)
# for file in tar_ref.namelist()
# if not file.endswith('/')
# and not file.startswith('__MACOSX/')
# and not file.endswith('.DS_Store')
# and os.path.isfile(os.path.join(extract_dir, file))
# and 'dcm' in file.lower() # 排除目录条目
# ]
# file_list = new_file_list #
# # breakpoint()
# if '.dcm' in file_list[0].lower():
# dcm_files = []
# dcm_orders=[]
# for dcm_file in file_list:
# dcm_data = pydicom.dcmread(dcm_file)
# if np.max(dcm_data.pixel_array) > 0:
# dcm_files.append(dcm_data.pixel_array)
# dcm_orders.append(int(dcm_data.InstanceNumber))
# # breakpoint()
# # 将 list 中的 np.array 沿第0维拼接成一个ndarray
# # 根据dcm_orders的顺序对dcm_files和dcm_orders同时排序(升序)
# if len(dcm_files) > 0:
# sorted_indices = np.argsort(dcm_orders)
# print(sorted_indices)
# print(dcm_orders)
# dcm_files = [dcm_files[i] for i in sorted_indices]
# dcm_orders = [dcm_orders[i] for i in sorted_indices]
# dcm_files = np.stack(dcm_files, axis=0)
# print(dcm_files.shape)
# files.append(dcm_files)
# modalities.append(modality)
# else:
# files.extend(file_list)
# for file in file_list:
# modalities.append(modality)
# img_name_list = [os.path.basename(f.name) for f in valid_files]
# print([os.path.abspath(f.name) for f in valid_files])
if not files:
return None, None, gr.update(interactive=True), gr.update(interactive=False), chat_state, None
# chat_state = CONV_VISION.copy()
# 只传递非None的文件对象和文件名
img_list = []
llm_message = chat.upload_img(files, chat_state, img_list)
instruction, LR_image_list, HR_image_list, modalities = encode_img(img_list, modalities)
# instruction, LR_image_list, HR_image_list, modalities = chat.encode_img(img_list, modalities)
return chatbot, chat_state, instruction, LR_image_list, HR_image_list, modalities, gr.update(interactive=False),gr.update(interactive=False)
# t1c_ax_file, t1_file, t2_file, fla_file, t1c_file, text_input, chat_state, model_type
def gradio_ask(user_message, age,gender,chatbot, chat_state,model_type):
# breakpoint()
if model_type == 'Diagnosis':
if age != '' and gender != '':
user_message = f'Please make a diagnosis for this {age} years old {gender} patient based on the MRI files, providing MRI report.'
else:
user_message = f'Please make a diagnosis for this patient based on the MRI files, providing MRI report.'
elif model_type == 'Diagnosis and Confidence':
if age != '' and gender != '':
user_message = f'Please make a diagnosis for this {age} years old {gender} patient based on the MRI files, providing MRI report and your confidence level.'
else:
user_message = f'Please make a diagnosis for this patient based on the MRI files, providing MRI report and your confidence level.'
# breakpoint()
chat_state = CONV_VISION.copy()
# chat.ask(user_message, chat_state)
if len(user_message) == 0:
return gr.update(interactive=True, placeholder='Input should not be empty!'), chatbot, chat_state
chat.ask(user_message, chat_state)
chatbot = chatbot + [{'role': 'user', 'content': user_message}]
return '', chatbot, chat_state,gr.update(interactive=False)
def button_wait():
return gr.update(interactive=False),gr.update(interactive=False),gr.update(interactive=False)
@spaces.GPU(duration=180)
def gradio_answer(chatbot, chat_state,instruction, lr_img_list, hr_img_list, modalities,model_type,age='',gender=''):
print('instruction',instruction)
try:
llm_message = chat.answer(conv=chat_state,
instruction=instruction,
lr_img_list=lr_img_list.to('cuda'),
hr_img_list=hr_img_list.to('cuda'),
model_type=model_type,
modalities=modalities,
age=age,
gender=gender,
max_new_tokens=300,
max_length=2000)
chatbot =chatbot + [{'role': 'assistant', 'content': llm_message}]
except Exception as e:
print(f'Error in gradio_answer: {e}')
chatbot =chatbot + [{'role': 'assistant', 'content': 'The data files type is not supported, please check the file shape, we only accept data files with shape (slice, W, H) or (slice, W, H, 3)'}]
return chatbot, chat_state, lr_img_list, hr_img_list,gr.update(interactive=True),gr.update(interactive=True),gr.update(interactive=True)
title = """<h1 align="center">BrainVLM</h1>"""
description = """<h3>This is the demo of BrainVLM. Upload patient MRI files and start chatting</h3>"""
article = """
<p style="display: inline-block; margin-right: 2px; vertical-align: top;">
<a href='https://github.com/Vision-CAIR/MiniGPT-4'><img src='https://img.shields.io/badge/Github-Code-blue' style="height: 20px; object-fit: contain;"></a>
</p>
"""
# initial_messages = [
# # (f"This is BrainVLM, a large vision-language model for brain image understanding. Please upload patient MRI files to start the chat!😊",f"Question template: Please make a diagnosis for this patient based on the MRI files, providing MRI report and your confidence level.")
# [None,f"This is BrainVLM, a large vision-language model for brain tumor image understanding. Please upload patient MRI files to start the chat!😊\n Using Pipeline: 1. Please upload patient MRI files via the upload module! 🏥 2. Input age and gender information of the patient(optional). 💬\n 3. Click the diagnosis button to get the diagnosis result! ✨ "],
# # (f"This is user, try to upload patient MRI files to start the chat!😊",f"Using Pipeline: 1. Please upload patient MRI files via the upload module! 🏥 2. Click the Start Chat button to start the chat! 💬\n 3. Input your question and click the Send button to get the answer! ✨ \n Question template: Please make a diagnosis for this patient based on the MRI files, providing MRI report.")
# ]
# [user_message, None]
initial_messages = [
gr.ChatMessage(role="assistant", content=(
"This is BrainVLM, a large vision-language model for brain tumor image understanding. "
"Please upload patient MRI files to start the chat!\n"
"Using Pipeline: 1. Rename your file with modality and view name, e.g. 'T1c_ax', 'T1_cor', 'T2_sag', 'T2f_ax', 'T1c_sag', etc. \n"
"2. Please upload patient MRI files via the upload module! \n"
"3. Input age and gender information of the patient (optional).\n"
"4. Click the diagnosis button to get the diagnosis result!\n"
"5. Click the restart button to process new files!\n"
"Attention: BrainVLM was trained based on 5 MRI sequences (T1c, T1, T2, FLAIR and another view of T1c).\n Full modality diagnosis (based on 5 sequences) is recommended. "
"We accept missing modality diagnosis, however, the diagnosis result may not be very accurate!\n"
"Support File type: .nii.gz, .npy and zip file with dcm slice files."
))
]
with gr.Blocks(theme=custom_theme,css=custom_css) as demo:
# gr.Markdown(title)
with gr.Row():
with gr.Column():
gr.Markdown(
"""
<div style="width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; position: relative;">
<div style="width: 100%; display: flex; align-items: center; justify-content: center; position: relative;">
<h1 style="
margin: 0 auto;
font-size: 2.3em;
line-height:1;
display: inline-block;
text-align: center;
width: auto;
flex-shrink: 0;
">BrainVLM</h1>
</div>
</div>
""",
elem_classes=["center-title"]
)
# print(os.getcwd())
# breakpoint()
# logo_path = os.path.join(os.getcwd(), "./icon/brain.png")
# gr.Markdown(f', "./icon/HKU.jpg")})', elem_classes=["logo-img"]) # Logo 图片
# html_content = f'<img src="/file={logo_path}" alt="预定义图片" style="max-width: 35px;margin-left: 10px;">'
# gr.HTML(html_content)
# gr.Markdown(description)
# gr.Markdown(article)
# with gr.Row():/
# with gr.Column(scale=0.3, elem_classes=["custom-column"]):
# image = gr.File(label="Upload .nii.gz file",file_count="multiple", file_types=[".nii.gz"])
# upload_button = gr.Button(value="Start Chat", interactive=True, variant="primary",elem_classes=["upload-button"])
# clear = gr.Button("Restart")
# model_type = gr.Dropdown(
# choices=["Diagnosis", "Diagnosis and Confidence"],
# value="Diagnosis",
# label="Task Type",
# interactive=True
# )
# ############################ 原始版本
# with gr.Row():
# # First row - Chat section (80% height)
# # with gr.Column(scale=1):
# chat_state = gr.State()
# img_list = gr.State()
# with gr.Accordion("Chat box", open=True):
# chatbot = gr.Chatbot(initial_messages,label='BrainVLM',type='messages',avatar_images=["./icon/user.png","./icon/robot.png"],elem_classes="custom-avatar",avatar_position="top", height=600) # Increased height
# with gr.Row():
# with gr.Column(scale=1):
# text_input = gr.Textbox(label='User', placeholder='Please upload patient nii.gz files first', interactive=False, container=False, lines=1, max_lines=1, elem_classes=["textbox-with-button"])
# submit_button = gr.Button("Send", variant="primary", interactive=False, elem_classes=["submit-button"])
# instruction,LR_image_list,HR_image_list=gr.State(),gr.State(),gr.State()
# with gr.Row():
# First row - Chat section (80% height)
# with gr.Column(scale=1):
chat_state = gr.State()
img_list = gr.State()
with gr.Row():
chatbot = gr.Chatbot(initial_messages,label='BrainVLM',avatar_images=[".\\icon\\user.png",".\\icon\\robot.png"],elem_classes="custom-avatar",height=500) # Increased height
# with gr.Row():
# with gr.Column(scale=1):
# text_input = gr.Textbox(label='User', placeholder='Please upload patient nii.gz files first', interactive=False, container=False, lines=1, max_lines=1, elem_classes=["textbox-with-button"])
# submit_button = gr.Button("Send", variant="primary", interactive=False, elem_classes=["submit-button"])
instruction,LR_image_list,HR_image_list,modalities=gr.State(),gr.State(),gr.State(),gr.State()
# Second row - File upload section (20% height)
with gr.Row():
# with gr.Column(scale=1):
# 增加自定义 CSS 类 upload-fixed-height,固定上传组件高度并滚动条
with gr.Row(elem_classes=["upload-column"]):
with gr.Column():
# 方法二:通过自定义 Gradio 组件以支持“文件夹上传”(即 <input type="file" webkitdirectory>)。
# 实现方式为嵌入自定义 HTML + JS + Gradio 的 gr.HTML() 和 gr.File() 配合。
# 下面实现一个自定义上传按钮,可以让用户直接选取文件夹,所有内部文件自动上传:
# 注意:当前 Gradio 没有直接内置支持 webkitdirectory 参数,需用 JS 处理。
# 这个输入组件仍用于支持常规多文件上传
t1c_ax_file = gr.File(
label="T1c MRI files",
file_count="multiple",
file_types=[".nii", ".gz", ".nii.gz",'.npy','.zip','.tar'],
# file_types=[".nii", ".gz", ".nii.gz", ".dcm", ".npy"],
interactive=True,
elem_id="custom-file-upload-t1c",
elem_classes=["upload-fixed-height"],
)
# 需要配合 gradio 回调,在 folder_upload_callback.click 时读取 window.folderUploadFiles → decode_files_from_js 并更新流程
# 你可以在 gradio 接口绑定如下回调 (需放在 app/Gradio Blocks 构建后):
# folder_upload_callback.click(fn=decode_files_from_js, inputs=None, outputs=YOUR_IMG_LIST_GRVAR)
t1_file=gr.File(
label="T1 MRI files",
file_count="multiple",
file_types=[".nii", ".gz", ".nii.gz",'.npy','.zip','.tar'],
interactive=True,
elem_id="custom-file-upload-t1",
elem_classes=["upload-fixed-height"]
)
with gr.Row():
with gr.Column():
t2_file=gr.File(
label="T2 MRI files",
file_count="multiple",
# file_types=[".nii", ".gz", ".nii.gz",'.npy','.dcm'],
file_types=[".nii", ".gz", ".nii.gz",'.npy','.zip','.tar'],
interactive=True,
elem_id="custom-file-upload-t2",
elem_classes=["upload-fixed-height"]
)
fla_file=gr.File(
label="FLAIR MRI files",
file_count="multiple",
# file_types=[".nii", ".gz", ".nii.gz",'.npy','.dcm'],
file_types=[".nii", ".gz", ".nii.gz",'.npy','.zip','.tar'],
interactive=True,
elem_id="custom-file-upload-flair",
elem_classes=["upload-fixed-height"]
)
# with gr.Row():
# with gr.Column():
# t1c_cor_file=gr.File(
# label="T1c cor files",
# file_count="multiple",
# file_types=[".nii", ".gz", ".nii.gz",'.npy','.dcm'],
# interactive=True,
# elem_id="custom-file-upload-t1c-cor",
# elem_classes=["upload-fixed-height"]
# )
# t1c_sag_file=gr.File(
# label="T1c sag MRI files",
# file_count="multiple",
# file_types=[".nii", ".gz", ".nii.gz",'.npy','.dcm'],
# interactive=True,
# elem_id="custom-file-upload-t1c-sag",
# elem_classes=["upload-fixed-height"]
# )
# 让 upload_button 以及下方所有与聊天相关的控件初始为 disabled/不可交互。
# 通过 image.change 事件,用户选择了文件后,自动激活 start chat 按钮以及相关控件
with gr.Column():
Confidence_Diagnosis = gr.Button("Full modality Diagnosis",interactive=False,variant="primary",elem_classes=["upload-button"])
Diagnosis = gr.Button(
value="Missing Modality Diagnosis",
interactive=False,
variant="primary",
elem_classes=["diagnosis-button"]
)
Restart = gr.Button(
"Restart",
interactive=False,
variant="secondary",
elem_classes=["restart-button"]
)
# with gr.Row():
with gr.Column():
# with gr.Column(scale=1):
age_input = gr.Textbox(
label="Age",
placeholder="Enter patient age (optional)",
interactive=True,
lines=1,
max_lines=1,
elem_classes=["fixed-height-textbox"]
)
gender_input = gr.Textbox(
label="Gender",
placeholder="Enter patient gender (optional)",
interactive=True,
lines=1,
max_lines=1,
elem_classes=["fixed-height-textbox"]
)
# To ensure the 'fixed-height-textbox' class disables resizing and fixes height,
# add the following CSS to your css config area:
#
# 注意:gr.Dropdown 组件可以直接在回调函数中使用,不需要转换为 State
# 在回调函数的 inputs 列表中添加 model_type 即可获取用户选择的值
# breakpoint()
# with gr.Column(scale=2.7):
# chat_state = gr.State()
# img_list = gr.State()
# with gr.Accordion("Chat box", open=True):
# chatbot = gr.Chatbot(initial_messages,label='BrainVLM',type='messages',avatar_images=["./icon/brain.png","./icon/robot.png"],elem_classes="custom-avatar",avatar_position="top")
# with gr.Row():
# with gr.Column(scale=1):
# text_input = gr.Textbox(label='User', placeholder='Please upload patient nii.gz files first', interactive=False, container=False, lines=1, max_lines=1, elem_classes=["textbox-with-button"])
# submit_button = gr.Button("Send", variant="primary", interactive=False, elem_classes=["submit-button"])
# instruction,LR_image_list,HR_image_list=gr.State(),gr.State(),gr.State()
# print('model_type.value',model_type.value)
# breakpoint()
# if image is not None:
# upload_button.interactive = True
# 检测用户完成 image 上传:使用 Gradio 的 `.change` 事件,在文件有变动时使 upload_button、text_input、submit_button 变为可交互
def on_image_change(files):
# files: list of gr.File objects or None
if files is not None and len(files) > 0:
# 已选文件,允许按钮交互,提示可以输入
return (
gr.update(interactive=True), # Diagnosis
gr.update(interactive=True) # Confidence_Diagnosis
# gr.update(interactive=False,placeholder="Click Start Chat button"), # text_input
# gr.update(interactive=False) # submit_button
)
else:
# 未选文件,禁用按钮和输入框
return (
gr.update(interactive=False),
gr.update(interactive=False)
# gr.update(interactive=False, placeholder="Please upload patient nii.gz files first"),
# gr.update(interactive=False)
)
# 当检测到 image 上传新文件后,先激活 Diagnosis/Confidence_Diagnosis 两按钮,再自动触发 Diagnosis.click (即 upload_img)
def on_image_and_upload(files, age_val, gender_val, chat_state_val, model_type_val):
# 激活按钮
diagnosis_update, confidence_update = on_image_change(files)
# 如果有文件,则自动调用 upload_img,相当于点击 Diagnosis 按钮
if files is not None and len(files) > 0:
# 自动触发 upload_img 的逻辑
# breakpoint()
chat_state, instruction,LR_image_list,HR_image_list,modalities=upload_img(files, age_val, chat_state_val, model_type_val)
# 返回按钮状态更新 + upload_img 所有返回值(注意顺序对齐 outputs)
# Diagnosis,Confidence_Diagnosis 为按钮状态,upload_img返回的顺序需与对应outputs对齐
return (
diagnosis_update, # Diagnosis按钮状态
confidence_update, # Confidence_Diagnosis按钮状态
chat_state,
instruction,
LR_image_list,
HR_image_list,
modalities # 展开 upload_img 返回值
)
else:
# 如果未上传文件,只返回按钮状态,其余输出为None
n_upload_outputs = 8 # Diagnosis, Confidence_Diagnosis, image, age_input, gender_input, Diagnosis, Confidence_Diagnosis, chat_state, instruction, LR_image_list, HR_image_list
return (diagnosis_update, confidence_update) + (None,) * 8 # 8个None作为其他output
model_type=gr.State("Diagnosis")
# 需要定义outputs序列,前2个为按钮,后面是upload_img返回的输出及所需参数
# t1c_ax_file.change(
# on_image_and_upload,
# inputs=[t1c_ax_file, age_input, chat_state, model_type],
# outputs=[
# Diagnosis, Confidence_Diagnosis,
# # upload_img 所有返回(需对齐调用 upload_img 的 signature和互动)
# chat_state, instruction, LR_image_list, HR_image_list, modalities
# ],
# queue=False
# )
# 实时检测五个gr.File组件是否都上传了文件,并据此动态设置Confidence Diagnosis按钮
def all_files_uploaded_modified(t1c_ax_file, t1_file, t2_file, fla_file):
# 判断前四个必填都不为None且都有文件
required_files = [t1c_ax_file, t1_file, t2_file, fla_file]
required_all_uploaded = all(f is not None and (not hasattr(f, "__len__") or len(f) > 0) for f in required_files)
return required_all_uploaded
def update_confidence_interactive(t1c_ax_file, t1_file, t2_file, fla_file):
# 返回的是gr.update(interactive=True/False)
if all_files_uploaded_modified(t1c_ax_file, t1_file, t2_file, fla_file):
return gr.update(interactive=True)
else:
return gr.update(interactive=False)
# 实时绑定change事件到五个文件Gradio组件上,只要有变化就检测状态
t1c_ax_file.change(
fn=update_confidence_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Confidence_Diagnosis,
queue=False,
show_progress=False
)
t1_file.change(
fn=update_confidence_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Confidence_Diagnosis,
queue=False,
show_progress=False
)
t2_file.change(
fn=update_confidence_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Confidence_Diagnosis,
queue=False,
show_progress=False
)
fla_file.change(
fn=update_confidence_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Confidence_Diagnosis,
queue=False,
show_progress=False
)
# t1c_file.change(
# fn=update_confidence_interactive,
# inputs=[t1c_ax_file, t1_file, t2_file, fla_file, t1c_file],
# outputs=Confidence_Diagnosis,
# queue=False,
# show_progress=False
# )
# 只要有任意一个 gr.File 上传文件,Diagnosis 按钮设为 interactive=True,否则为False
def any_file_uploaded(t1c_ax_file, t1_file, t2_file, fla_file):
files = [t1c_ax_file, t1_file, t2_file, fla_file]
for f in files:
# gr.File 有些gradio版本可能返回None或者[],都视为“未上传”
if f is not None:
# 如果f为list(multiple),检查有内容;如果是单File对象/单项,也算
if hasattr(f, "__len__"):
if len(f) > 0:
return True
else:
return True
return False
def update_diagnosis_interactive(t1c_ax_file, t1_file, t2_file, fla_file):
if any_file_uploaded(t1c_ax_file, t1_file, t2_file, fla_file):
return gr.update(interactive=True)
else:
return gr.update(interactive=False)
# 绑定change事件到五个文件组件
t1c_ax_file.change(
fn=update_diagnosis_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Diagnosis,
queue=False,
show_progress=False
)
t1_file.change(
fn=update_diagnosis_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Diagnosis,
queue=False,
show_progress=False
)
t2_file.change(
fn=update_diagnosis_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Diagnosis,
queue=False,
show_progress=False
)
fla_file.change(
fn=update_diagnosis_interactive,
inputs=[t1c_ax_file, t1_file, t2_file, fla_file],
outputs=Diagnosis,
queue=False,
show_progress=False
)
# t1c_file.change(
# fn=update_diagnosis_interactive,
# inputs=[t1c_ax_file, t1_file, t2_file, fla_file, t1c_file],
# outputs=Diagnosis,
# queue=False,
# show_progress=False
# )
text_input=gr.State(' ')
text_input_confidence=gr.State(' ')
# Diagnosis.click(gradio_ask, [text_input, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis')], [text_input, chatbot, chat_state]).then(
# gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis')], [chatbot, chat_state, LR_image_list,HR_image_list]
# )
# Confidence_Diagnosis.click(upload_img, [t1c_ax_file, t1_file, t2_file, fla_file,t1c_cor_file,t1c_sag_file, age_input, chat_state, model_type], [chat_state, instruction, LR_image_list, HR_image_list, modalities,Confidence_Diagnosis,Diagnosis]).then(gradio_ask, [text_input_confidence, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis and Confidence')], [text_input_confidence, chatbot, chat_state,Confidence_Diagnosis]).then(
# gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis and Confidence')], [chatbot, chat_state, LR_image_list,HR_image_list,Confidence_Diagnosis,Diagnosis,Restart]
# )
# Confidence_Diagnosis.click(button_wait,[], [Confidence_Diagnosis,Diagnosis,Restart]).then(upload_img, [t1c_ax_file, t1_file, t2_file, fla_file, age_input, chat_state, model_type], [chat_state, instruction, LR_image_list, HR_image_list, modalities,Confidence_Diagnosis,Diagnosis]).then(gradio_ask, [text_input_confidence, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis and Confidence')], [text_input_confidence, chatbot, chat_state,Confidence_Diagnosis]).then(
# gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis and Confidence')], [chatbot, chat_state, LR_image_list,HR_image_list,Confidence_Diagnosis,Diagnosis,Restart]
# )
Confidence_Diagnosis.click(button_wait,[], [Confidence_Diagnosis,Diagnosis,Restart]).then(gradio_ask, [text_input_confidence, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis and Confidence')], [text_input_confidence, chatbot, chat_state,Confidence_Diagnosis]).then(upload_img, [chatbot,t1c_ax_file, t1_file, t2_file, fla_file, age_input, chat_state, model_type], [chatbot,chat_state, instruction, LR_image_list, HR_image_list, modalities,Confidence_Diagnosis,Diagnosis]).then(
gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis and Confidence'),age_input, gender_input], [chatbot, chat_state, LR_image_list,HR_image_list,Confidence_Diagnosis,Diagnosis,Restart]
)
Diagnosis.click(button_wait,[], [Diagnosis,gr.State('Diagnosis and Confidence'),Restart]).then(gradio_ask, [text_input, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis and Confidence')], [text_input, chatbot, chat_state,Diagnosis]).then(upload_img, [chatbot,t1c_ax_file, t1_file, t2_file, fla_file, age_input, chat_state, model_type], [chatbot,chat_state, instruction, LR_image_list, HR_image_list, modalities,Diagnosis,Confidence_Diagnosis]).then(
gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis and Confidence'),age_input, gender_input], [chatbot, chat_state, LR_image_list,HR_image_list,Diagnosis,gr.State('Diagnosis and Confidence'),Restart]
)
# Diagnosis.click(button_wait,[], [Diagnosis,gr.State('Diagnosis and Confidence'),Restart]).then(upload_img, [t1c_ax_file, t1_file, t2_file, fla_file, age_input, chat_state, model_type], [chat_state, instruction, LR_image_list, HR_image_list, modalities,Diagnosis,Confidence_Diagnosis]).then(gradio_ask, [text_input, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis and Confidence')], [text_input, chatbot, chat_state,Diagnosis]).then(
# gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis')], [chatbot, chat_state, LR_image_list,HR_image_list,Diagnosis,gr.State('Diagnosis and Confidence'),Restart]
# )
# Diagnosis.click(upload_img, [t1c_ax_file, t1_file, t2_file, fla_file,t1c_cor_file,t1c_sag_file, age_input, chat_state, model_type], [chat_state, instruction, LR_image_list, HR_image_list, modalities,Diagnosis,Confidence_Diagnosis]).then(gradio_ask, [text_input, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis')], [text_input, chatbot, chat_state,Diagnosis]).then(
# gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis and Confidence')], [chatbot, chat_state, LR_image_list,HR_image_list,Diagnosis,Confidence_Diagnosis,Restart]
# )
# Confidence_Diagnosis.click(gradio_ask, [text_input_confidence, age_input, gender_input, chatbot, chat_state,gr.State('Diagnosis and Confidence')], [text_input_confidence, chatbot, chat_state,Confidence_Diagnosis]).then(
# gradio_answer, [chatbot, chat_state,instruction, LR_image_list,HR_image_list, modalities, gr.State('Diagnosis and Confidence')], [chatbot, chat_state, LR_image_list,HR_image_list,Confidence_Diagnosis]
# )
def gradio_reset():
# breakpoint()
# 清空 /tmp/gradio/ 目录下的所有文件
import os
import shutil
gradio_tmp_dir = "/tmp/gradio/"
if os.path.exists(gradio_tmp_dir):
for filename in os.listdir(gradio_tmp_dir):
file_path = os.path.join(gradio_tmp_dir, 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(f'Failed to delete {file_path}. Reason: {e}')
return gr.update(value=None, interactive=True), gr.update(value=[]), gr.update(value=[])
def gradio_reset_all():
# 清空 /tmp/gradio/ 目录下的所有文件
import os
import shutil
gradio_tmp_dir = "/tmp/gradio/"
if os.path.exists(gradio_tmp_dir):
for filename in os.listdir(gradio_tmp_dir):
file_path = os.path.join(gradio_tmp_dir, 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(f'Failed to delete {file_path}. Reason: {e}')
return gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(value=[]), gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False)
# t1c_ax_file.clear(gradio_reset,[], [img_list,LR_image_list,HR_image_list])
# 插入清除按钮和重置逻辑
# 定义一个重置函数,重置所有state和控件到初始状态
Restart.click(gradio_reset_all,[], [t1c_ax_file, t1_file, t2_file, fla_file, chat_state, instruction, LR_image_list, HR_image_list, modalities, Diagnosis, Confidence_Diagnosis,Restart])
demo.launch(share=True,allowed_paths=['./icon'])
|