Spaces:
Build error
Build error
File size: 132,814 Bytes
5637560 |
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 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 |
"""Contains all of the components that can be used with Gradio Interface / Blocks.
Along with the docs for each component, you can find the names of example demos that use
each component. These demos are located in the `demo` directory."""
from __future__ import annotations
import inspect
import json
import math
import numbers
import operator
import os
import shutil
import tempfile
import warnings
from copy import deepcopy
from types import ModuleType
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import matplotlib.figure
import numpy as np
import pandas as pd
import PIL
from ffmpy import FFmpeg
from gradio import media_data
from gradio import processing_utils
from gradio.blocks import Block
from gradio.events import Changeable
from gradio.events import Clearable
from gradio.events import Clickable
from gradio.events import Editable
from gradio.events import Playable
from gradio.events import Streamable
from gradio.events import Submittable
from gradio.utils import component_or_layout_class
from markdown_it import MarkdownIt
class Component(Block):
"""
A base class for defining the methods that all gradio components should have.
"""
def __str__(self):
return self.__repr__()
def __repr__(self):
return f"{self.get_block_name()}"
def get_config(self):
"""
:return: a dictionary with context variables for the javascript file associated with the context
"""
return {
"name": self.get_block_name(),
**super().get_config(),
}
class IOComponent(Component):
"""
A base class for defining methods that all input/output components should have.
"""
def __init__(
self,
*,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
requires_permissions: bool = False,
elem_id: Optional[str] = None,
**kwargs,
):
self.label = label
self.show_label = show_label
self.requires_permissions = requires_permissions
self.interactive = interactive
self.set_interpret_parameters()
super().__init__(elem_id=elem_id, visible=visible, **kwargs)
def get_config(self):
return {
"label": self.label,
"show_label": self.show_label,
"interactive": self.interactive,
**super().get_config(),
}
def save_flagged(
self, dir: str, label: Optional[str], data: Any, encryption_key: bool
) -> Any:
"""
Saves flagged data from component
"""
return data
def restore_flagged(self, dir, data, encryption_key):
"""
Restores flagged data from logs
"""
return data
def save_file(self, file: tempfile._TemporaryFileWrapper, dir: str, label: str):
"""
Saved flagged file and returns filepath
"""
label = "".join([char for char in label if char.isalnum() or char in "._- "])
old_file_name = file.name
output_dir = os.path.join(dir, label)
if os.path.exists(output_dir):
file_index = len(os.listdir(output_dir))
else:
os.makedirs(output_dir)
file_index = 0
new_file_name = str(file_index)
if "." in old_file_name:
uploaded_format = old_file_name.split(".")[-1].lower()
new_file_name += "." + uploaded_format
file.close()
shutil.move(old_file_name, os.path.join(dir, label, new_file_name))
return label + "/" + new_file_name
def save_flagged_file(
self,
dir: str,
label: str,
data: Any,
encryption_key: bool,
file_path: Optional[str] = None,
) -> Optional[str]:
"""
Saved flagged data (e.g. image or audio) as a file and returns filepath
"""
if data is None:
return None
file = processing_utils.decode_base64_to_file(data, encryption_key, file_path)
return self.save_file(file, dir, label)
def restore_flagged_file(
self,
dir: str,
file: str,
encryption_key: bool,
as_data: bool = False,
) -> Dict[str, Any]:
"""
Loads flagged data from file and returns it
"""
if as_data:
data = processing_utils.encode_file_to_base64(
os.path.join(dir, file), encryption_key=encryption_key
)
return {"name": file, "data": data}
else:
return {
"name": os.path.join(dir, file),
"data": os.path.join(dir, file),
"file_name": file,
"is_example": True,
}
# Input Functionalities
def preprocess(self, x: Any) -> Any:
"""
Any preprocessing needed to be performed on function input.
"""
return x
def serialize(self, x: Any, called_directly: bool) -> Any:
"""
Convert from a human-readable version of the input (path of an image, URL of a video, etc.) into the interface to a serialized version (e.g. base64) to pass into an API. May do different things if the interface is called() vs. used via GUI.
Parameters:
x (Any): Input to interface
called_directly (bool): if true, the interface was called(), otherwise, it is being used via the GUI
"""
return x
def preprocess_example(self, x: Any) -> Any:
"""
Any preprocessing needed to be performed on an example before being passed to the main function.
"""
return x
def set_interpret_parameters(self):
"""
Set any parameters for interpretation.
"""
return self
def get_interpretation_neighbors(self, x: Any) -> Tuple[List[Any], Dict[Any], bool]:
"""
Generates values similar to input to be used to interpret the significance of the input in the final output.
Parameters:
x (Any): Input to interface
Returns: (neighbor_values, interpret_kwargs, interpret_by_removal)
neighbor_values (List[Any]): Neighboring values to input x to compute for interpretation
interpret_kwargs (Dict[Any]): Keyword arguments to be passed to get_interpretation_scores
interpret_by_removal (bool): If True, returned neighbors are values where the interpreted subsection was removed. If False, returned neighbors are values where the interpreted subsection was modified to a different value.
"""
return [], {}, True
def get_interpretation_scores(
self, x: Any, neighbors: List[Any], scores: List[float], **kwargs
) -> List[Any]:
"""
Arrange the output values from the neighbors into interpretation scores for the interface to render.
Parameters:
x (Any): Input to interface
neighbors (List[Any]): Neighboring values to input x used for interpretation.
scores (List[float]): Output value corresponding to each neighbor in neighbors
kwargs (Dict[str, Any]): Any additional arguments passed from get_interpretation_neighbors.
Returns:
(List[Any]): Arrangement of interpretation scores for interfaces to render.
"""
pass
def generate_sample(self) -> Any:
"""
Returns a sample value of the input that would be accepted by the api. Used for api documentation.
"""
pass
# Output Functionalities
def postprocess(self, y):
"""
Any postprocessing needed to be performed on function output.
"""
return y
def deserialize(self, x):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return x
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
border: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
container: Optional[bool] = None,
):
if rounded is not None:
self._style["rounded"] = rounded
if border is not None:
self._style["border"] = border
if container is not None:
self._style["container"] = container
return self
@classmethod
def document_parameters(cls, target):
if target == "input":
doc = inspect.getdoc(cls.preprocess)
if "Parameters:\nx (" in doc:
return doc.split("Parameters:\nx ")[1].split("\n")[0]
return None
elif target == "output":
doc = inspect.getdoc(cls.postprocess)
if "Returns:\n" in doc:
return doc.split("Returns:\n")[1].split("\n")[0]
return None
else:
raise ValueError("Invalid doumentation target.")
class Textbox(Changeable, Submittable, IOComponent):
"""
Creates a textarea for user to enter string input or display string output.
Preprocessing: passes textarea value as a {str} into the function.
Postprocessing: expects a {str} returned from function and sets textarea value to it.
Demos: hello_world, diff_texts, sentence_builder
"""
def __init__(
self,
value: str = "",
*,
lines: int = 1,
max_lines: int = 20,
placeholder: Optional[str] = None,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): default text to provide in textarea.
lines (int): minimum number of line rows to provide in textarea.
max_lines (int): maximum number of line rows to provide in textarea.
placeholder (str): placeholder hint to provide behind textarea.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.lines = lines
self.max_lines = max_lines
self.placeholder = placeholder
self.value = self.postprocess(value)
self.cleared_value = ""
self.test_input = value
self.interpret_by_tokens = True
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"lines": self.lines,
"max_lines": self.max_lines,
"placeholder": self.placeholder,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
lines: Optional[int] = None,
max_lines: Optional[int] = None,
placeholder: Optional[str] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"lines": lines,
"max_lines": max_lines,
"placeholder": placeholder,
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
# Input Functionalities
def preprocess(self, x: str | None) -> Any:
"""
Any preprocessing needed to be performed on function input.
Parameters:
x (str): text
Returns:
(str): text
"""
if x is None:
return None
else:
return str(x)
def serialize(self, x: Any, called_directly: bool) -> Any:
"""
Convert from a human-readable version of the input (path of an image, URL of a video, etc.) into the interface to a serialized version (e.g. base64) to pass into an API. May do different things if the interface is called() vs. used via GUI.
Parameters:
x (Any): Input to interface
called_directly (bool): if true, the interface was called(), otherwise, it is being used via the GUI
"""
return x
def preprocess_example(self, x: str | None) -> Any:
"""
Any preprocessing needed to be performed on an example before being passed to the main function.
"""
if x is None:
return None
else:
return str(x)
def set_interpret_parameters(
self, separator: str = " ", replacement: Optional[str] = None
):
"""
Calculates interpretation score of characters in input by splitting input into tokens, then using a "leave one out" method to calculate the score of each token by removing each token and measuring the delta of the output value.
Parameters:
separator (str): Separator to use to split input into tokens.
replacement (str): In the "leave one out" step, the text that the token should be replaced with. If None, the token is removed altogether.
"""
self.interpretation_separator = separator
self.interpretation_replacement = replacement
return self
def tokenize(self, x: str) -> Tuple[List[str], List[str], None]:
"""
Tokenizes an input string by dividing into "words" delimited by self.interpretation_separator
"""
tokens = x.split(self.interpretation_separator)
leave_one_out_strings = []
for index in range(len(tokens)):
leave_one_out_set = list(tokens)
if self.interpretation_replacement is None:
leave_one_out_set.pop(index)
else:
leave_one_out_set[index] = self.interpretation_replacement
leave_one_out_strings.append(
self.interpretation_separator.join(leave_one_out_set)
)
return tokens, leave_one_out_strings, None
def get_masked_inputs(
self, tokens: List[str], binary_mask_matrix: List[List[int]]
) -> List[str]:
"""
Constructs partially-masked sentences for SHAP interpretation
"""
masked_inputs = []
for binary_mask_vector in binary_mask_matrix:
masked_input = np.array(tokens)[np.array(binary_mask_vector, dtype=bool)]
masked_inputs.append(self.interpretation_separator.join(masked_input))
return masked_inputs
def get_interpretation_scores(
self, x, neighbors, scores: List[float], tokens: List[str], masks=None, **kwargs
) -> List[Tuple[str, float]]:
"""
Returns:
(List[Tuple[str, float]]): Each tuple set represents a set of characters and their corresponding interpretation score.
"""
result = []
for token, score in zip(tokens, scores):
result.append((token, score))
result.append((self.interpretation_separator, 0))
return result
def generate_sample(self) -> str:
return "Hello World"
# Output Functionalities
def postprocess(self, y: str | None):
"""
Any postprocessing needed to be performed on function output.
Parameters:
y (str | None): text
Returns:
(str | None): text
"""
if y is None:
return None
else:
return str(y)
def deserialize(self, x):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return x
class Number(Changeable, Submittable, IOComponent):
"""
Creates a numeric field for user to enter numbers as input or display numeric output.
Preprocessing: passes field value as a {float} or {int} into the function, depending on `precision`.
Postprocessing: expects an {int} or {float} returned from the function and sets field value to it.
Demos: tax_calculator, titanic_survival, blocks_simple_squares
"""
def __init__(
self,
value: Optional[float] = None,
*,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
precision: Optional[int] = None,
**kwargs,
):
"""
Parameters:
value (float): default value.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
precision (Optional[int]): Precision to round input/output to. If set to 0, will round to nearest integer and covert type to int. If None, no rounding happens.
"""
self.precision = precision
self.value = self.postprocess(value)
self.test_input = self.value if self.value is not None else 1
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
@staticmethod
def round_to_precision(
num: float | int | None, precision: int | None
) -> float | int | None:
"""
Round to a given precision.
If precision is None, no rounding happens. If 0, num is converted to int.
Parameters:
num (float | int): Number to round.
precision (int | None): Precision to round to.
Returns:
(float | int): rounded number
"""
if num is None:
return None
if precision is None:
return float(num)
elif precision == 0:
return int(round(num, precision))
else:
return round(num, precision)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"interactive": interactive,
"__type__": "update",
}
def preprocess(self, x: float | None) -> float | None:
"""
Parameters:
x (float | None): numeric input
Returns:
(float | None): number representing function input
"""
if x is None:
return None
return self.round_to_precision(x, self.precision)
def preprocess_example(self, x: float | None) -> float | None:
"""
Returns:
(float | None): Number representing function input
"""
if x is None:
return None
else:
return self.round_to_precision(x, self.precision)
def set_interpret_parameters(
self, steps: int = 3, delta: float = 1, delta_type: str = "percent"
):
"""
Calculates interpretation scores of numeric values close to the input number.
Parameters:
steps (int): Number of nearby values to measure in each direction (above and below the input number).
delta (float): Size of step in each direction between nearby values.
delta_type (str): "percent" if delta step between nearby values should be a calculated as a percent, or "absolute" if delta should be a constant step change.
"""
self.interpretation_steps = steps
self.interpretation_delta = delta
self.interpretation_delta_type = delta_type
return self
def get_interpretation_neighbors(self, x: float | int) -> Tuple[List[float], Dict]:
x = self.round_to_precision(x, self.precision)
if self.interpretation_delta_type == "percent":
delta = 1.0 * self.interpretation_delta * x / 100
elif self.interpretation_delta_type == "absolute":
delta = self.interpretation_delta
else:
delta = self.interpretation_delta
if self.precision == 0 and math.floor(delta) != delta:
raise ValueError(
f"Delta value {delta} is not an integer and precision=0. Cannot generate valid set of neighbors. "
"If delta_type='percent', pick a value of delta such that x * delta is an integer. "
"If delta_type='absolute', pick a value of delta that is an integer."
)
# run_interpretation will preprocess the neighbors so no need to covert to int here
negatives = (x + np.arange(-self.interpretation_steps, 0) * delta).tolist()
positives = (x + np.arange(1, self.interpretation_steps + 1) * delta).tolist()
return negatives + positives, {}
def get_interpretation_scores(
self, x: Number, neighbors: List[float], scores: List[float], **kwargs
) -> List[Tuple[float, float]]:
"""
Returns:
(List[Tuple[float, float]]): Each tuple set represents a numeric value near the input and its corresponding interpretation score.
"""
interpretation = list(zip(neighbors, scores))
interpretation.insert(int(len(interpretation) / 2), [x, None])
return interpretation
def generate_sample(self) -> float:
return self.round_to_precision(1, self.precision)
# Output Functionalities
def postprocess(self, y: float | None) -> float | None:
"""
Any postprocessing needed to be performed on function output.
Parameters:
y (float | None): numeric output
Returns:
(float | None): number representing function output
"""
if y is None:
return None
else:
return self.round_to_precision(y, self.precision)
def deserialize(self, y):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return y
class Slider(Changeable, IOComponent):
"""
Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`.
Preprocessing: passes slider value as a {float} into the function.
Postprocessing: expects an {int} or {float} returned from function and sets slider value to it as long as it is within range.
Demos: sentence_builder, generate_tone, titanic_survival
"""
def __init__(
self,
minimum: float = 0,
maximum: float = 100,
value: Optional[float] = None,
*,
step: Optional[float] = None,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
minimum (float): minimum value for slider.
maximum (float): maximum value for slider.
value (float): default value.
step (float): increment between slider values.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.minimum = minimum
self.maximum = maximum
if step is None:
difference = maximum - minimum
power = math.floor(math.log10(difference) - 2)
step = 10**power
self.step = step
self.value = self.postprocess(value)
self.cleared_value = self.value
self.test_input = self.value
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"minimum": self.minimum,
"maximum": self.maximum,
"step": self.step,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
minimum: Optional[float] = None,
maximum: Optional[float] = None,
step: Optional[float] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"minimum": minimum,
"maximum": maximum,
"step": step,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: float) -> float:
"""
Parameters:
x (number): numeric input
Returns:
(number): numeric input
"""
return x
def preprocess_example(self, x: float) -> float:
"""
Returns:
(float): Number representing function input
"""
return x
def set_interpret_parameters(self, steps: int = 8) -> "Slider":
"""
Calculates interpretation scores of numeric values ranging between the minimum and maximum values of the slider.
Parameters:
steps (int): Number of neighboring values to measure between the minimum and maximum values of the slider range.
"""
self.interpretation_steps = steps
return self
def get_interpretation_neighbors(self, x) -> Tuple[object, dict]:
return (
np.linspace(self.minimum, self.maximum, self.interpretation_steps).tolist(),
{},
)
def get_interpretation_scores(
self, x, neighbors, scores: List[float], **kwargs
) -> List[float]:
"""
Returns:
(List[float]): Each value represents the score corresponding to an evenly spaced range of inputs between the minimum and maximum slider values.
"""
return scores
def generate_sample(self) -> float:
return self.maximum
# Output Functionalities
def postprocess(self, y: float | None):
"""
Any postprocessing needed to be performed on function output.
Parameters:
y (float | None): numeric output
Returns:
(float): numeric output or minimum number if None
"""
return self.minimum if y is None else y
def deserialize(self, y):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return y
def style(
self,
container: Optional[bool] = None,
):
return IOComponent.style(
self,
container=container,
)
class Checkbox(Changeable, IOComponent):
"""
Creates a checkbox that can be set to `True` or `False`.
Preprocessing: passes the status of the checkbox as a {bool} into the function.
Postprocessing: expects a {bool} returned from the function and, if it is True, checks the checkbox.
Demos: sentence_builder, titanic_survival
"""
def __init__(
self,
value: bool = False,
*,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (bool): if True, checked by default.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.test_input = True
self.value = self.postprocess(value)
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: bool) -> bool:
"""
Parameters:
x (bool): boolean input
Returns:
(bool): boolean input
"""
return x
def preprocess_example(self, x):
"""
Returns:
(bool): Boolean representing function input
"""
return x
def set_interpret_parameters(self):
"""
Calculates interpretation score of the input by comparing the output against the output when the input is the inverse boolean value of x.
"""
return self
def get_interpretation_neighbors(self, x):
return [not x], {}
def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
"""
Returns:
(Tuple[float, float]): The first value represents the interpretation score if the input is False, and the second if the input is True.
"""
if x:
return scores[0], None
else:
return None, scores[0]
def generate_sample(self):
return True
# Output Functionalities
def postprocess(self, y):
"""
Any postprocessing needed to be performed on function output.
Parameters:
y (bool): boolean output
Returns:
(bool): boolean output
"""
return y
def deserialize(self, x):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return x
class CheckboxGroup(Changeable, IOComponent):
"""
Creates a set of checkboxes of which a subset can be checked.
Preprocessing: passes the list of checked checkboxes as a {List[str]} or their indices as a {List[int]} into the function, depending on `type`.
Postprocessing: expects a {List[str]}, each element of which becomes a checked checkbox.
Demos: sentence_builder, titanic_survival
"""
def __init__(
self,
choices: List[str] = None,
*,
value: List[str] = None,
type: str = "value",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
choices (List[str]): list of options to select from.
value (List[str]): default selected list of options.
type (str): Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.choices = choices or []
self.cleared_value = []
self.type = type
self.value = self.postprocess(value)
self.test_input = self.choices
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"choices": self.choices,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
choices: Optional[List[str]] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"choices": choices,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: List[str]) -> List[str] | List[int]:
"""
Parameters:
x (List[str]): list of selected choices
Returns:
(List[str] | List[int]): list of selected choices as strings or indices within choice list
"""
if self.type == "value":
return x
elif self.type == "index":
return [self.choices.index(choice) for choice in x]
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'value', 'index'."
)
def set_interpret_parameters(self):
"""
Calculates interpretation score of each choice in the input by comparing the output against the outputs when each choice in the input is independently either removed or added.
"""
return self
def get_interpretation_neighbors(self, x):
leave_one_out_sets = []
for choice in self.choices:
leave_one_out_set = list(x)
if choice in leave_one_out_set:
leave_one_out_set.remove(choice)
else:
leave_one_out_set.append(choice)
leave_one_out_sets.append(leave_one_out_set)
return leave_one_out_sets, {}
def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
"""
Returns:
(List[Tuple[float, float]]): For each tuple in the list, the first value represents the interpretation score if the input is False, and the second if the input is True.
"""
final_scores = []
for choice, score in zip(self.choices, scores):
if choice in x:
score_set = [score, None]
else:
score_set = [None, score]
final_scores.append(score_set)
return final_scores
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (List[str]])
"""
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
def generate_sample(self):
return self.choices
# Output Functionalities
def postprocess(self, y):
"""
Any postprocessing needed to be performed on function output.
Parameters:
y (List[str]): List of selected choices
Returns:
(List[str]): List of selected choices
"""
return [] if y is None else y
def deserialize(self, x):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return x
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
item_container: Optional[bool] = None,
container: Optional[bool] = None,
):
if item_container is not None:
self._style["item_container"] = item_container
return IOComponent.style(
self,
rounded=rounded,
container=container,
)
class Radio(Changeable, IOComponent):
"""
Creates a set of radio buttons of which only one can be selected.
Preprocessing: passes the value of the selected radio button as a {str} or its index as an {int} into the function, depending on `type`.
Postprocessing: expects a {str} corresponding to the value of the radio button to be selected.
Demos: sentence_builder, titanic_survival, blocks_essay
"""
def __init__(
self,
choices: List[str] = None,
*,
value: Optional[str] = None,
type: str = "value",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
choices (List[str]): list of options to select from.
value (str): the button selected by default. If None, no button is selected by default.
type (str): Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.choices = choices or []
self.type = type
self.test_input = self.choices[0] if len(self.choices) else None
self.value = self.postprocess(value)
self.cleared_value = self.value
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"choices": self.choices,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
choices: Optional[List[str]] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"choices": choices,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: str) -> str | int:
"""
Parameters:
x (str): selected choice
Returns:
(str | int): selected choice as string or index within choice list
"""
if self.type == "value":
return x
elif self.type == "index":
if x is None:
return None
else:
return self.choices.index(x)
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'value', 'index'."
)
def set_interpret_parameters(self):
"""
Calculates interpretation score of each choice by comparing the output against each of the outputs when alternative choices are selected.
"""
return self
def get_interpretation_neighbors(self, x):
choices = list(self.choices)
choices.remove(x)
return choices, {}
def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
"""
Returns:
(List[float]): Each value represents the interpretation score corresponding to each choice.
"""
scores.insert(self.choices.index(x), None)
return scores
def generate_sample(self):
return self.choices[0]
# Output Functionalities
def postprocess(self, y):
"""
Any postprocessing needed to be performed on function output.
Parameters:
y (str): string of choice
Returns:
(str): string of choice
"""
return (
y if y is not None else self.choices[0] if len(self.choices) > 0 else None
)
def deserialize(self, x):
"""
Convert from serialized output (e.g. base64 representation) from a call() to the interface to a human-readable version of the output (path of an image, etc.)
"""
return x
def style(
self,
item_container: Optional[bool] = None,
container: Optional[bool] = None,
):
if item_container is not None:
self._style["item_container"] = item_container
return IOComponent.style(
self,
container=container,
)
class Dropdown(Radio):
"""
Creates a dropdown of which only one entry can be selected.
Preprocessing: passes the value of the selected dropdown entry as a {str} or its index as an {int} into the function, depending on `type`.
Postprocessing: expects a {str} corresponding to the value of the dropdown entry to be selected.
Demos: sentence_builder, titanic_survival
"""
def __init__(
self,
choices: List[str] = None,
*,
value: Optional[str] = None,
type: str = "value",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
choices (List[str]): list of options to select from.
value (str): default value selected in dropdown. If None, no value is selected by default.
type (str): Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
Radio.__init__(
self,
value=value,
choices=choices,
type=type,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
border: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
container: Optional[bool] = None,
):
return IOComponent.style(
self, rounded=rounded, border=border, container=container
)
class Image(Editable, Clearable, Changeable, Streamable, IOComponent):
"""
Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
Preprocessing: passes the uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type`.
Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} filepath to an image and displays the image.
Demos: image_classifier, image_mod, webcam, digit_classifier
"""
def __init__(
self,
value: Optional[str | PIL.Image | np.narray] = None,
*,
shape: Tuple[int, int] = None,
image_mode: str = "RGB",
invert_colors: bool = False,
source: str = "upload",
tool: str = "editor",
type: str = "numpy",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
streaming: bool = False,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (Optional[str | PIL.Image | np.narray]): A PIL Image, numpy array, path or URL for the default value that Image component is going to take.
shape (Tuple[int, int]): (width, height) shape to crop and resize image to; if None, matches input image size. Pass None for either width or height to only crop and resize the other.
image_mode (str): "RGB" if color, or "L" if black and white.
invert_colors (bool): whether to invert the image as a preprocessing step.
source (str): Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
tool (str): Tools used for editing. "editor" allows a full screen editor, "select" provides a cropping and zoom tool.
type (str): The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "file" produces a temporary file object whose path can be retrieved by file_obj.name, "filepath" passes a str path to a temporary file containing the image.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
streaming (bool): If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.
"""
self.type = type
self.value = self.postprocess(value)
self.shape = shape
self.image_mode = image_mode
self.source = source
requires_permissions = source == "webcam"
self.tool = tool
self.invert_colors = invert_colors
self.test_input = deepcopy(media_data.BASE64_IMAGE)
self.interpret_by_tokens = True
self.streaming = streaming
if streaming and source != "webcam":
raise ValueError("Image streaming only available if source is 'webcam'.")
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
requires_permissions=requires_permissions,
**kwargs,
)
def get_config(self):
return {
"image_mode": self.image_mode,
"shape": self.shape,
"source": self.source,
"tool": self.tool,
"value": self.value,
"streaming": self.streaming,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: Optional[str]) -> np.array | PIL.Image | str | None:
"""
Parameters:
x (str): base64 url data
Returns:
(numpy.array | PIL.Image | str): image in requested format
"""
if x is None:
return x
im = processing_utils.decode_base64_to_image(x)
fmt = im.format
with warnings.catch_warnings():
warnings.simplefilter("ignore")
im = im.convert(self.image_mode)
if self.shape is not None:
im = processing_utils.resize_and_crop(im, self.shape)
if self.invert_colors:
im = PIL.ImageOps.invert(im)
if self.type == "pil":
return im
elif self.type == "numpy":
return np.array(im)
elif self.type == "file" or self.type == "filepath":
file_obj = tempfile.NamedTemporaryFile(
delete=False,
suffix=("." + fmt.lower() if fmt is not None else ".png"),
)
im.save(file_obj.name)
if self.type == "file":
warnings.warn(
"The 'file' type has been deprecated. Set parameter 'type' to 'filepath' instead.",
DeprecationWarning,
)
return file_obj
else:
return file_obj.name
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'numpy', 'pil', 'filepath'."
)
def preprocess_example(self, x):
return processing_utils.encode_file_to_base64(x)
def serialize(self, x, called_directly=False):
# if called directly, can assume it's a URL or filepath
if self.type == "filepath" or called_directly:
return processing_utils.encode_url_or_file_to_base64(x)
elif self.type == "file":
return processing_utils.encode_url_or_file_to_base64(x.name)
elif self.type in ("numpy", "pil"):
if self.type == "numpy":
x = PIL.Image.fromarray(np.uint8(x)).convert("RGB")
fmt = x.format
file_obj = tempfile.NamedTemporaryFile(
delete=False,
suffix=("." + fmt.lower() if fmt is not None else ".png"),
)
x.save(file_obj.name)
return processing_utils.encode_url_or_file_to_base64(file_obj.name)
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'numpy', 'pil', 'filepath'."
)
def set_interpret_parameters(self, segments=16):
"""
Calculates interpretation score of image subsections by splitting the image into subsections, then using a "leave one out" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value.
Parameters:
segments (int): Number of interpretation segments to split image into.
"""
self.interpretation_segments = segments
return self
def _segment_by_slic(self, x):
"""
Helper method that segments an image into superpixels using slic.
Parameters:
x: base64 representation of an image
"""
x = processing_utils.decode_base64_to_image(x)
if self.shape is not None:
x = processing_utils.resize_and_crop(x, self.shape)
resized_and_cropped_image = np.array(x)
try:
from skimage.segmentation import slic
except (ImportError, ModuleNotFoundError):
raise ValueError(
"Error: running this interpretation for images requires scikit-image, please install it first."
)
try:
segments_slic = slic(
resized_and_cropped_image,
self.interpretation_segments,
compactness=10,
sigma=1,
start_label=1,
)
except TypeError: # For skimage 0.16 and older
segments_slic = slic(
resized_and_cropped_image,
self.interpretation_segments,
compactness=10,
sigma=1,
)
return segments_slic, resized_and_cropped_image
def tokenize(self, x):
"""
Segments image into tokens, masks, and leave-one-out-tokens
Parameters:
x: base64 representation of an image
Returns:
tokens: list of tokens, used by the get_masked_input() method
leave_one_out_tokens: list of left-out tokens, used by the get_interpretation_neighbors() method
masks: list of masks, used by the get_interpretation_neighbors() method
"""
segments_slic, resized_and_cropped_image = self._segment_by_slic(x)
tokens, masks, leave_one_out_tokens = [], [], []
replace_color = np.mean(resized_and_cropped_image, axis=(0, 1))
for (i, segment_value) in enumerate(np.unique(segments_slic)):
mask = segments_slic == segment_value
image_screen = np.copy(resized_and_cropped_image)
image_screen[segments_slic == segment_value] = replace_color
leave_one_out_tokens.append(
processing_utils.encode_array_to_base64(image_screen)
)
token = np.copy(resized_and_cropped_image)
token[segments_slic != segment_value] = 0
tokens.append(token)
masks.append(mask)
return tokens, leave_one_out_tokens, masks
def get_masked_inputs(self, tokens, binary_mask_matrix):
masked_inputs = []
for binary_mask_vector in binary_mask_matrix:
masked_input = np.zeros_like(tokens[0], dtype=int)
for token, b in zip(tokens, binary_mask_vector):
masked_input = masked_input + token * int(b)
masked_inputs.append(processing_utils.encode_array_to_base64(masked_input))
return masked_inputs
def get_interpretation_scores(
self, x, neighbors, scores, masks, tokens=None, **kwargs
):
"""
Returns:
(List[List[float]]): A 2D array representing the interpretation score of each pixel of the image.
"""
x = processing_utils.decode_base64_to_image(x)
if self.shape is not None:
x = processing_utils.resize_and_crop(x, self.shape)
x = np.array(x)
output_scores = np.zeros((x.shape[0], x.shape[1]))
for score, mask in zip(scores, masks):
output_scores += score * mask
max_val, min_val = np.max(output_scores), np.min(output_scores)
if max_val > 0:
output_scores = (output_scores - min_val) / (max_val - min_val)
return output_scores.tolist()
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (str) path to image file
"""
return self.save_flagged_file(dir, label, data, encryption_key)
def restore_flagged(self, dir, data, encryption_key):
return processing_utils.encode_file_to_base64(
os.path.join(dir, data), encryption_key=encryption_key
)
def generate_sample(self):
return deepcopy(media_data.BASE64_IMAGE)
# Output functions
def postprocess(self, y):
"""
Parameters:
y (numpy.array | PIL.Image | str): image in specified format
Returns:
(str): base64 url data
"""
if y is None:
return None
if isinstance(y, np.ndarray):
dtype = "numpy"
elif isinstance(y, PIL.Image.Image):
dtype = "pil"
elif isinstance(y, str):
dtype = "file"
else:
raise ValueError("Cannot process this value as an Image")
if dtype in ["numpy", "pil"]:
if dtype == "pil":
y = np.array(y)
out_y = processing_utils.encode_array_to_base64(y)
elif dtype == "file":
out_y = processing_utils.encode_url_or_file_to_base64(y)
return out_y
def deserialize(self, x):
return processing_utils.decode_base64_to_file(x).name
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
height: Optional[int] = None,
width: Optional[int] = None,
):
self._style["height"] = height
self._style["width"] = width
return IOComponent.style(
self,
rounded=rounded,
)
def stream(
self,
fn: Callable,
inputs: List[Component],
outputs: List[Component],
_js: Optional[str] = None,
):
"""
Parameters:
fn: Callable function
inputs: List of inputs
outputs: List of outputs
_js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
Returns: None
"""
if self.source != "webcam":
raise ValueError("Image streaming only available if source is 'webcam'.")
Streamable.stream(self, fn, inputs, outputs, _js)
class Video(Changeable, Clearable, Playable, IOComponent):
"""
Creates an video component that can be used to upload/record videos (as an input) or display videos (as an output).
Preprocessing: passes the uploaded video as a {str} filepath whose extension can be set by `format`.
Postprocessing: expects a {str} filepath to a video which is displayed.
Demos: video_identity
"""
def __init__(
self,
value: Optional[str] = None,
*,
format: Optional[str] = None,
source: str = "upload",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): A path or URL for the default value that Video component is going to take.
format (str): Format of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format.
source (str): Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.format = format
self.source = source
self.value = self.postprocess(value)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"source": self.source,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
source: Optional[str] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"source": source,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess_example(self, x):
return {"name": x, "data": None, "is_example": True}
def preprocess(self, x: Dict[str, str] | None) -> str | None:
"""
Parameters:
x (Dict[name: str, data: str]): JSON object with filename as 'name' property and base64 data as 'data' property
Returns:
(str): file path to video
"""
if x is None:
return x
file_name, file_data, is_example = (
x["name"],
x["data"],
x.get("is_example", False),
)
if is_example:
file = processing_utils.create_tmp_copy_of_file(file_name)
else:
file = processing_utils.decode_base64_to_file(
file_data, file_path=file_name
)
file_name = file.name
uploaded_format = file_name.split(".")[-1].lower()
if self.format is not None and uploaded_format != self.format:
output_file_name = file_name[0 : file_name.rindex(".") + 1] + self.format
ff = FFmpeg(inputs={file_name: None}, outputs={output_file_name: None})
ff.run()
return output_file_name
else:
return file_name
def serialize(self, x, called_directly):
data = processing_utils.encode_url_or_file_to_base64(x)
return {"name": x, "data": data, "is_example": False}
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (str) path to video file
"""
return self.save_flagged_file(
dir, label, None if data is None else data["data"], encryption_key
)
def restore_flagged(self, dir, data, encryption_key):
return self.restore_flagged_file(dir, data, encryption_key)
def generate_sample(self):
return deepcopy(media_data.BASE64_VIDEO)
def postprocess(self, y):
"""
Parameters:
y (str): path to video
Returns:
(str): base64 url data
"""
if y is None:
return None
returned_format = y.split(".")[-1].lower()
if self.format is not None and returned_format != self.format:
output_file_name = y[0 : y.rindex(".") + 1] + self.format
ff = FFmpeg(inputs={y: None}, outputs={output_file_name: None})
ff.run()
y = output_file_name
return {
"name": os.path.basename(y),
"data": processing_utils.encode_file_to_base64(y),
}
def deserialize(self, x):
file = processing_utils.decode_base64_to_file(x["data"])
return file.name
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
height: Optional[int] = None,
width: Optional[int] = None,
):
self._style["height"] = height
self._style["width"] = width
return IOComponent.style(
self,
rounded=rounded,
)
class Audio(Changeable, Clearable, Playable, Streamable, IOComponent):
"""
Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).
Preprocessing: passes the uploaded audio as a {Tuple(int, numpy.array)} corresponding to (sample rate, data) or as a {str} filepath, depending on `type`
Postprocessing: expects a {Tuple(int, numpy.array)} corresponding to (sample rate, data) or as a {str} filepath to an audio file, which gets displayed
Demos: main_note, generate_tone, reverse_audio
"""
def __init__(
self,
value: Optional[str | Tuple[int, np.array]] = None,
*,
source: str = "upload",
type: str = "numpy",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
streaming: bool = False,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str | Tuple[int, numpy.array]): A path, URL, or [sample_rate, numpy array] tuple for the default value that Audio component is going to take.
source (str): Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input.
type (str): The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
streaming (bool): If set to true when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'microphone'.
"""
self.value = self.postprocess(value)
self.source = source
requires_permissions = source == "microphone"
self.type = type
self.test_input = deepcopy(media_data.BASE64_AUDIO)
self.interpret_by_tokens = True
self.streaming = streaming
if streaming and source != "microphone":
raise ValueError(
"Audio streaming only available if source is 'microphone'."
)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
requires_permissions=requires_permissions,
**kwargs,
)
def get_config(self):
return {
"source": self.source,
"value": self.value,
"streaming": self.streaming,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
source: Optional[str] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"source": source,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess_example(self, x):
return {"name": x, "data": None, "is_example": True}
def preprocess(self, x: Dict[str, str] | None) -> Tuple[int, np.array] | str | None:
"""
Parameters:
x (Dict[name: str, data: str]): JSON object with filename as 'name' property and base64 data as 'data' property
Returns:
(Tuple[int, numpy.array] | str): audio in requested format
"""
if x is None:
return x
file_name, file_data, is_example = (
x["name"],
x["data"],
x.get("is_example", False),
)
crop_min, crop_max = x.get("crop_min", 0), x.get("crop_max", 100)
if is_example:
file_obj = processing_utils.create_tmp_copy_of_file(file_name)
else:
file_obj = processing_utils.decode_base64_to_file(
file_data, file_path=file_name
)
if crop_min != 0 or crop_max != 100:
sample_rate, data = processing_utils.audio_from_file(
file_obj.name, crop_min=crop_min, crop_max=crop_max
)
processing_utils.audio_to_file(sample_rate, data, file_obj.name)
if self.type == "file":
warnings.warn(
"The 'file' type has been deprecated. Set parameter 'type' to 'filepath' instead.",
DeprecationWarning,
)
return file_obj
elif self.type == "filepath":
return file_obj.name
elif self.type == "numpy":
return processing_utils.audio_from_file(file_obj.name)
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'numpy', 'filepath'."
)
def serialize(self, x, called_directly):
if x is None:
return None
if self.type == "filepath" or called_directly:
name = x
elif self.type == "file":
warnings.warn(
"The 'file' type has been deprecated. Set parameter 'type' to 'filepath' instead.",
DeprecationWarning,
)
name = x.name
elif self.type == "numpy":
file = tempfile.NamedTemporaryFile(delete=False)
name = file.name
processing_utils.audio_to_file(x[0], x[1], name)
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'numpy', 'filepath'."
)
file_data = processing_utils.encode_url_or_file_to_base64(name)
return {"name": name, "data": file_data, "is_example": False}
def set_interpret_parameters(self, segments=8):
"""
Calculates interpretation score of audio subsections by splitting the audio into subsections, then using a "leave one out" method to calculate the score of each subsection by removing the subsection and measuring the delta of the output value.
Parameters:
segments (int): Number of interpretation segments to split audio into.
"""
self.interpretation_segments = segments
return self
def tokenize(self, x):
if x.get("is_example"):
sample_rate, data = processing_utils.audio_from_file(x["name"])
else:
file_obj = processing_utils.decode_base64_to_file(x["data"])
sample_rate, data = processing_utils.audio_from_file(file_obj.name)
leave_one_out_sets = []
tokens = []
masks = []
duration = data.shape[0]
boundaries = np.linspace(0, duration, self.interpretation_segments + 1).tolist()
boundaries = [round(boundary) for boundary in boundaries]
for index in range(len(boundaries) - 1):
start, stop = boundaries[index], boundaries[index + 1]
masks.append((start, stop))
# Handle the leave one outs
leave_one_out_data = np.copy(data)
leave_one_out_data[start:stop] = 0
file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
processing_utils.audio_to_file(sample_rate, leave_one_out_data, file.name)
out_data = processing_utils.encode_file_to_base64(file.name)
leave_one_out_sets.append(out_data)
file.close()
os.unlink(file.name)
# Handle the tokens
token = np.copy(data)
token[0:start] = 0
token[stop:] = 0
file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
processing_utils.audio_to_file(sample_rate, token, file.name)
token_data = processing_utils.encode_file_to_base64(file.name)
file.close()
os.unlink(file.name)
tokens.append(token_data)
tokens = [{"name": "token.wav", "data": token} for token in tokens]
leave_one_out_sets = [
{"name": "loo.wav", "data": loo_set} for loo_set in leave_one_out_sets
]
return tokens, leave_one_out_sets, masks
def get_masked_inputs(self, tokens, binary_mask_matrix):
# create a "zero input" vector and get sample rate
x = tokens[0]["data"]
file_obj = processing_utils.decode_base64_to_file(x)
sample_rate, data = processing_utils.audio_from_file(file_obj.name)
zero_input = np.zeros_like(data, dtype="int16")
# decode all of the tokens
token_data = []
for token in tokens:
file_obj = processing_utils.decode_base64_to_file(token["data"])
_, data = processing_utils.audio_from_file(file_obj.name)
token_data.append(data)
# construct the masked version
masked_inputs = []
for binary_mask_vector in binary_mask_matrix:
masked_input = np.copy(zero_input)
for t, b in zip(token_data, binary_mask_vector):
masked_input = masked_input + t * int(b)
file = tempfile.NamedTemporaryFile(delete=False)
processing_utils.audio_to_file(sample_rate, masked_input, file.name)
masked_data = processing_utils.encode_file_to_base64(file.name)
file.close()
os.unlink(file.name)
masked_inputs.append(masked_data)
return masked_inputs
def get_interpretation_scores(self, x, neighbors, scores, masks=None, tokens=None):
"""
Returns:
(List[float]): Each value represents the interpretation score corresponding to an evenly spaced subsection of audio.
"""
return list(scores)
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (str) path to audio file
"""
if data is None:
data_string = None
elif isinstance(data, str):
data_string = data
else:
data_string = data["data"]
is_example = data.get("is_example", False)
if is_example:
file_obj = processing_utils.create_tmp_copy_of_file(data["name"])
return self.save_file(file_obj, dir, label)
return self.save_flagged_file(dir, label, data_string, encryption_key)
def restore_flagged(self, dir, data, encryption_key):
return self.restore_flagged_file(dir, data, encryption_key)
def generate_sample(self):
return deepcopy(media_data.BASE64_AUDIO)
def postprocess(self, y):
"""
Parameters:
y (Tuple[int, numpy.array] | str): audio data in requested format
Returns:
(str): base64 url data
"""
if y is None:
return None
if isinstance(y, tuple):
sample_rate, data = y
file = tempfile.NamedTemporaryFile(
prefix="sample", suffix=".wav", delete=False
)
processing_utils.audio_to_file(sample_rate, data, file.name)
y = file.name
return processing_utils.encode_url_or_file_to_base64(y)
def deserialize(self, x):
file = processing_utils.decode_base64_to_file(x["data"])
return file.name
def stream(
self,
fn: Callable,
inputs: List[Component],
outputs: List[Component],
_js: Optional[str] = None,
):
"""
Parameters:
fn: Callable function
inputs: List of inputs
outputs: List of outputs
_js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
Returns: None
"""
if self.source != "microphone":
raise ValueError(
"Audio streaming only available if source is 'microphone'."
)
Streamable.stream(self, fn, inputs, outputs, _js)
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
return IOComponent.style(
self,
rounded=rounded,
)
class File(Changeable, Clearable, IOComponent):
"""
Creates a file component that allows uploading generic file (when used as an input) and or displaying generic files (output).
Preprocessing: passes the uploaded file as a {file-object} or {List[file-object]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`)
Postprocessing: expects a {str} path to a file returned by the function.
Demos: zip_to_json, zip_two_files
"""
def __init__(
self,
value: Optional[str] = None,
*,
file_count: str = "single",
type: str = "file",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (Optional[str]): Default file to display, given as str file path
file_count (str): if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory".
type (str): Type of value to be returned by component. "file" returns a temporary file object whose path can be retrieved by file_obj.name, "binary" returns an bytes object.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.file_count = file_count
self.type = type
self.value = self.postprocess(value)
self.test_input = None
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"file_count": self.file_count,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess_example(self, x):
if isinstance(x, list):
return [
{
"name": file,
"data": None,
"size": os.path.getsize(file),
"is_example": True,
}
for file in x
]
else:
return {
"name": x,
"data": None,
"size": os.path.getsize(x),
"is_example": True,
}
def preprocess(self, x: List[Dict[str, str]] | None):
"""
Parameters:
x (List[Dict[name: str, data: str]]): List of JSON objects with filename as 'name' property and base64 data as 'data' property
Returns:
(file-object | bytes | List[file-object] | List[bytes]]): File objects in requested format
"""
if x is None:
return None
def process_single_file(f):
file_name, data, is_example = (
f["name"],
f["data"],
f.get("is_example", False),
)
if self.type == "file":
if is_example:
return processing_utils.create_tmp_copy_of_file(file_name)
else:
return processing_utils.decode_base64_to_file(
data, file_path=file_name
)
elif self.type == "bytes":
if is_example:
with open(file_name, "rb") as file_data:
return file_data.read()
return processing_utils.decode_base64_to_binary(data)[0]
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'file', 'bytes'."
)
if self.file_count == "single":
if isinstance(x, list):
return process_single_file(x[0])
else:
return process_single_file(x)
else:
return [process_single_file(f) for f in x]
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (str) path to file
"""
if isinstance(data, list):
return self.save_flagged_file(
dir, label, None if data is None else data[0]["data"], encryption_key
)
else:
return self.save_flagged_file(
dir, label, data["data"], encryption_key, data["name"]
)
def generate_sample(self):
return deepcopy(media_data.BASE64_FILE)
# Output Functionalities
def postprocess(self, y):
"""
Parameters:
y (str): file path
Returns:
(Dict[name: str, size: number, data: str]): JSON object with key 'name' for filename, 'data' for base64 url, and 'size' for filesize in bytes
"""
if y is None:
return None
if isinstance(y, list):
return [
{
"name": os.path.basename(file),
"size": os.path.getsize(file),
"data": processing_utils.encode_file_to_base64(file),
}
for file in y
]
else:
return {
"name": os.path.basename(y),
"size": os.path.getsize(y),
"data": processing_utils.encode_file_to_base64(y),
}
def deserialize(self, x):
file = processing_utils.decode_base64_to_file(x["data"])
return file.name
def restore_flagged(self, dir, data, encryption_key):
return self.restore_flagged_file(dir, data, encryption_key)
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
return IOComponent.style(
self,
rounded=rounded,
)
class Dataframe(Changeable, IOComponent):
"""
Accepts or displays 2D input through a spreadsheet-like component for dataframes.
Preprocessing: passes the uploaded spreadsheet data as a {pandas.DataFrame}, {numpy.array}, {List[List]}, or {List} depending on `type`
Postprocessing: expects a {pandas.DataFrame}, {numpy.array}, {List[List]}, {List}, or {str} path to a csv, which is rendered in the spreadsheet.
Demos: filter_records, matrix_transpose, tax_calculator
"""
def __init__(
self,
value: Optional[List[List[Any]]] = None,
*,
headers: Optional[List[str]] = None,
row_count: int | Tuple[int, str] = (3, "dynamic"),
col_count: Optional[int | Tuple[int, str]] = None,
datatype: str | List[str] = "str",
type: str = "pandas",
max_rows: Optional[int] = 20,
max_cols: Optional[int] = None,
overflow_row_behaviour: str = "paginate",
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (List[List[Any]]): Default value as a 2-dimensional list of values.
headers (List[str] | None): List of str header names. If None, no headers are shown.
row_count (int | Tuple[int, str]): Limit number of rows for input and decide whether user can create new rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic'
col_count (int | Tuple[int, str]): Limit number of columns for input and decide whether user can create new columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic'
datatype (str | List[str]): Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", and "date".
type (str): Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array.
label (str): component name in interface.
max_rows (int): Maximum number of rows to display at once. Set to None for infinite.
max_cols (int): Maximum number of columns to display at once. Set to None for infinite.
overflow_row_behaviour (str): If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.row_count = self.__process_counts(row_count)
self.col_count = self.__process_counts(
col_count, len(headers) if headers else 3
)
self.__validate_headers(headers, self.col_count[0])
self.headers = headers
self.datatype = datatype
self.type = type
values = {
"str": "",
"number": 0,
"bool": False,
"date": "01/01/1970",
}
column_dtypes = (
[datatype] * self.col_count[0] if isinstance(datatype, str) else datatype
)
self.test_input = [
[values[c] for c in column_dtypes] for _ in range(self.row_count[0])
]
self.value = value if value is not None else self.test_input
self.max_rows = max_rows
self.max_cols = max_cols
self.overflow_row_behaviour = overflow_row_behaviour
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"headers": self.headers,
"datatype": self.datatype,
"row_count": self.row_count,
"col_count": self.col_count,
"value": self.value,
"max_rows": self.max_rows,
"max_cols": self.max_cols,
"overflow_row_behaviour": self.overflow_row_behaviour,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
max_rows: Optional[int] = None,
max_cols: Optional[str] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"max_rows": max_rows,
"max_cols": max_cols,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: List[List[str | Number | bool]]):
"""
Parameters:
x (List[List[str | number | bool]]): 2D array of str, numeric, or bool data
Returns:
(pandas.DataFrame | numpy.array | List[str | float | bool], List[List[str | float | bool]]): Dataframe in requested format
"""
if self.type == "pandas":
if self.headers:
return pd.DataFrame(x, columns=self.headers)
else:
return pd.DataFrame(x)
if self.col_count[0] == 1:
x = [row[0] for row in x]
if self.type == "numpy":
return np.array(x)
elif self.type == "array":
return x
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'pandas', 'numpy', 'array'."
)
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (List[List[str | float]]) 2D array
"""
return json.dumps(data)
# TODO: (faruk) output was dumping differently, how to converge?
# return json.dumps(data["data"])
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
# TODO: (faruk) output was dumping differently, how to converge?
# return {"data": json.loads(data)}
def generate_sample(self):
return [[1, 2, 3], [4, 5, 6]]
def postprocess(self, y):
"""
Parameters:
y (str | pandas.DataFrame | numpy.array | List[str | float], List[List[str | float]]]): dataframe in given format
Returns:
(Dict[headers: List[str], data: List[List[str | number]]]): JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data
"""
if y is None:
return y
if isinstance(y, str):
y = pd.read_csv(str)
return {"headers": list(y.columns), "data": y.values.tolist()}
if isinstance(y, pd.DataFrame):
return {"headers": list(y.columns), "data": y.values.tolist()}
if isinstance(y, (np.ndarray, list)):
if isinstance(y, np.ndarray):
y = y.tolist()
if len(y) == 0 or not isinstance(y[0], list):
y = [y]
return {"data": y}
raise ValueError("Cannot process value as a Dataframe")
@staticmethod
def __process_counts(count, default=3):
if count is None:
return (default, "dynamic")
if type(count) == int or type(count) == float:
return (int(count), "dynamic")
else:
return count
@staticmethod
def __validate_headers(headers: List[str] | None, col_count: int):
if headers is not None and len(headers) != col_count:
raise ValueError(
"The length of the headers list must be equal to the col_count int.\nThe column count is set to {cols} but `headers` has {headers} items. Check the values passed to `col_count` and `headers`.".format(
cols=col_count, headers=len(headers)
)
)
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
border: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
return IOComponent.style(
self,
rounded=rounded,
)
class Timeseries(Changeable, IOComponent):
"""
Creates a component that can be used to upload/preview timeseries csv files or display a dataframe consisting of a time series graphically.
Preprocessing: passes the uploaded timeseries data as a {pandas.DataFrame} into the function
Postprocessing: expects a {pandas.DataFrame} or {str} path to a csv to be returned, which is then displayed as a timeseries graph
Demos: fraud_detector
"""
def __init__(
self,
value: Optional[str] = None,
*,
x: Optional[str] = None,
y: str | List[str] = None,
colors: List[str] = None,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value: File path for the timeseries csv file.
x (str): Column name of x (time) series. None if csv has no headers, in which case first column is x series.
y (str | List[str]): Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
label (str): component name in interface.
colors (List[str]): an ordered list of colors to use for each line plot
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.value = self.postprocess(value)
self.x = x
if isinstance(y, str):
y = [y]
self.y = y
self.colors = colors
IOComponent.__init__(
self,
label=label,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"x": self.x,
"y": self.y,
"value": self.value,
"colors": self.colors,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
colors: Optional[List[str]] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"colors": colors,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess_example(self, x):
return {"name": x, "is_example": True}
def preprocess(self, x: Dict | None) -> pd.DataFrame | None:
"""
Parameters:
x (Dict[data: List[List[str | number | bool]], headers: List[str], range: List[number]]): Dict with keys 'data': 2D array of str, numeric, or bool data, 'headers': list of strings for header names, 'range': optional two element list designating start of end of subrange.
Returns:
(pandas.DataFrame): Dataframe of timeseries data
"""
if x is None:
return x
elif x.get("is_example"):
dataframe = pd.read_csv(x["name"])
else:
dataframe = pd.DataFrame(data=x["data"], columns=x["headers"])
if x.get("range") is not None:
dataframe = dataframe.loc[dataframe[self.x or 0] >= x["range"][0]]
dataframe = dataframe.loc[dataframe[self.x or 0] <= x["range"][1]]
return dataframe
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (List[List[str | float]]) 2D array
"""
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
def generate_sample(self):
return {"data": [[1] + [2] * len(self.y)] * 4, "headers": [self.x] + self.y}
# Output Functionalities
def postprocess(self, y):
"""
Parameters:
y (str | pandas.DataFrame): csv or dataframe with timeseries data
Returns:
(Dict[headers: List[str], data: List[List[str | number]]]): JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data
"""
if y is None:
return None
if isinstance(y, str):
y = pd.read_csv(y)
return {"headers": y.columns.values.tolist(), "data": y.values.tolist()}
if isinstance(y, pd.DataFrame):
return {"headers": y.columns.values.tolist(), "data": y.values.tolist()}
raise ValueError("Cannot process value as Timeseries data")
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
border: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
return IOComponent.style(
self,
rounded=rounded,
)
class Variable(IOComponent):
"""
Special hidden component that stores session state across runs of the demo by the
same user. The value of the Variable is cleared when the user refreshes the page.
Preprocessing: No preprocessing is performed
Postprocessing: No postprocessing is performed
Demos: chatbot_demo, blocks_simple_squares
"""
def __init__(
self,
value: Any = None,
**kwargs,
):
"""
Parameters:
value (Any): the initial value of the state.
"""
self.value = value
self.stateful = True
IOComponent.__init__(self, **kwargs)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
def style(self):
return self
############################
# Only Output Components
############################
class Label(Changeable, IOComponent):
"""
Displays a classification label, along with confidence scores of top categories, if provided.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a {Dict[str, float]} of classes and confidences, or {str} with just the class or an {int}/{float} for regression outputs.
Demos: image_classifier, main_note, titanic_survival
"""
CONFIDENCES_KEY = "confidences"
def __init__(
self,
value: Optional[str] = None,
*,
num_top_classes: Optional[int] = None,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value(str): Default value to show in the component.
num_top_classes (int): number of most confident classes to show.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.num_top_classes = num_top_classes
self.value = self.postprocess(value)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"num_top_classes": self.num_top_classes,
"value": self.value,
**IOComponent.get_config(self),
}
def postprocess(self, y):
"""
Parameters:
y (Dict[str, float] | str | Number): a dictionary mapping labels to confidence value, or just a string/numerical label by itself
Returns:
(Dict[label: str, confidences: List[Dict[label: str, confidence: number]]]): Object with key 'label' representing primary label, and key 'confidences' representing a list of label-confidence pairs
"""
if y is None:
return None
if isinstance(y, (str, numbers.Number)):
return {"label": str(y)}
if isinstance(y, dict):
sorted_pred = sorted(y.items(), key=operator.itemgetter(1), reverse=True)
if self.num_top_classes is not None:
sorted_pred = sorted_pred[: self.num_top_classes]
return {
"label": sorted_pred[0][0],
"confidences": [
{"label": pred[0], "confidence": pred[1]} for pred in sorted_pred
],
}
raise ValueError(
"The `Label` output interface expects one of: a string label, or an int label, a "
"float label, or a dictionary whose keys are labels and values are confidences. "
"Instead, got a {}".format(type(y))
)
def deserialize(self, y):
if y is None:
return None
# 5 cases: (1): {'label': 'lion'}, {'label': 'lion', 'confidences':...}, {'lion': 0.46, ...}, 'lion', '0.46'
if isinstance(y, (str, numbers.Number)) or (
"label" in y and not ("confidences" in y.keys())
):
if isinstance(y, (str, numbers.Number)):
return y
else:
return y["label"]
if ("confidences" in y.keys()) and isinstance(y["confidences"], list):
return {k["label"]: k["confidence"] for k in y["confidences"]}
else:
return y
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (str | Dict[str, number]): Either a string representing the main category label, or a dictionary with category keys mapping to confidence levels.
"""
if "confidences" in data:
return json.dumps(
{
example["label"]: example["confidence"]
for example in data["confidences"]
}
)
else:
return data["label"]
def restore_flagged(self, dir, data, encryption_key):
try:
data = json.loads(data)
return self.postprocess(data)
except ValueError:
return data
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def style(
self,
container: Optional[bool] = None,
):
return IOComponent.style(self, container=container)
class HighlightedText(Changeable, IOComponent):
"""
Displays text that contains spans that are highlighted by category or numerical value.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a {List[Tuple[str, float | str]]]} consisting of spans of text and their associated labels.
Demos: diff_texts, text_analysis
"""
def __init__(
self,
value: Optional[str] = None,
*,
color_map: Dict[str, str] = None,
show_legend: bool = False,
combine_adjacent: bool = False,
adjacent_separator: str = "",
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (List[Tuple[str, str | Number | None]]): Default value to show.
color_map (Dict[str, str]): Map between category and respective colors.
combine_adjacent (bool): If True, will merge the labels of adjacent tokens belonging to the same category.
adjacent_separator (str): Specifies the separator to be used between tokens if combine_adjacent is True.
show_legend (bool): whether to show span categories in a separate legend or inline.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.color_map = color_map
if color_map is not None:
warnings.warn(
"The 'color_map' parameter has been moved from the constructor to `HighlightedText.style()` ",
DeprecationWarning,
)
self.show_legend = show_legend
self.combine_adjacent = combine_adjacent
self.adjacent_separator = adjacent_separator
self.value = self.postprocess(value)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"color_map": self.color_map,
"show_legend": self.show_legend,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
color_map: Optional[Dict[str, str]] = None,
show_legend: Optional[bool] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"color_map": color_map,
"show_legend": show_legend,
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y):
"""
Parameters:
y (List[Tuple[str, str | number | None]]): List of (word, category) tuples
Returns:
(List[Tuple[str, str | number | None]]): List of (word, category) tuples
"""
if y is None:
return None
if self.combine_adjacent:
output = []
running_text, running_category = None, None
for text, category in y:
if running_text is None:
running_text = text
running_category = category
elif category == running_category:
running_text += self.adjacent_separator + text
else:
output.append((running_text, running_category))
running_text = text
running_category = category
if running_text is not None:
output.append((running_text, running_category))
return output
else:
return y
def save_flagged(self, dir, label, data, encryption_key):
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
color_map: Optional[Dict[str, str]] = None,
container: Optional[bool] = None,
):
if color_map is not None:
self._style["color_map"] = color_map
return IOComponent.style(self, rounded=rounded, container=container)
class JSON(Changeable, IOComponent):
"""
Used to display arbitrary JSON output prettily.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a valid JSON {str} -- or a {list} or {dict} that is JSON serializable.
Demos: zip_to_json, blocks_xray
"""
def __init__(
self,
value: Optional[str] = None,
*,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): Default value
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.value = self.postprocess(value)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y):
"""
Parameters:
y (Dict | List | str]): JSON output
Returns:
(Dict | List): JSON output
"""
if isinstance(y, str):
return json.dumps(y)
else:
return y
def save_flagged(self, dir, label, data, encryption_key):
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
def style(self, container: Optional[bool] = None):
return IOComponent.style(self, container=container)
class HTML(Changeable, IOComponent):
"""
Used to display arbitrary HTML output.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a valid HTML {str}.
Demos: text_analysis
"""
def __init__(
self,
value: str = "",
*,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): Default value
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.value = value
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def style(self):
return self
class Gallery(IOComponent):
"""
Used to display a list of images as a gallery that can be scrolled through.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a list of images in any format, {List[numpy.array | PIL.Image | str]}, and displays them.
Demos: fake_gan
"""
def __init__(
self,
value: Optional[List[np.ndarray | PIL.Image | str]] = None,
*,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (Optional[List[np.ndarray | PIL.Image | str]]): List of images to display in the gallery by default
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.value = self.postprocess(value)
super().__init__(
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y):
"""
Parameters:
y (List[numpy.array | PIL.Image | str]): list of images
Returns:
(str): list of base64 url data for images
"""
if y is None:
return []
output = []
for img in y:
if isinstance(img, np.ndarray):
img = processing_utils.encode_array_to_base64(img)
elif isinstance(img, PIL.Image.Image):
img = np.array(img)
img = processing_utils.encode_array_to_base64(img)
elif isinstance(img, str):
img = processing_utils.encode_url_or_file_to_base64(img)
else:
raise ValueError(
"Unknown type. Please choose from: 'numpy', 'pil', 'file'."
)
output.append(img)
return output
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
grid: Optional[int | Tuple[int, int, int, int, int, int]] = None,
height: Optional[str] = None,
container: Optional[bool] = None,
):
if grid is not None:
self._style["grid"] = grid
if height is not None:
self._style["height"] = height
return IOComponent.style(self, rounded=rounded, container=container)
class Carousel(IOComponent, Changeable):
"""
Component displays a set of output components that can be scrolled through.
Output type: List[List[Any]]
Demos: disease_report
"""
def __init__(
self,
*,
components: Component | List[Component],
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
components (List[Component] | Component): Classes of component(s) that will be scrolled through.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
warnings.warn(
"The Carousel component is partially deprecated. It may not behave as expected.",
DeprecationWarning,
)
if not isinstance(components, list):
components = [components]
self.components = [
get_component_instance(component) for component in components
]
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"components": [component.get_config() for component in self.components],
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y):
"""
Parameters:
y (List[List[Any]]): carousel output
Returns:
(List[List[Any]]): 2D array, where each sublist represents one set of outputs or 'slide' in the carousel
"""
if isinstance(y, list):
if len(y) != 0 and not isinstance(y[0], list):
y = [[z] for z in y]
output = []
for row in y:
output_row = []
for i, cell in enumerate(row):
output_row.append(self.components[i].postprocess(cell))
output.append(output_row)
return output
else:
raise ValueError("Unknown type. Please provide a list for the Carousel.")
def save_flagged(self, dir, label, data, encryption_key):
return json.dumps(
[
[
component.save_flagged(
dir, f"{label}_{j}", data[i][j], encryption_key
)
for j, component in enumerate(self.components)
]
for i, _ in enumerate(data)
]
)
def restore_flagged(self, dir, data, encryption_key):
return [
[
component.restore_flagged(dir, sample, encryption_key)
for component, sample in zip(self.components, sample_set)
]
for sample_set in json.loads(data)
]
class Chatbot(Changeable, IOComponent):
"""
Displays a chatbot output showing both user submitted messages and responses
Preprocessing: this component does *not* accept input.
Postprocessing: expects a {List[Tuple[str, str]]}, a list of tuples with user inputs and responses.
Demos: chatbot_demo
"""
def __init__(
self,
value: Optional[List[Tuple[str, str]]] = None,
color_map: Dict[str, str] = None,
*,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): Default value to show in chatbot
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
if color_map is not None:
warnings.warn(
"The 'color_map' parameter has been moved from the constructor to `Chatbot.style()` ",
DeprecationWarning,
)
self.value = self.postprocess(value)
self.color_map = color_map
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"value": self.value,
"color_map": self.color_map,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
color_map: Optional[Tuple[str, str]] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"color_map": color_map,
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y):
"""
Parameters:
y (List[Tuple[str, str]]): List of tuples representing the message and response
Returns:
(List[Tuple[str, str]]): Returns same list of tuples
"""
return y
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
color_map: Optional[Dict[str, str]] = None,
):
if color_map is not None:
self._style["color_map"] = color_map
return IOComponent.style(
self,
rounded=rounded,
)
class Model3D(Changeable, Editable, Clearable, IOComponent):
"""
Component creates a 3D Model component with input and output capabilities.
Input type: File object of type (.obj, glb, or .gltf)
Output type: filepath
Demos: model3D
"""
def __init__(
self,
value: Optional[str] = None,
*,
clear_color: List[float] = None,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (Optional[str]): path to (.obj, glb, or .gltf) file to show in model3D viewer
clear_color (List[r, g, b, a]): background color of scene
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.clear_color = clear_color or [0.2, 0.2, 0.2, 1.0]
self.value = self.postprocess(value)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {
"clearColor": self.clear_color,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess_example(self, x):
return {"name": x, "data": None, "is_example": True}
def preprocess(self, x: Dict[str, str] | None) -> str | None:
"""
Parameters:
x (Dict[name: str, data: str]): JSON object with filename as 'name' property and base64 data as 'data' property
Returns:
(str): file path to 3D image model
"""
if x is None:
return x
file_name, file_data, is_example = (
x["name"],
x["data"],
x.get("is_example", False),
)
if is_example:
file = processing_utils.create_tmp_copy_of_file(file_name)
else:
file = processing_utils.decode_base64_to_file(
file_data, file_path=file_name
)
file_name = file.name
return file_name
def serialize(self, x, called_directly):
raise NotImplementedError()
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (str) path to 3D image model file
"""
return self.save_flagged_file(
dir, label, data["data"], encryption_key, data["name"]
)
def generate_sample(self):
return media_data.BASE64_MODEL3D
# Output functions
def postprocess(self, y):
"""
Parameters:
y (str): path to the model
Returns:
(Dict[name (str): file name, data (str): base64 url data] | None)
"""
if y is None:
return y
data = {
"name": os.path.basename(y),
"data": processing_utils.encode_file_to_base64(y),
}
return data
def deserialize(self, x):
file = processing_utils.decode_base64_to_file(x["data"], file_path=x["name"])
return file.name
def restore_flagged(self, dir, data, encryption_key):
return self.restore_flagged_file(dir, data, encryption_key, as_data=True)
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
return IOComponent.style(
self,
rounded=rounded,
)
class Plot(Changeable, Clearable, IOComponent):
"""
Used to display various kinds of plots (matplotlib, plotly, or bokeh are supported)
Preprocessing: this component does *not* accept input.
Postprocessing: expects either a {matplotlib.figure.Figure}, a {plotly.graph_objects._figure.Figure}, or a {dict} corresponding to a bokeh plot (json_item format)
Demos: outbreak_forecast, blocks_kinematics, stock_forecast
"""
def __init__(
self,
value=None,
*,
label: Optional[str] = None,
show_label: bool = True,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (Optional[matplotlib.figure.Figure | dict | plotly.graph_objects._figure.Figure]): Optionally, supply a default plot object to display, must be a matplotlib, plotly, or bokeh figure.
label (Optional[str]): component name in interface.
show_label (bool): if True, will display label.
visible (bool): If False, component will be hidden.
"""
self.value = self.postprocess(value)
IOComponent.__init__(
self,
label=label,
show_label=show_label,
visible=visible,
elem_id=elem_id,
**kwargs,
)
def get_config(self):
return {"value": self.value, **IOComponent.get_config(self)}
@staticmethod
def update(
value: Optional[Any] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
):
return {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y):
"""
Parameters:
y (str): plot data
Returns:
(Dict[type (str): plot type, plot (str): plot base64 | json] | None)
"""
if y is None:
return None
if isinstance(y, (ModuleType, matplotlib.figure.Figure)):
dtype = "matplotlib"
out_y = processing_utils.encode_plot_to_base64(y)
elif isinstance(y, dict):
dtype = "bokeh"
out_y = json.dumps(y)
else:
dtype = "plotly"
out_y = y.to_json()
return {"type": dtype, "plot": out_y}
def style(self):
return self
class Markdown(IOComponent, Changeable):
"""
Used to render arbitrary Markdown output.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a valid {str} that can be rendered as Markdown.
Demos: blocks_hello, blocks_kinematics
"""
def __init__(
self,
value: str = "",
*,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): Value to show in Markdown component
visible (bool): If False, component will be hidden.
"""
IOComponent.__init__(self, visible=visible, elem_id=elem_id, **kwargs)
self.md = MarkdownIt()
self.value = self.postprocess(value)
def postprocess(self, y):
if y is None:
return None
unindented_y = inspect.cleandoc(y)
return self.md.render(unindented_y)
def get_config(self):
return {
"value": self.value,
**Component.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
visible: Optional[bool] = None,
):
return {
"visible": visible,
"value": value,
"__type__": "update",
}
def style(self):
return self
############################
# Static Components
############################
class Button(Clickable, Component):
"""
Used to create a button, that can be assigned arbitrary click() events. Accepts neither input nor output.
Demos: blocks_inputs, blocks_kinematics
"""
def __init__(
self,
value: str = "Run",
*,
variant: str = "secondary",
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value (str): Default value
variant (str): 'primary' for main call-to-action, 'secondary' for a more subdued style
visible (bool): If False, component will be hidden.
"""
Component.__init__(self, visible=visible, elem_id=elem_id, **kwargs)
self.value = value
self.variant = variant
def get_config(self):
return {
"value": self.value,
"variant": self.variant,
**Component.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
variant: Optional[str] = None,
visible: Optional[bool] = None,
):
return {
"variant": variant,
"visible": visible,
"value": value,
"__type__": "update",
}
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
full_width: Optional[str] = None,
border: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
margin: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
if full_width is not None:
self._style["full_width"] = full_width
if margin is not None:
self._style["margin"] = margin
return IOComponent.style(
self,
rounded=rounded,
border=border,
)
class Dataset(Clickable, Component):
"""
Used to create a output widget for showing datasets. Used to render the examples
box in the interface.
"""
def __init__(
self,
*,
components: List[Component] | List[str],
samples: List[List[Any]],
headers: Optional[List[str]] = None,
type: str = "values",
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
components (List[Component]): Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances
samples (str): a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component
headers (List[str]): Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels
type (str): 'values' if clicking on a sample should pass the value of the sample, or "index" if it should pass the index of the sample
visible (bool): If False, component will be hidden.
"""
Component.__init__(self, visible=visible, elem_id=elem_id, **kwargs)
self.components = [get_component_instance(c, render=False) for c in components]
self.type = type
self.headers = headers or [c.label for c in self.components]
self.samples = samples
def get_config(self):
return {
"components": [component.get_block_name() for component in self.components],
"headers": self.headers,
"samples": self.samples,
"type": self.type,
**Component.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
visible: Optional[bool] = None,
):
return {
"visible": visible,
"value": value,
"__type__": "update",
}
def preprocess(self, x: Any) -> Any:
"""
Any preprocessing needed to be performed on function input.
"""
if self.type == "index":
return x
elif self.type == "values":
return self.samples[x]
def style(
self,
rounded: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
border: Optional[bool | Tuple[bool, bool, bool, bool]] = None,
):
return IOComponent.style(
self,
rounded=rounded,
border=border,
)
class Interpretation(Component):
"""
Used to create an interpretation widget for a component.
"""
def __init__(
self,
component: Component,
*,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
Component.__init__(self, visible=visible, elem_id=elem_id, **kwargs)
self.component = component
def get_config(self):
return {
"component": self.component.get_block_name(),
"component_props": self.component.get_config(),
}
@staticmethod
def update(
value: Optional[Any] = None,
visible: Optional[bool] = None,
):
return {
"visible": visible,
"value": value,
"__type__": "update",
}
def style(self):
return self
class StatusTracker(Component):
"""
Used to indicate status of a function call. Event listeners can bind to a StatusTracker with 'status=' keyword argument.
"""
def __init__(
self,
*,
cover_container: bool = False,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
cover_container (bool): If True, will expand to cover parent container while function pending.
"""
Component.__init__(self, visible=visible, elem_id=elem_id, **kwargs)
self.cover_container = cover_container
def get_config(self):
return {
"cover_container": self.cover_container,
**Component.get_config(self),
}
@staticmethod
def update(
value: Optional[Any] = None,
visible: Optional[bool] = None,
):
return {
"visible": visible,
"value": value,
"__type__": "update",
}
def component(cls_name: str) -> Component:
obj = component_or_layout_class(cls_name)()
return obj
def get_component_instance(comp: str | dict | Component, render=True) -> Component:
if isinstance(comp, str):
component_obj = component(comp)
if not (render):
component_obj.unrender()
return component_obj
elif isinstance(comp, dict):
name = comp.pop("name")
component_cls = component_or_layout_class(name)
component_obj = component_cls(**comp)
if not (render):
component_obj.unrender()
return component_obj
elif isinstance(comp, Component):
return comp
else:
raise ValueError(
f"Component must provided as a `str` or `dict` or `Component` but is {comp}"
)
DataFrame = Dataframe
Highlightedtext = HighlightedText
Checkboxgroup = CheckboxGroup
TimeSeries = Timeseries
|