Spaces:
Running
Running
File size: 111,021 Bytes
d129378 b68ab8a f4bfa4e 32efa22 d129378 b4c56a0 32efa22 b4c56a0 32efa22 b4c56a0 32efa22 b4c56a0 d129378 32efa22 b68ab8a f949063 d8bbec8 f949063 d38fe40 925914f f949063 f4bfa4e 15531e3 925914f f949063 f4bfa4e 925914f f4bfa4e 925914f f4bfa4e f949063 925914f 15531e3 f949063 15531e3 f949063 925914f f949063 15531e3 f949063 15531e3 d8bbec8 f4bfa4e f949063 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 32efa22 b68ab8a 32efa22 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a d129378 b68ab8a 32efa22 b68ab8a 32efa22 d129378 32efa22 d129378 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 3d0bb33 d0c1a11 3d0bb33 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 3d0bb33 d0c1a11 3d0bb33 32efa22 3d0bb33 32efa22 3d0bb33 32efa22 3d0bb33 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 3d0bb33 c315193 f949063 c315193 d129378 32efa22 d8bbec8 f949063 4348906 32efa22 b4c56a0 2290df0 c315193 f949063 d38fe40 51a3e6d f949063 e609162 51a3e6d f949063 6db2c97 e609162 6db2c97 e609162 f949063 d38fe40 f949063 e609162 51a3e6d d38fe40 51a3e6d ccdd80f 51a3e6d f949063 51a3e6d d38fe40 f949063 d38fe40 51a3e6d ccdd80f 51a3e6d 32efa22 925914f e609162 c315193 e609162 f949063 c315193 32efa22 c315193 e609162 32efa22 e838605 e609162 e838605 e609162 f949063 e838605 32efa22 e838605 c315193 32efa22 0e1ad49 32efa22 51a3e6d 0e1ad49 c315193 32efa22 aa2fa0a d8bbec8 32efa22 d129378 32efa22 d8bbec8 32efa22 d8bbec8 d129378 32efa22 d0c1a11 d129378 f949063 32efa22 f949063 32efa22 f949063 32efa22 f949063 32efa22 f949063 d0c1a11 51a3e6d d0c1a11 32efa22 925914f 51a3e6d d0c1a11 925914f 15531e3 d0c1a11 15531e3 32efa22 d0c1a11 f4bfa4e b68ab8a d8bbec8 32efa22 d8bbec8 32efa22 b68ab8a d0c1a11 b68ab8a d8bbec8 32efa22 b68ab8a d8bbec8 32efa22 d8bbec8 b68ab8a 32efa22 b68ab8a 32efa22 d8bbec8 32efa22 f4bfa4e 32efa22 f4bfa4e 32efa22 d0c1a11 d129378 32efa22 b68ab8a 32efa22 b68ab8a d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 d0c1a11 32efa22 b3176eb 32efa22 d8bbec8 32efa22 d8bbec8 32efa22 d38fe40 |
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 |
import streamlit as st
from huggingface_hub import HfApi
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import lru_cache
import time
import requests
from collections import Counter
import numpy as np
st.set_page_config(page_title="HF Contributions", layout="wide", initial_sidebar_state="expanded")
# ν₯μλ UI μ€νμΌλ§
st.markdown("""
<style>
/* μ¬μ΄λλ° μ€νμΌλ§ */
[data-testid="stSidebar"] {
min-width: 35vw !important;
max-width: 35vw !important;
background-color: #f8f9fa;
padding: 1rem;
border-right: 1px solid #e9ecef;
}
/* ν€λ μ€νμΌλ§ */
h1, h2, h3 {
color: #1e88e5;
font-weight: 700;
}
h1 {
font-size: 2.5rem;
margin-bottom: 1.5rem;
border-bottom: 2px solid #e0e0e0;
padding-bottom: 0.5rem;
}
h2 {
font-size: 1.8rem;
margin-top: 1.5rem;
}
h3 {
font-size: 1.4rem;
margin-top: 1rem;
}
/* μΉ΄λ μ€νμΌλ§ */
div[data-testid="stMetric"] {
background-color: #f1f8fe;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
margin-bottom: 1rem;
}
/* μ°¨νΈ μ»¨ν
μ΄λ μ€νμΌλ§ */
.chart-container {
background-color: white;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin: 1rem 0;
}
/* ν
μ΄λΈ μ€νμΌλ§ */
div[data-testid="stDataFrame"] {
background-color: white;
border-radius: 10px;
padding: 0.5rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
/* ν μ€νμΌλ§ */
button[data-baseweb="tab"] {
font-weight: 600;
}
/* μλΈν€λ λ°°κ²½ */
.subheader {
background-color: #f1f8fe;
padding: 0.5rem 1rem;
border-radius: 5px;
margin-bottom: 1rem;
}
/* μ 보 λ±μ§ */
.info-badge {
background-color: #e3f2fd;
color: #1976d2;
padding: 0.3rem 0.7rem;
border-radius: 20px;
display: inline-block;
font-weight: 500;
margin-right: 0.5rem;
}
/* νλ‘κ·Έλ μ€ λ° */
div[data-testid="stProgress"] {
height: 0.5rem !important;
}
/* λ²νΌ μ€νμΌλ§ */
.stButton button {
background-color: #1e88e5;
color: white;
border: none;
font-weight: 500;
}
/* κ²½κ³ /μ±κ³΅ λ©μμ§ κ°μ */
div[data-testid="stAlert"] {
border-radius: 10px;
margin: 1rem 0;
}
/* μΉ΄ν
κ³ λ¦¬ λΆμ μΉμ
*/
.category-section {
background-color: white;
border-radius: 10px;
padding: 1rem;
margin-bottom: 1.5rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
</style>
""", unsafe_allow_html=True)
api = HfApi()
# Cache for API responses
@lru_cache(maxsize=1000)
def cached_repo_info(repo_id, repo_type):
return api.repo_info(repo_id=repo_id, repo_type=repo_type)
@lru_cache(maxsize=1000)
def cached_list_commits(repo_id, repo_type):
return list(api.list_repo_commits(repo_id=repo_id, repo_type=repo_type))
@lru_cache(maxsize=100)
def cached_list_items(username, kind):
if kind == "model":
return list(api.list_models(author=username))
elif kind == "dataset":
return list(api.list_datasets(author=username))
elif kind == "space":
return list(api.list_spaces(author=username))
return []
# Rate limiting
class RateLimiter:
def __init__(self, calls_per_second=10):
self.calls_per_second = calls_per_second
self.last_call = 0
def wait(self):
current_time = time.time()
time_since_last_call = current_time - self.last_call
if time_since_last_call < (1.0 / self.calls_per_second):
time.sleep((1.0 / self.calls_per_second) - time_since_last_call)
self.last_call = time.time()
rate_limiter = RateLimiter()
# Function to fetch quick commit stats for a user (optimized for ranking)
@st.cache_data(ttl=3600) # Cache for 1 hour
def get_user_commit_stats(username):
"""Fetch basic commit statistics for a user"""
try:
total_commits = 0
items_count = {"model": 0, "dataset": 0, "space": 0}
for kind in ["model", "dataset", "space"]:
try:
items = cached_list_items(username, kind)
items_count[kind] = len(items)
# Sample a few repos to estimate commit activity
sample_size = min(5, len(items)) # Check up to 5 repos per type
if sample_size > 0:
sample_items = items[:sample_size]
for item in sample_items:
try:
rate_limiter.wait()
commits = cached_list_commits(item.id, kind)
total_commits += len(commits)
except:
pass
# Estimate total commits based on sample
if sample_size < len(items):
total_commits = int(total_commits * len(items) / sample_size)
except:
pass
# Calculate contribution score based on commits only
score = total_commits
return {
"username": username,
"models": items_count["model"],
"spaces": items_count["space"],
"datasets": items_count["dataset"],
"estimated_commits": total_commits,
"score": score
}
except Exception as e:
return {
"username": username,
"models": 0,
"spaces": 0,
"datasets": 0,
"estimated_commits": 0,
"score": 0
}
# Enhanced function to get trending accounts with commit-based ranking
@st.cache_data(ttl=3600) # Cache for 1 hour
def get_trending_accounts_with_commits(limit=100):
try:
# First, get top accounts by model/space count
spaces_response = requests.get("https://huggingface.co/api/spaces",
params={"limit": 10000},
timeout=30)
models_response = requests.get("https://huggingface.co/api/models",
params={"limit": 10000},
timeout=30)
# Process spaces data
top_space_owners = []
if spaces_response.status_code == 200:
spaces = spaces_response.json()
owner_counts_spaces = {}
for space in spaces:
if '/' in space.get('id', ''):
owner, _ = space.get('id', '').split('/', 1)
else:
owner = space.get('owner', '')
if owner != 'None':
owner_counts_spaces[owner] = owner_counts_spaces.get(owner, 0) + 1
top_space_owners = sorted(owner_counts_spaces.items(), key=lambda x: x[1], reverse=True)[:limit]
# Process models data
top_model_owners = []
if models_response.status_code == 200:
models = models_response.json()
owner_counts_models = {}
for model in models:
if '/' in model.get('id', ''):
owner, _ = model.get('id', '').split('/', 1)
else:
owner = model.get('owner', '')
if owner != 'None':
owner_counts_models[owner] = owner_counts_models.get(owner, 0) + 1
top_model_owners = sorted(owner_counts_models.items(), key=lambda x: x[1], reverse=True)[:limit]
# Get unique users from top 100 of both lists
unique_users = set()
for owner, _ in top_space_owners[:100]:
unique_users.add(owner)
for owner, _ in top_model_owners[:100]:
unique_users.add(owner)
# Create progress bar for fetching commit stats
progress_text = st.empty()
progress_bar = st.progress(0)
progress_text.text(f"Analyzing top contributors... (0/{len(unique_users)})")
# Fetch commit stats for all unique users
user_stats = []
with ThreadPoolExecutor(max_workers=5) as executor:
future_to_user = {executor.submit(get_user_commit_stats, user): user for user in unique_users}
completed = 0
for future in as_completed(future_to_user):
stats = future.result()
if stats["score"] > 0: # Only include users with some activity
user_stats.append(stats)
completed += 1
progress = completed / len(unique_users)
progress_bar.progress(progress)
progress_text.text(f"Analyzing top contributors... ({completed}/{len(unique_users)})")
# Clear progress indicators
progress_text.empty()
progress_bar.empty()
# Sort by score (combination of commits and repo counts)
user_stats.sort(key=lambda x: x["score"], reverse=True)
# Extract rankings
trending_authors = [stat["username"] for stat in user_stats[:limit]]
# Create detailed rankings for display
spaces_rank_data = [(stat["username"], stat["spaces"]) for stat in user_stats if stat["spaces"] > 0][:limit]
models_rank_data = [(stat["username"], stat["models"]) for stat in user_stats if stat["models"] > 0][:limit]
return trending_authors, spaces_rank_data, models_rank_data, user_stats[:limit]
except Exception as e:
st.error(f"Error fetching trending accounts: {str(e)}")
fallback_authors = ["ritvik77", "facebook", "google", "stabilityai", "Salesforce", "tiiuae", "bigscience"]
fallback_stats = [{"username": author, "models": 0, "spaces": 0, "datasets": 0, "estimated_commits": 0, "score": 0} for author in fallback_authors]
return fallback_authors, [(author, 0) for author in fallback_authors], [(author, 0) for author in fallback_authors], fallback_stats
# Function to fetch commits for a repository (optimized)
def fetch_commits_for_repo(repo_id, repo_type, username, selected_year):
try:
rate_limiter.wait()
# Skip private/gated repos upfront
repo_info = cached_repo_info(repo_id, repo_type)
if repo_info.private or (hasattr(repo_info, 'gated') and repo_info.gated):
return [], 0
# Get initial commit date
initial_commit_date = pd.to_datetime(repo_info.created_at).tz_localize(None).date()
commit_dates = []
commit_count = 0
# Add initial commit if it's from the selected year
if initial_commit_date.year == selected_year:
commit_dates.append(initial_commit_date)
commit_count += 1
# Get all commits
commits = cached_list_commits(repo_id, repo_type)
for commit in commits:
commit_date = pd.to_datetime(commit.created_at).tz_localize(None).date()
if commit_date.year == selected_year:
commit_dates.append(commit_date)
commit_count += 1
return commit_dates, commit_count
except Exception as e:
return [], 0
# Function to get commit events for a user (optimized)
def get_commit_events(username, kind=None, selected_year=None):
commit_dates = []
items_with_type = []
kinds = [kind] if kind else ["model", "dataset", "space"]
for k in kinds:
try:
items = cached_list_items(username, k)
items_with_type.extend((item, k) for item in items)
repo_ids = [item.id for item in items]
# Optimized parallel fetch with chunking
chunk_size = 5 # Process 5 repos at a time
for i in range(0, len(repo_ids), chunk_size):
chunk = repo_ids[i:i + chunk_size]
with ThreadPoolExecutor(max_workers=min(5, len(chunk))) as executor:
future_to_repo = {
executor.submit(fetch_commits_for_repo, repo_id, k, username, selected_year): repo_id
for repo_id in chunk
}
for future in as_completed(future_to_repo):
repo_commits, repo_count = future.result()
if repo_commits: # Only extend if we got commits
commit_dates.extend(repo_commits)
except Exception as e:
st.warning(f"Error fetching {k}s for {username}: {str(e)}")
# Create DataFrame with all commits
df = pd.DataFrame(commit_dates, columns=["date"])
if not df.empty:
df = df.drop_duplicates() # Remove any duplicate dates
return df, items_with_type
# Calendar heatmap function (optimized)
def make_calendar_heatmap(df, title, year):
if df.empty:
st.info(f"No {title.lower()} found for {year}.")
return
# Optimize DataFrame operations
df["count"] = 1
df = df.groupby("date", as_index=False).sum()
df["date"] = pd.to_datetime(df["date"])
# Create date range more efficiently
start = pd.Timestamp(f"{year}-01-01")
end = pd.Timestamp(f"{year}-12-31")
all_days = pd.date_range(start=start, end=end)
# Optimize DataFrame creation and merging
heatmap_data = pd.DataFrame({"date": all_days, "count": 0})
heatmap_data = heatmap_data.merge(df, on="date", how="left", suffixes=("", "_y"))
heatmap_data["count"] = heatmap_data["count_y"].fillna(0)
heatmap_data = heatmap_data.drop("count_y", axis=1)
# Calculate week and day of week more efficiently
heatmap_data["dow"] = heatmap_data["date"].dt.dayofweek
heatmap_data["week"] = (heatmap_data["date"] - start).dt.days // 7
# Create pivot table more efficiently
pivot = heatmap_data.pivot(index="dow", columns="week", values="count").fillna(0)
# Optimize month labels calculation
month_labels = pd.date_range(start, end, freq="MS").strftime("%b")
month_positions = pd.date_range(start, end, freq="MS").map(lambda x: (x - start).days // 7)
# Create custom colormap with specific boundaries
from matplotlib.colors import ListedColormap, BoundaryNorm
colors = ['#ebedf0', '#9be9a8', '#40c463', '#30a14e', '#216e39'] # GitHub-style green colors
bounds = [0, 1, 3, 11, 31, float('inf')] # Boundaries for color transitions
cmap = ListedColormap(colors)
norm = BoundaryNorm(bounds, cmap.N)
# Create plot more efficiently
fig, ax = plt.subplots(figsize=(12, 1.5))
# Convert pivot values to integers to ensure proper color mapping
pivot_int = pivot.astype(int)
# Create heatmap with explicit vmin and vmax
sns.heatmap(pivot_int, ax=ax, cmap=cmap, norm=norm, linewidths=0.5, linecolor="white",
square=True, cbar=False, yticklabels=["M", "T", "W", "T", "F", "S", "S"])
ax.set_title(f"{title}", fontsize=14, pad=10)
ax.set_xlabel("")
ax.set_ylabel("")
ax.set_xticks(month_positions)
ax.set_xticklabels(month_labels, fontsize=10)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=10)
# μκ°μ ν₯μμ μν figure μ€νμΌλ§
fig.tight_layout()
fig.patch.set_facecolor('#F8F9FA')
st.pyplot(fig)
# Function to create a fancy contribution radar chart
def create_contribution_radar(username, models_count, spaces_count, datasets_count, commits_count):
# Create radar chart for contribution metrics
categories = ['Models', 'Spaces', 'Datasets', 'Activity']
values = [models_count, spaces_count, datasets_count, commits_count]
# Normalize values for better visualization
max_vals = [100, 100, 50, 500] # Reasonable max values for each category
normalized = [min(v/m, 1.0) for v, m in zip(values, max_vals)]
# Create radar chart
angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False).tolist()
angles += angles[:1] # Close the loop
normalized += normalized[:1] # Close the loop
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'polar': True}, facecolor='#F8F9FA')
# Add background grid with improved styling
ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)
ax.set_thetagrids(np.degrees(angles[:-1]), categories, fontsize=12, fontweight='bold')
# 그리λ μ€νμΌλ§ κ°μ
ax.grid(color='#CCCCCC', linestyle='-', linewidth=0.5, alpha=0.7)
# Draw the chart with improved color scheme
ax.fill(angles, normalized, color='#4CAF50', alpha=0.25)
ax.plot(angles, normalized, color='#4CAF50', linewidth=3)
# Add value labels with improved styling
for i, val in enumerate(values):
angle = angles[i]
x = (normalized[i] + 0.1) * np.cos(angle)
y = (normalized[i] + 0.1) * np.sin(angle)
ax.text(angle, normalized[i] + 0.1, str(val),
ha='center', va='center', fontsize=12,
fontweight='bold', color='#1976D2')
# Add highlight circles
circles = [0.25, 0.5, 0.75, 1.0]
for circle in circles:
ax.plot(angles, [circle] * len(angles), color='gray', alpha=0.3, linewidth=0.5, linestyle='--')
ax.set_title(f"{username}'s Contribution Profile", fontsize=16, pad=20, fontweight='bold')
# λ°°κ²½ μ μμ κΈ°
ax.set_facecolor('#F8F9FA')
return fig
# Function to create contribution distribution pie chart
def create_contribution_pie(model_commits, dataset_commits, space_commits):
labels = ['Models', 'Datasets', 'Spaces']
sizes = [model_commits, dataset_commits, space_commits]
# Filter out zero values
filtered_labels = [label for label, size in zip(labels, sizes) if size > 0]
filtered_sizes = [size for size in sizes if size > 0]
if not filtered_sizes:
return None # No data to show
# Use a more attractive color scheme
colors = ['#FF9800', '#2196F3', '#4CAF50']
filtered_colors = [color for color, size in zip(colors, sizes) if size > 0]
fig, ax = plt.subplots(figsize=(7, 7), facecolor='#F8F9FA')
# Create exploded pie chart with improved styling
explode = [0.1] * len(filtered_sizes) # Explode all slices for better visualization
wedges, texts, autotexts = ax.pie(
filtered_sizes,
labels=None, # We'll add custom labels
colors=filtered_colors,
autopct='%1.1f%%',
startangle=90,
shadow=True,
explode=explode,
textprops={'fontsize': 14, 'weight': 'bold'},
wedgeprops={'edgecolor': 'white', 'linewidth': 2}
)
# Customize the percentage text
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontsize(12)
autotext.set_weight('bold')
# Add legend with custom styling
ax.legend(
wedges,
[f"{label} ({size})" for label, size in zip(filtered_labels, filtered_sizes)],
title="Contribution Types",
loc="center left",
bbox_to_anchor=(0.85, 0.5),
fontsize=12
)
ax.set_title('Distribution of Contributions by Type', fontsize=16, pad=20, fontweight='bold')
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle
return fig
# Function to create monthly activity chart
def create_monthly_activity(df, year):
if df.empty:
return None
# Aggregate by month
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['month_name'] = df['date'].dt.strftime('%b')
# Count by month and ensure all months are present
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
counts_by_month = df.groupby('month_name')['date'].count()
monthly_counts = pd.Series([counts_by_month.get(m, 0) for m in month_order], index=month_order)
# Create bar chart with improved styling
fig, ax = plt.subplots(figsize=(14, 6), facecolor='#F8F9FA')
# Create bars with gradient colors based on activity level
norm = plt.Normalize(0, monthly_counts.max() if monthly_counts.max() > 0 else 1)
colors = plt.cm.viridis(norm(monthly_counts.values))
bars = ax.bar(monthly_counts.index, monthly_counts.values, color=colors, width=0.7)
# Highlight the month with most activity
if monthly_counts.max() > 0:
max_idx = monthly_counts.argmax()
bars[max_idx].set_color('#FF5722')
bars[max_idx].set_edgecolor('black')
bars[max_idx].set_linewidth(1.5)
# Add labels and styling with enhanced design
ax.set_title(f'Monthly Activity in {year}', fontsize=18, pad=20, fontweight='bold')
ax.set_xlabel('Month', fontsize=14, labelpad=10)
ax.set_ylabel('Number of Contributions', fontsize=14, labelpad=10)
# Add value labels on top of bars with improved styling
for i, count in enumerate(monthly_counts.values):
if count > 0:
ax.text(i, count + 0.5, str(int(count)), ha='center', fontsize=12, fontweight='bold')
# Add grid for better readability with improved styling
ax.grid(axis='y', linestyle='--', alpha=0.7, color='#CCCCCC')
ax.set_axisbelow(True) # Grid lines behind bars
# Style the chart borders and background
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Adjust tick parameters for better look
ax.tick_params(axis='x', labelsize=12, pad=5)
ax.tick_params(axis='y', labelsize=12, pad=5)
plt.tight_layout()
return fig
# Function to render follower growth simulation
def simulate_follower_data(username, spaces_count, models_count, total_commits):
# Simulate follower growth based on contribution metrics
# This is just a simulation for visual purposes
import numpy as np
from datetime import timedelta
# Start with a base number of followers proportional to contribution metrics
base_followers = max(10, int((spaces_count * 2 + models_count * 3 + total_commits/10) / 6))
# Generate timestamps for the past year
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
dates = pd.date_range(start=start_date, end=end_date, freq='W') # Weekly data points
# Generate follower growth with some randomness
followers = []
current = base_followers / 2 # Start from half the base
for i in range(len(dates)):
growth_factor = 1 + (np.random.random() * 0.1) # Random growth between 0% and 10%
current = current * growth_factor
followers.append(int(current))
# Ensure end value matches our base_followers estimate
followers[-1] = base_followers
# Create the chart with improved styling
fig, ax = plt.subplots(figsize=(14, 6), facecolor='#F8F9FA')
# Create gradient line for better visualization
points = np.array([dates, followers]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
from matplotlib.collections import LineCollection
norm = plt.Normalize(0, len(segments))
lc = LineCollection(segments, cmap='viridis', norm=norm, linewidth=3, alpha=0.8)
lc.set_array(np.arange(len(segments)))
line = ax.add_collection(lc)
# Add markers
ax.scatter(dates, followers, s=50, color='#9C27B0', alpha=0.8, zorder=10)
# Add styling with enhanced design
ax.set_title(f"Estimated Follower Growth for {username}", fontsize=18, pad=20, fontweight='bold')
ax.set_xlabel("Date", fontsize=14, labelpad=10)
ax.set_ylabel("Followers", fontsize=14, labelpad=10)
# Format the axes limits
ax.set_xlim(dates.min(), dates.max())
ax.set_ylim(0, max(followers) * 1.1)
# Add grid for better readability with improved styling
ax.grid(True, linestyle='--', alpha=0.7, color='#CCCCCC')
ax.set_axisbelow(True) # Grid lines behind plot
# Style the chart borders and background
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Adjust tick parameters for better look
ax.tick_params(axis='x', labelsize=12, rotation=45)
ax.tick_params(axis='y', labelsize=12)
# Add annotations for start and end points
ax.annotate(f"Start: {followers[0]}",
xy=(dates[0], followers[0]),
xytext=(10, 10),
textcoords='offset points',
fontsize=12,
fontweight='bold',
color='#9C27B0',
bbox=dict(boxstyle="round,pad=0.3", fc="#F3E5F5", ec="#9C27B0", alpha=0.8))
ax.annotate(f"Current: {followers[-1]}",
xy=(dates[-1], followers[-1]),
xytext=(-10, 10),
textcoords='offset points',
fontsize=12,
fontweight='bold',
color='#9C27B0',
ha='right',
bbox=dict(boxstyle="round,pad=0.3", fc="#F3E5F5", ec="#9C27B0", alpha=0.8))
plt.tight_layout()
return fig
# Function to create ranking position visualization
def create_ranking_chart(username, overall_rank, spaces_rank, models_rank):
if not (overall_rank or spaces_rank or models_rank):
return None
# Create a horizontal bar chart for rankings with improved styling
fig, ax = plt.subplots(figsize=(12, 5), facecolor='#F8F9FA')
categories = []
positions = []
colors = []
rank_values = []
if overall_rank:
categories.append('Overall')
positions.append(101 - overall_rank) # Invert rank for visualization (higher is better)
colors.append('#673AB7')
rank_values.append(overall_rank)
if spaces_rank:
categories.append('Spaces')
positions.append(101 - spaces_rank)
colors.append('#2196F3')
rank_values.append(spaces_rank)
if models_rank:
categories.append('Models')
positions.append(101 - models_rank)
colors.append('#FF9800')
rank_values.append(models_rank)
# Create horizontal bars with enhanced styling
bars = ax.barh(categories, positions, color=colors, alpha=0.8, height=0.6,
edgecolor='white', linewidth=1.5)
# Add rank values as text with improved styling
for i, bar in enumerate(bars):
ax.text(bar.get_width() + 2, bar.get_y() + bar.get_height()/2,
f'Rank #{rank_values[i]}', va='center', fontsize=12,
fontweight='bold', color=colors[i])
# Set chart properties with enhanced styling
ax.set_xlim(0, 105)
ax.set_title(f"Ranking Positions for {username} (Top 100)", fontsize=18, pad=20, fontweight='bold')
ax.set_xlabel("Percentile (higher is better)", fontsize=14, labelpad=10)
# Add explanatory text
ax.text(50, -0.6, "β Lower rank (higher number) | Higher rank (lower number) β",
ha='center', va='center', fontsize=10, fontweight='bold', color='#666666')
# Add a vertical line at 90th percentile to highlight top 10 with improved styling
ax.axvline(x=90, color='#FF5252', linestyle='--', alpha=0.7, linewidth=2)
ax.text(92, len(categories)/2, 'Top 10', color='#D32F2F', fontsize=12,
rotation=90, va='center', fontweight='bold')
# Style the chart borders and background
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Adjust tick parameters for better look
ax.tick_params(axis='x', labelsize=12)
ax.tick_params(axis='y', labelsize=14, pad=5)
# Add grid for better readability
ax.grid(axis='x', linestyle='--', alpha=0.5, color='#CCCCCC')
ax.set_axisbelow(True) # Grid lines behind bars
# Invert x-axis to show ranking position more intuitively
ax.invert_xaxis()
plt.tight_layout()
return fig
# Fetch trending accounts with a loading spinner (do this once at the beginning)
with st.spinner("Loading and analyzing top contributors... This may take a few moments."):
trending_accounts, top_owners_spaces, top_owners_models, user_stats = get_trending_accounts_with_commits(limit=100)
# Sidebar
with st.sidebar:
st.markdown('<h1 style="text-align: center; color: #1E88E5;">π€ Contributor</h1>', unsafe_allow_html=True)
# Create tabs for rankings
tab1, tab2 = st.tabs([
"Top 100 Overall",
"Top Spaces & Models"
])
with tab1:
# Show combined trending accounts list with commit-based ranking
st.markdown('<div class="subheader"><h3>π₯ Top 100 Contributors by Commits</h3></div>', unsafe_allow_html=True)
st.markdown('<p style="font-size: 0.9rem; color: #666; margin-bottom: 10px;">Ranked by total commit count</p>', unsafe_allow_html=True)
# Create a data frame for the table
if user_stats:
# Create the overall ranking dataframe with trophies for top 3
overall_data = []
for idx, stat in enumerate(user_stats[:100]):
# Add trophy emojis for top 3
rank_display = ""
if idx == 0:
rank_display = "π " # Gold trophy for 1st place
elif idx == 1:
rank_display = "π " # Silver trophy for 2nd place
elif idx == 2:
rank_display = "π " # Bronze trophy for 3rd place
overall_data.append([
f"{rank_display}{stat['username']}",
str(stat['estimated_commits']),
str(stat['models']),
str(stat['spaces']),
str(stat['datasets'])
])
ranking_data_overall = pd.DataFrame(
overall_data,
columns=["Contributor", "Total Commits", "Models", "Spaces", "Datasets"]
)
ranking_data_overall.index = ranking_data_overall.index + 1 # Start index from 1 for ranking
st.dataframe(
ranking_data_overall,
height=900, # μ½ 30ν μ λ 보μ΄λλ‘ ν½μ
λ¨μ λμ΄ μ€μ
column_config={
"Contributor": st.column_config.TextColumn("Contributor"),
"Total Commits": st.column_config.TextColumn("Total Commits"),
"Models": st.column_config.TextColumn("Models"),
"Spaces": st.column_config.TextColumn("Spaces"),
"Datasets": st.column_config.TextColumn("Datasets")
},
use_container_width=True,
hide_index=False
)
with tab2:
# Show trending accounts by Spaces & Models
st.markdown('<div class="subheader"><h3>π Spaces Leaders</h3></div>', unsafe_allow_html=True)
# Create a data frame for the Spaces table with medals for top 3
if top_owners_spaces:
spaces_data = []
for idx, (owner, count) in enumerate(top_owners_spaces[:50]):
# Add medal emojis for top 3
rank_display = ""
if idx == 0:
rank_display = "π₯ " # Gold medal for 1st place
elif idx == 1:
rank_display = "π₯ " # Silver medal for 2nd place
elif idx == 2:
rank_display = "π₯ " # Bronze medal for 3rd place
spaces_data.append([f"{rank_display}{owner}", count])
ranking_data_spaces = pd.DataFrame(spaces_data, columns=["Contributor", "Spaces Count"])
ranking_data_spaces.index = ranking_data_spaces.index + 1 # Start index from 1 for ranking
st.dataframe(
ranking_data_spaces,
column_config={
"Contributor": st.column_config.TextColumn("Contributor"),
"Spaces Count": st.column_config.NumberColumn("Spaces Count", format="%d")
},
use_container_width=True,
hide_index=False
)
# Display the top Models accounts list with medals for top 3
st.markdown('<div class="subheader"><h3>π§ Models Leaders</h3></div>', unsafe_allow_html=True)
# Create a data frame for the Models table with medals for top 3
if top_owners_models:
models_data = []
for idx, (owner, count) in enumerate(top_owners_models[:50]):
# Add medal emojis for top 3
rank_display = ""
if idx == 0:
rank_display = "π₯ " # Gold medal for 1st place
elif idx == 1:
rank_display = "π₯ " # Silver medal for 2nd place
elif idx == 2:
rank_display = "π₯ " # Bronze medal for 3rd place
models_data.append([f"{rank_display}{owner}", count])
ranking_data_models = pd.DataFrame(models_data, columns=["Contributor", "Models Count"])
ranking_data_models.index = ranking_data_models.index + 1 # Start index from 1 for ranking
st.dataframe(
ranking_data_models,
column_config={
"Contributor": st.column_config.TextColumn("Contributor"),
"Models Count": st.column_config.NumberColumn("Models Count", format="%d")
},
use_container_width=True,
hide_index=False
)
# Add visual divider
st.markdown('<hr style="margin: 2rem 0; border-color: #e0e0e0;">', unsafe_allow_html=True)
# Display contributor selection with enhanced styling
st.markdown('<div class="subheader"><h3>Select Contributor</h3></div>', unsafe_allow_html=True)
selected_trending = st.selectbox(
"Choose from trending accounts",
options=trending_accounts[:100], # Limit to top 100
index=0 if trending_accounts else None,
key="trending_selectbox"
)
# Custom account input option with enhanced styling
st.markdown('<div style="text-align: center; margin: 15px 0; font-weight: bold;">- OR -</div>', unsafe_allow_html=True)
custom = st.text_input("Enter a username/organization:", placeholder="e.g. facebook, google...")
# Add visual divider
st.markdown('<hr style="margin: 1.5rem 0; border-color: #e0e0e0;">', unsafe_allow_html=True)
# Set username based on selection or custom input
if custom.strip():
username = custom.strip()
elif selected_trending:
username = selected_trending
else:
username = "facebook" # Default fallback
# Year selection with enhanced styling
st.markdown('<div class="subheader"><h3>ποΈ Time Period</h3></div>', unsafe_allow_html=True)
year_options = list(range(datetime.now().year, 2017, -1))
selected_year = st.selectbox("Select Year:", options=year_options)
# Additional options for customization with enhanced styling
st.markdown('<div class="subheader"><h3>βοΈ Display Options</h3></div>', unsafe_allow_html=True)
show_models = st.checkbox("Show Models", value=True)
show_datasets = st.checkbox("Show Datasets", value=True)
show_spaces = st.checkbox("Show Spaces", value=True)
# Main Content
st.markdown(f'<h1 style="text-align: center; color: #1E88E5; margin-bottom: 2rem;">π€ Hugging Face Contributions</h1>', unsafe_allow_html=True)
if username:
# Find user's stats in the pre-calculated data
user_stat = next((stat for stat in user_stats if stat["username"] == username), None)
# Create a header card with contributor info
header_col1, header_col2 = st.columns([1, 2])
with header_col1:
score_display = f"Score: {user_stat['score']:.1f}" if user_stat else "Score: N/A"
st.markdown(f'<div style="background-color: #E3F2FD; padding: 20px; border-radius: 10px; border-left: 5px solid #1E88E5;">'
f'<h2 style="color: #1E88E5;">π€ {username}</h2>'
f'<p style="font-size: 16px;">Analyzing contributions for {selected_year}</p>'
f'<p style="font-size: 14px; font-weight: bold;">{score_display}</p>'
f'<p><a href="https://huggingface.co/{username}" target="_blank" style="color: #1E88E5; font-weight: bold;">View Profile</a></p>'
f'</div>', unsafe_allow_html=True)
with header_col2:
# Add explanation about the app
st.markdown(f'<div style="background-color: #F3E5F5; padding: 20px; border-radius: 10px; border-left: 5px solid #9C27B0;">'
f'<h3 style="color: #9C27B0;">About This Analysis</h3>'
f'<p>This dashboard analyzes {username}\'s contributions to Hugging Face in {selected_year}, including models, datasets, and spaces.</p>'
f'<p style="font-style: italic; font-size: 12px;">* Rankings are based on contribution scores combining repos and commit activity.</p>'
f'</div>', unsafe_allow_html=True)
with st.spinner(f"Fetching detailed contribution data for {username}..."):
# Initialize variables for tracking
overall_rank = None
spaces_rank = None
models_rank = None
spaces_count = 0
models_count = 0
datasets_count = 0
# Display contributor rank if in top 100
if username in trending_accounts[:100]:
overall_rank = trending_accounts.index(username) + 1
# Create a prominent ranking display
st.markdown(f'<div style="background-color: #FFF8E1; padding: 20px; border-radius: 10px; border-left: 5px solid #FFC107; margin: 1rem 0;">'
f'<h2 style="color: #FFA000; text-align: center;">π Ranked #{overall_rank} in Top Contributors</h2>'
f'</div>', unsafe_allow_html=True)
# Find user in spaces ranking
for i, (owner, count) in enumerate(top_owners_spaces):
if owner == username:
spaces_rank = i+1
spaces_count = count
break
# Find user in models ranking
for i, (owner, count) in enumerate(top_owners_models):
if owner == username:
models_rank = i+1
models_count = count
break
# Display ranking visualization
rank_chart = create_ranking_chart(username, overall_rank, spaces_rank, models_rank)
if rank_chart:
st.pyplot(rank_chart)
# Create a dictionary to store commits by type
commits_by_type = {}
commit_counts_by_type = {}
# Determine which types to fetch based on checkboxes
types_to_fetch = []
if show_models:
types_to_fetch.append("model")
if show_datasets:
types_to_fetch.append("dataset")
if show_spaces:
types_to_fetch.append("space")
if not types_to_fetch:
st.warning("Please select at least one content type to display (Models, Datasets, or Spaces)")
st.stop()
# Create a progress container
progress_container = st.container()
progress_container.markdown('<h3 style="color: #1E88E5;">Fetching Repository Data...</h3>', unsafe_allow_html=True)
progress_bar = progress_container.progress(0)
# Fetch commits for each selected type
for type_index, kind in enumerate(types_to_fetch):
try:
items = cached_list_items(username, kind)
# Update counts for radar chart
if kind == "model":
models_count = len(items)
elif kind == "dataset":
datasets_count = len(items)
elif kind == "space":
spaces_count = len(items)
repo_ids = [item.id for item in items]
progress_container.info(f"Found {len(repo_ids)} {kind}s for {username}")
# Process repos in chunks
chunk_size = 5
total_commits = 0
all_commit_dates = []
for i in range(0, len(repo_ids), chunk_size):
chunk = repo_ids[i:i + chunk_size]
with ThreadPoolExecutor(max_workers=min(5, len(chunk))) as executor:
future_to_repo = {
executor.submit(fetch_commits_for_repo, repo_id, kind, username, selected_year): repo_id
for repo_id in chunk
}
for future in as_completed(future_to_repo):
repo_commits, repo_count = future.result()
if repo_commits:
all_commit_dates.extend(repo_commits)
total_commits += repo_count
# Update progress for all types
progress_per_type = 1.0 / len(types_to_fetch)
current_type_progress = min(1.0, (i + len(chunk)) / max(1, len(repo_ids)))
overall_progress = (type_index * progress_per_type) + (current_type_progress * progress_per_type)
progress_bar.progress(overall_progress)
commits_by_type[kind] = all_commit_dates
commit_counts_by_type[kind] = total_commits
except Exception as e:
st.warning(f"Error fetching {kind}s for {username}: {str(e)}")
commits_by_type[kind] = []
commit_counts_by_type[kind] = 0
# Complete progress
progress_bar.progress(1.0)
progress_container.success("Data fetching complete!")
time.sleep(0.5) # Short pause for visual feedback
progress_container.empty() # Clear the progress indicators
# Calculate total commits across all types
total_commits = sum(commit_counts_by_type.values())
# Main dashboard layout with improved structure
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Activity Overview</h2>', unsafe_allow_html=True)
# Profile summary
profile_col1, profile_col2 = st.columns([1, 2])
with profile_col1:
# Create a stats card with key metrics
st.markdown(f'<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">'
f'<h3 style="color: #1E88E5; text-align: center; margin-bottom: 15px;">Contribution Stats</h3>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Total Commits:</span><span>{total_commits}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Models:</span><span>{models_count}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Datasets:</span><span>{datasets_count}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Spaces:</span><span>{spaces_count}</span></div>'
f'</div>', unsafe_allow_html=True)
# Type breakdown pie chart
model_commits = commit_counts_by_type.get("model", 0)
dataset_commits = commit_counts_by_type.get("dataset", 0)
space_commits = commit_counts_by_type.get("space", 0)
pie_chart = create_contribution_pie(model_commits, dataset_commits, space_commits)
if pie_chart:
st.pyplot(pie_chart)
with profile_col2:
# Display contribution radar chart
radar_fig = create_contribution_radar(username, models_count, spaces_count, datasets_count, total_commits)
st.pyplot(radar_fig)
# Create DataFrame for all commits
all_commits = []
for commits in commits_by_type.values():
all_commits.extend(commits)
all_df = pd.DataFrame(all_commits, columns=["date"])
if not all_df.empty:
all_df = all_df.drop_duplicates() # Remove any duplicate dates
# Calendar heatmap for all commits in a separate section
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Contribution Calendar</h2>', unsafe_allow_html=True)
if not all_df.empty:
make_calendar_heatmap(all_df, "All Contributions", selected_year)
else:
st.info(f"No contributions found for {username} in {selected_year}")
# Monthly activity chart
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Monthly Activity</h2>', unsafe_allow_html=True)
monthly_fig = create_monthly_activity(all_df, selected_year)
if monthly_fig:
st.pyplot(monthly_fig)
else:
st.info(f"No activity data available for {username} in {selected_year}")
# Follower growth simulation
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Growth Projection</h2>', unsafe_allow_html=True)
st.markdown('<div style="background-color: #EDE7F6; padding: 10px; border-radius: 5px; margin-bottom: 15px;">'
'<p style="font-style: italic; margin: 0;">π This is a simulation based on contribution metrics - for visualization purposes only</p>'
'</div>', unsafe_allow_html=True)
follower_chart = simulate_follower_data(username, spaces_count, models_count, total_commits)
st.pyplot(follower_chart)
# Analytics summary section
if total_commits > 0:
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">π Analytics Summary</h2>', unsafe_allow_html=True)
# Contribution pattern analysis
monthly_df = pd.DataFrame(all_commits, columns=["date"])
monthly_df['date'] = pd.to_datetime(monthly_df['date'])
monthly_df['month'] = monthly_df['date'].dt.month
if not monthly_df.empty:
most_active_month = monthly_df['month'].value_counts().idxmax()
month_name = datetime(2020, most_active_month, 1).strftime('%B')
# Create a summary card
st.markdown(f'<div style="background-color: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">'
f'<h3 style="color: #1E88E5; border-bottom: 1px solid #E0E0E0; padding-bottom: 10px;">Activity Analysis for {username}</h3>'
f'<ul style="list-style-type: none; padding-left: 5px;">'
f'<li style="margin: 15px 0; font-size: 16px;">π <strong>Total Activity:</strong> {total_commits} contributions in {selected_year}</li>'
f'<li style="margin: 15px 0; font-size: 16px;">ποΈ <strong>Most Active Month:</strong> {month_name} with {monthly_df["month"].value_counts().max()} contributions</li>'
f'<li style="margin: 15px 0; font-size: 16px;">π§© <strong>Repository Breakdown:</strong> {models_count} Models, {spaces_count} Spaces, {datasets_count} Datasets</li>'
f'</ul>', unsafe_allow_html=True)
# Add ranking context if available
if overall_rank:
percentile = 100 - overall_rank
st.markdown(f'<div style="margin-top: 20px;">'
f'<h3 style="color: #1E88E5; border-bottom: 1px solid #E0E0E0; padding-bottom: 10px;">Ranking Analysis</h3>'
f'<ul style="list-style-type: none; padding-left: 5px;">'
f'<li style="margin: 15px 0; font-size: 16px;">π <strong>Overall Ranking:</strong> #{overall_rank} (Top {percentile}% of contributors)</li>', unsafe_allow_html=True)
badge_html = '<div style="margin: 20px 0;">'
if spaces_rank and spaces_rank <= 10:
badge_html += f'<span style="background-color: #FFECB3; color: #FF6F00; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">π Elite Spaces Contributor (#{spaces_rank})</span>'
elif spaces_rank and spaces_rank <= 30:
badge_html += f'<span style="background-color: #E1F5FE; color: #0277BD; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">β¨ Outstanding Spaces Contributor (#{spaces_rank})</span>'
if models_rank and models_rank <= 10:
badge_html += f'<span style="background-color: #FFECB3; color: #FF6F00; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">π Elite Models Contributor (#{models_rank})</span>'
elif models_rank and models_rank <= 30:
badge_html += f'<span style="background-color: #E1F5FE; color: #0277BD; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">β¨ Outstanding Models Contributor (#{models_rank})</span>'
badge_html += '</div>'
# Add achievement badges
if spaces_rank or models_rank:
st.markdown(badge_html, unsafe_allow_html=True)
st.markdown('</ul></div></div>', unsafe_allow_html=True)
# Detailed category analysis section
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Detailed Category Analysis</h2>', unsafe_allow_html=True)
# Create category cards in columns
cols = st.columns(len(types_to_fetch)) if types_to_fetch else st.columns(1)
category_icons = {
"model": "π§ ",
"dataset": "π¦",
"space": "π"
}
category_colors = {
"model": "#FF9800",
"dataset": "#2196F3",
"space": "#4CAF50"
}
for i, kind in enumerate(types_to_fetch):
with cols[i]:
try:
emoji = category_icons.get(kind, "π")
label = kind.capitalize() + "s"
color = category_colors.get(kind, "#1E88E5")
total = len(cached_list_items(username, kind))
commits = commits_by_type.get(kind, [])
commit_count = commit_counts_by_type.get(kind, 0)
# Create styled card header
st.markdown(f'<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-top: 5px solid {color};">'
f'<h3 style="color: {color}; text-align: center;">{emoji} {label}</h3>'
f'<div style="display: flex; justify-content: space-between; margin: 15px 0;">'
f'<span style="font-weight: bold;">Total:</span><span>{total}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 15px;">'
f'<span style="font-weight: bold;">Commits:</span><span>{commit_count}</span></div>'
f'</div>', unsafe_allow_html=True)
# Create calendar for this type
df_kind = pd.DataFrame(commits, columns=["date"])
if not df_kind.empty:
df_kind = df_kind.drop_duplicates() # Remove any duplicate dates
make_calendar_heatmap(df_kind, f"{label} Commits", selected_year)
else:
st.info(f"No {label.lower()} activity in {selected_year}")
except Exception as e:
st.warning(f"Error processing {kind.capitalize()}s: {str(e)}")
# Show empty placeholder
st.markdown(f'<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-top: 5px solid #9E9E9E; text-align: center;">'
f'<h3 style="color: #9E9E9E;">β οΈ Error</h3>'
f'<p>Could not load {kind.capitalize()}s data</p>'
f'</div>', unsafe_allow_html=True)
# Footer
st.markdown('<hr style="margin: 3rem 0 1rem 0;">', unsafe_allow_html=True)
st.markdown('<p style="text-align: center; color: #9E9E9E; font-size: 0.8rem;">Hugging Face Contributions Dashboard | Data fetched from Hugging Face API</p>', unsafe_allow_html=True)
else:
# If no username is selected, show welcome screen
st.markdown(f'<div style="text-align: center; margin: 50px 0;">'
f'<img src="https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.svg" style="width: 200px; margin-bottom: 30px;">'
f'<h2>Welcome to Hugging Face Contributions Dashboard</h2>'
f'<p style="font-size: 1.2rem;">Please select a contributor from the sidebar to view their activity.</p>'
f'</div>', unsafe_allow_html=True)import streamlit as st
from huggingface_hub import HfApi
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import lru_cache
import time
import requests
from collections import Counter
import numpy as np
st.set_page_config(page_title="HF Contributions", layout="wide", initial_sidebar_state="expanded")
# ν₯μλ UI μ€νμΌλ§
st.markdown("""
<style>
/* μ¬μ΄λλ° μ€νμΌλ§ */
[data-testid="stSidebar"] {
min-width: 35vw !important;
max-width: 35vw !important;
background-color: #f8f9fa;
padding: 1rem;
border-right: 1px solid #e9ecef;
}
/* ν€λ μ€νμΌλ§ */
h1, h2, h3 {
color: #1e88e5;
font-weight: 700;
}
h1 {
font-size: 2.5rem;
margin-bottom: 1.5rem;
border-bottom: 2px solid #e0e0e0;
padding-bottom: 0.5rem;
}
h2 {
font-size: 1.8rem;
margin-top: 1.5rem;
}
h3 {
font-size: 1.4rem;
margin-top: 1rem;
}
/* μΉ΄λ μ€νμΌλ§ */
div[data-testid="stMetric"] {
background-color: #f1f8fe;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
margin-bottom: 1rem;
}
/* μ°¨νΈ μ»¨ν
μ΄λ μ€νμΌλ§ */
.chart-container {
background-color: white;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin: 1rem 0;
}
/* ν
μ΄λΈ μ€νμΌλ§ */
div[data-testid="stDataFrame"] {
background-color: white;
border-radius: 10px;
padding: 0.5rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
/* ν μ€νμΌλ§ */
button[data-baseweb="tab"] {
font-weight: 600;
}
/* μλΈν€λ λ°°κ²½ */
.subheader {
background-color: #f1f8fe;
padding: 0.5rem 1rem;
border-radius: 5px;
margin-bottom: 1rem;
}
/* μ 보 λ±μ§ */
.info-badge {
background-color: #e3f2fd;
color: #1976d2;
padding: 0.3rem 0.7rem;
border-radius: 20px;
display: inline-block;
font-weight: 500;
margin-right: 0.5rem;
}
/* νλ‘κ·Έλ μ€ λ° */
div[data-testid="stProgress"] {
height: 0.5rem !important;
}
/* λ²νΌ μ€νμΌλ§ */
.stButton button {
background-color: #1e88e5;
color: white;
border: none;
font-weight: 500;
}
/* κ²½κ³ /μ±κ³΅ λ©μμ§ κ°μ */
div[data-testid="stAlert"] {
border-radius: 10px;
margin: 1rem 0;
}
/* μΉ΄ν
κ³ λ¦¬ λΆμ μΉμ
*/
.category-section {
background-color: white;
border-radius: 10px;
padding: 1rem;
margin-bottom: 1.5rem;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
</style>
""", unsafe_allow_html=True)
api = HfApi()
# Cache for API responses
@lru_cache(maxsize=1000)
def cached_repo_info(repo_id, repo_type):
return api.repo_info(repo_id=repo_id, repo_type=repo_type)
@lru_cache(maxsize=1000)
def cached_list_commits(repo_id, repo_type):
return list(api.list_repo_commits(repo_id=repo_id, repo_type=repo_type))
@lru_cache(maxsize=100)
def cached_list_items(username, kind):
if kind == "model":
return list(api.list_models(author=username))
elif kind == "dataset":
return list(api.list_datasets(author=username))
elif kind == "space":
return list(api.list_spaces(author=username))
return []
# Rate limiting
class RateLimiter:
def __init__(self, calls_per_second=10):
self.calls_per_second = calls_per_second
self.last_call = 0
def wait(self):
current_time = time.time()
time_since_last_call = current_time - self.last_call
if time_since_last_call < (1.0 / self.calls_per_second):
time.sleep((1.0 / self.calls_per_second) - time_since_last_call)
self.last_call = time.time()
rate_limiter = RateLimiter()
# Function to fetch quick commit stats for a user (optimized for ranking)
@st.cache_data(ttl=3600) # Cache for 1 hour
def get_user_commit_stats(username):
"""Fetch basic commit statistics for a user"""
try:
total_commits = 0
items_count = {"model": 0, "dataset": 0, "space": 0}
for kind in ["model", "dataset", "space"]:
try:
items = cached_list_items(username, kind)
items_count[kind] = len(items)
# Sample a few repos to estimate commit activity
sample_size = min(5, len(items)) # Check up to 5 repos per type
if sample_size > 0:
sample_items = items[:sample_size]
for item in sample_items:
try:
rate_limiter.wait()
commits = cached_list_commits(item.id, kind)
total_commits += len(commits)
except:
pass
# Estimate total commits based on sample
if sample_size < len(items):
total_commits = int(total_commits * len(items) / sample_size)
except:
pass
# Calculate contribution score based on commits only
score = total_commits
return {
"username": username,
"models": items_count["model"],
"spaces": items_count["space"],
"datasets": items_count["dataset"],
"estimated_commits": total_commits,
"score": score
}
except Exception as e:
return {
"username": username,
"models": 0,
"spaces": 0,
"datasets": 0,
"estimated_commits": 0,
"score": 0
}
# Enhanced function to get trending accounts with commit-based ranking
@st.cache_data(ttl=3600) # Cache for 1 hour
def get_trending_accounts_with_commits(limit=100):
try:
# First, get top accounts by model/space count
spaces_response = requests.get("https://huggingface.co/api/spaces",
params={"limit": 10000},
timeout=30)
models_response = requests.get("https://huggingface.co/api/models",
params={"limit": 10000},
timeout=30)
# Process spaces data
top_space_owners = []
if spaces_response.status_code == 200:
spaces = spaces_response.json()
owner_counts_spaces = {}
for space in spaces:
if '/' in space.get('id', ''):
owner, _ = space.get('id', '').split('/', 1)
else:
owner = space.get('owner', '')
if owner != 'None':
owner_counts_spaces[owner] = owner_counts_spaces.get(owner, 0) + 1
top_space_owners = sorted(owner_counts_spaces.items(), key=lambda x: x[1], reverse=True)[:limit]
# Process models data
top_model_owners = []
if models_response.status_code == 200:
models = models_response.json()
owner_counts_models = {}
for model in models:
if '/' in model.get('id', ''):
owner, _ = model.get('id', '').split('/', 1)
else:
owner = model.get('owner', '')
if owner != 'None':
owner_counts_models[owner] = owner_counts_models.get(owner, 0) + 1
top_model_owners = sorted(owner_counts_models.items(), key=lambda x: x[1], reverse=True)[:limit]
# Get unique users from top 100 of both lists
unique_users = set()
for owner, _ in top_space_owners[:100]:
unique_users.add(owner)
for owner, _ in top_model_owners[:100]:
unique_users.add(owner)
# Create progress bar for fetching commit stats
progress_text = st.empty()
progress_bar = st.progress(0)
progress_text.text(f"Analyzing top contributors... (0/{len(unique_users)})")
# Fetch commit stats for all unique users
user_stats = []
with ThreadPoolExecutor(max_workers=5) as executor:
future_to_user = {executor.submit(get_user_commit_stats, user): user for user in unique_users}
completed = 0
for future in as_completed(future_to_user):
stats = future.result()
if stats["score"] > 0: # Only include users with some activity
user_stats.append(stats)
completed += 1
progress = completed / len(unique_users)
progress_bar.progress(progress)
progress_text.text(f"Analyzing top contributors... ({completed}/{len(unique_users)})")
# Clear progress indicators
progress_text.empty()
progress_bar.empty()
# Sort by score (combination of commits and repo counts)
user_stats.sort(key=lambda x: x["score"], reverse=True)
# Extract rankings
trending_authors = [stat["username"] for stat in user_stats[:limit]]
# Create detailed rankings for display
spaces_rank_data = [(stat["username"], stat["spaces"]) for stat in user_stats if stat["spaces"] > 0][:limit]
models_rank_data = [(stat["username"], stat["models"]) for stat in user_stats if stat["models"] > 0][:limit]
return trending_authors, spaces_rank_data, models_rank_data, user_stats[:limit]
except Exception as e:
st.error(f"Error fetching trending accounts: {str(e)}")
fallback_authors = ["ritvik77", "facebook", "google", "stabilityai", "Salesforce", "tiiuae", "bigscience"]
fallback_stats = [{"username": author, "models": 0, "spaces": 0, "datasets": 0, "estimated_commits": 0, "score": 0} for author in fallback_authors]
return fallback_authors, [(author, 0) for author in fallback_authors], [(author, 0) for author in fallback_authors], fallback_stats
# Function to fetch commits for a repository (optimized)
def fetch_commits_for_repo(repo_id, repo_type, username, selected_year):
try:
rate_limiter.wait()
# Skip private/gated repos upfront
repo_info = cached_repo_info(repo_id, repo_type)
if repo_info.private or (hasattr(repo_info, 'gated') and repo_info.gated):
return [], 0
# Get initial commit date
initial_commit_date = pd.to_datetime(repo_info.created_at).tz_localize(None).date()
commit_dates = []
commit_count = 0
# Add initial commit if it's from the selected year
if initial_commit_date.year == selected_year:
commit_dates.append(initial_commit_date)
commit_count += 1
# Get all commits
commits = cached_list_commits(repo_id, repo_type)
for commit in commits:
commit_date = pd.to_datetime(commit.created_at).tz_localize(None).date()
if commit_date.year == selected_year:
commit_dates.append(commit_date)
commit_count += 1
return commit_dates, commit_count
except Exception as e:
return [], 0
# Function to get commit events for a user (optimized)
def get_commit_events(username, kind=None, selected_year=None):
commit_dates = []
items_with_type = []
kinds = [kind] if kind else ["model", "dataset", "space"]
for k in kinds:
try:
items = cached_list_items(username, k)
items_with_type.extend((item, k) for item in items)
repo_ids = [item.id for item in items]
# Optimized parallel fetch with chunking
chunk_size = 5 # Process 5 repos at a time
for i in range(0, len(repo_ids), chunk_size):
chunk = repo_ids[i:i + chunk_size]
with ThreadPoolExecutor(max_workers=min(5, len(chunk))) as executor:
future_to_repo = {
executor.submit(fetch_commits_for_repo, repo_id, k, username, selected_year): repo_id
for repo_id in chunk
}
for future in as_completed(future_to_repo):
repo_commits, repo_count = future.result()
if repo_commits: # Only extend if we got commits
commit_dates.extend(repo_commits)
except Exception as e:
st.warning(f"Error fetching {k}s for {username}: {str(e)}")
# Create DataFrame with all commits
df = pd.DataFrame(commit_dates, columns=["date"])
if not df.empty:
df = df.drop_duplicates() # Remove any duplicate dates
return df, items_with_type
# Calendar heatmap function (optimized)
def make_calendar_heatmap(df, title, year):
if df.empty:
st.info(f"No {title.lower()} found for {year}.")
return
# Optimize DataFrame operations
df["count"] = 1
df = df.groupby("date", as_index=False).sum()
df["date"] = pd.to_datetime(df["date"])
# Create date range more efficiently
start = pd.Timestamp(f"{year}-01-01")
end = pd.Timestamp(f"{year}-12-31")
all_days = pd.date_range(start=start, end=end)
# Optimize DataFrame creation and merging
heatmap_data = pd.DataFrame({"date": all_days, "count": 0})
heatmap_data = heatmap_data.merge(df, on="date", how="left", suffixes=("", "_y"))
heatmap_data["count"] = heatmap_data["count_y"].fillna(0)
heatmap_data = heatmap_data.drop("count_y", axis=1)
# Calculate week and day of week more efficiently
heatmap_data["dow"] = heatmap_data["date"].dt.dayofweek
heatmap_data["week"] = (heatmap_data["date"] - start).dt.days // 7
# Create pivot table more efficiently
pivot = heatmap_data.pivot(index="dow", columns="week", values="count").fillna(0)
# Optimize month labels calculation
month_labels = pd.date_range(start, end, freq="MS").strftime("%b")
month_positions = pd.date_range(start, end, freq="MS").map(lambda x: (x - start).days // 7)
# Create custom colormap with specific boundaries
from matplotlib.colors import ListedColormap, BoundaryNorm
colors = ['#ebedf0', '#9be9a8', '#40c463', '#30a14e', '#216e39'] # GitHub-style green colors
bounds = [0, 1, 3, 11, 31, float('inf')] # Boundaries for color transitions
cmap = ListedColormap(colors)
norm = BoundaryNorm(bounds, cmap.N)
# Create plot more efficiently
fig, ax = plt.subplots(figsize=(12, 1.5))
# Convert pivot values to integers to ensure proper color mapping
pivot_int = pivot.astype(int)
# Create heatmap with explicit vmin and vmax
sns.heatmap(pivot_int, ax=ax, cmap=cmap, norm=norm, linewidths=0.5, linecolor="white",
square=True, cbar=False, yticklabels=["M", "T", "W", "T", "F", "S", "S"])
ax.set_title(f"{title}", fontsize=14, pad=10)
ax.set_xlabel("")
ax.set_ylabel("")
ax.set_xticks(month_positions)
ax.set_xticklabels(month_labels, fontsize=10)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=10)
# μκ°μ ν₯μμ μν figure μ€νμΌλ§
fig.tight_layout()
fig.patch.set_facecolor('#F8F9FA')
st.pyplot(fig)
# Function to create a fancy contribution radar chart
def create_contribution_radar(username, models_count, spaces_count, datasets_count, commits_count):
# Create radar chart for contribution metrics
categories = ['Models', 'Spaces', 'Datasets', 'Activity']
values = [models_count, spaces_count, datasets_count, commits_count]
# Normalize values for better visualization
max_vals = [100, 100, 50, 500] # Reasonable max values for each category
normalized = [min(v/m, 1.0) for v, m in zip(values, max_vals)]
# Create radar chart
angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False).tolist()
angles += angles[:1] # Close the loop
normalized += normalized[:1] # Close the loop
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'polar': True}, facecolor='#F8F9FA')
# Add background grid with improved styling
ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)
ax.set_thetagrids(np.degrees(angles[:-1]), categories, fontsize=12, fontweight='bold')
# 그리λ μ€νμΌλ§ κ°μ
ax.grid(color='#CCCCCC', linestyle='-', linewidth=0.5, alpha=0.7)
# Draw the chart with improved color scheme
ax.fill(angles, normalized, color='#4CAF50', alpha=0.25)
ax.plot(angles, normalized, color='#4CAF50', linewidth=3)
# Add value labels with improved styling
for i, val in enumerate(values):
angle = angles[i]
x = (normalized[i] + 0.1) * np.cos(angle)
y = (normalized[i] + 0.1) * np.sin(angle)
ax.text(angle, normalized[i] + 0.1, str(val),
ha='center', va='center', fontsize=12,
fontweight='bold', color='#1976D2')
# Add highlight circles
circles = [0.25, 0.5, 0.75, 1.0]
for circle in circles:
ax.plot(angles, [circle] * len(angles), color='gray', alpha=0.3, linewidth=0.5, linestyle='--')
ax.set_title(f"{username}'s Contribution Profile", fontsize=16, pad=20, fontweight='bold')
# λ°°κ²½ μ μμ κΈ°
ax.set_facecolor('#F8F9FA')
return fig
# Function to create contribution distribution pie chart
def create_contribution_pie(model_commits, dataset_commits, space_commits):
labels = ['Models', 'Datasets', 'Spaces']
sizes = [model_commits, dataset_commits, space_commits]
# Filter out zero values
filtered_labels = [label for label, size in zip(labels, sizes) if size > 0]
filtered_sizes = [size for size in sizes if size > 0]
if not filtered_sizes:
return None # No data to show
# Use a more attractive color scheme
colors = ['#FF9800', '#2196F3', '#4CAF50']
filtered_colors = [color for color, size in zip(colors, sizes) if size > 0]
fig, ax = plt.subplots(figsize=(7, 7), facecolor='#F8F9FA')
# Create exploded pie chart with improved styling
explode = [0.1] * len(filtered_sizes) # Explode all slices for better visualization
wedges, texts, autotexts = ax.pie(
filtered_sizes,
labels=None, # We'll add custom labels
colors=filtered_colors,
autopct='%1.1f%%',
startangle=90,
shadow=True,
explode=explode,
textprops={'fontsize': 14, 'weight': 'bold'},
wedgeprops={'edgecolor': 'white', 'linewidth': 2}
)
# Customize the percentage text
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontsize(12)
autotext.set_weight('bold')
# Add legend with custom styling
ax.legend(
wedges,
[f"{label} ({size})" for label, size in zip(filtered_labels, filtered_sizes)],
title="Contribution Types",
loc="center left",
bbox_to_anchor=(0.85, 0.5),
fontsize=12
)
ax.set_title('Distribution of Contributions by Type', fontsize=16, pad=20, fontweight='bold')
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle
return fig
# Function to create monthly activity chart
def create_monthly_activity(df, year):
if df.empty:
return None
# Aggregate by month
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['month_name'] = df['date'].dt.strftime('%b')
# Count by month and ensure all months are present
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
counts_by_month = df.groupby('month_name')['date'].count()
monthly_counts = pd.Series([counts_by_month.get(m, 0) for m in month_order], index=month_order)
# Create bar chart with improved styling
fig, ax = plt.subplots(figsize=(14, 6), facecolor='#F8F9FA')
# Create bars with gradient colors based on activity level
norm = plt.Normalize(0, monthly_counts.max() if monthly_counts.max() > 0 else 1)
colors = plt.cm.viridis(norm(monthly_counts.values))
bars = ax.bar(monthly_counts.index, monthly_counts.values, color=colors, width=0.7)
# Highlight the month with most activity
if monthly_counts.max() > 0:
max_idx = monthly_counts.argmax()
bars[max_idx].set_color('#FF5722')
bars[max_idx].set_edgecolor('black')
bars[max_idx].set_linewidth(1.5)
# Add labels and styling with enhanced design
ax.set_title(f'Monthly Activity in {year}', fontsize=18, pad=20, fontweight='bold')
ax.set_xlabel('Month', fontsize=14, labelpad=10)
ax.set_ylabel('Number of Contributions', fontsize=14, labelpad=10)
# Add value labels on top of bars with improved styling
for i, count in enumerate(monthly_counts.values):
if count > 0:
ax.text(i, count + 0.5, str(int(count)), ha='center', fontsize=12, fontweight='bold')
# Add grid for better readability with improved styling
ax.grid(axis='y', linestyle='--', alpha=0.7, color='#CCCCCC')
ax.set_axisbelow(True) # Grid lines behind bars
# Style the chart borders and background
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Adjust tick parameters for better look
ax.tick_params(axis='x', labelsize=12, pad=5)
ax.tick_params(axis='y', labelsize=12, pad=5)
plt.tight_layout()
return fig
# Function to render follower growth simulation
def simulate_follower_data(username, spaces_count, models_count, total_commits):
# Simulate follower growth based on contribution metrics
# This is just a simulation for visual purposes
import numpy as np
from datetime import timedelta
# Start with a base number of followers proportional to contribution metrics
base_followers = max(10, int((spaces_count * 2 + models_count * 3 + total_commits/10) / 6))
# Generate timestamps for the past year
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
dates = pd.date_range(start=start_date, end=end_date, freq='W') # Weekly data points
# Generate follower growth with some randomness
followers = []
current = base_followers / 2 # Start from half the base
for i in range(len(dates)):
growth_factor = 1 + (np.random.random() * 0.1) # Random growth between 0% and 10%
current = current * growth_factor
followers.append(int(current))
# Ensure end value matches our base_followers estimate
followers[-1] = base_followers
# Create the chart with improved styling
fig, ax = plt.subplots(figsize=(14, 6), facecolor='#F8F9FA')
# Create gradient line for better visualization
points = np.array([dates, followers]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
from matplotlib.collections import LineCollection
norm = plt.Normalize(0, len(segments))
lc = LineCollection(segments, cmap='viridis', norm=norm, linewidth=3, alpha=0.8)
lc.set_array(np.arange(len(segments)))
line = ax.add_collection(lc)
# Add markers
ax.scatter(dates, followers, s=50, color='#9C27B0', alpha=0.8, zorder=10)
# Add styling with enhanced design
ax.set_title(f"Estimated Follower Growth for {username}", fontsize=18, pad=20, fontweight='bold')
ax.set_xlabel("Date", fontsize=14, labelpad=10)
ax.set_ylabel("Followers", fontsize=14, labelpad=10)
# Format the axes limits
ax.set_xlim(dates.min(), dates.max())
ax.set_ylim(0, max(followers) * 1.1)
# Add grid for better readability with improved styling
ax.grid(True, linestyle='--', alpha=0.7, color='#CCCCCC')
ax.set_axisbelow(True) # Grid lines behind plot
# Style the chart borders and background
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Adjust tick parameters for better look
ax.tick_params(axis='x', labelsize=12, rotation=45)
ax.tick_params(axis='y', labelsize=12)
# Add annotations for start and end points
ax.annotate(f"Start: {followers[0]}",
xy=(dates[0], followers[0]),
xytext=(10, 10),
textcoords='offset points',
fontsize=12,
fontweight='bold',
color='#9C27B0',
bbox=dict(boxstyle="round,pad=0.3", fc="#F3E5F5", ec="#9C27B0", alpha=0.8))
ax.annotate(f"Current: {followers[-1]}",
xy=(dates[-1], followers[-1]),
xytext=(-10, 10),
textcoords='offset points',
fontsize=12,
fontweight='bold',
color='#9C27B0',
ha='right',
bbox=dict(boxstyle="round,pad=0.3", fc="#F3E5F5", ec="#9C27B0", alpha=0.8))
plt.tight_layout()
return fig
# Function to create ranking position visualization
def create_ranking_chart(username, overall_rank, spaces_rank, models_rank):
if not (overall_rank or spaces_rank or models_rank):
return None
# Create a horizontal bar chart for rankings with improved styling
fig, ax = plt.subplots(figsize=(12, 5), facecolor='#F8F9FA')
categories = []
positions = []
colors = []
rank_values = []
if overall_rank:
categories.append('Overall')
positions.append(101 - overall_rank) # Invert rank for visualization (higher is better)
colors.append('#673AB7')
rank_values.append(overall_rank)
if spaces_rank:
categories.append('Spaces')
positions.append(101 - spaces_rank)
colors.append('#2196F3')
rank_values.append(spaces_rank)
if models_rank:
categories.append('Models')
positions.append(101 - models_rank)
colors.append('#FF9800')
rank_values.append(models_rank)
# Create horizontal bars with enhanced styling
bars = ax.barh(categories, positions, color=colors, alpha=0.8, height=0.6,
edgecolor='white', linewidth=1.5)
# Add rank values as text with improved styling
for i, bar in enumerate(bars):
ax.text(bar.get_width() + 2, bar.get_y() + bar.get_height()/2,
f'Rank #{rank_values[i]}', va='center', fontsize=12,
fontweight='bold', color=colors[i])
# Set chart properties with enhanced styling
ax.set_xlim(0, 105)
ax.set_title(f"Ranking Positions for {username} (Top 100)", fontsize=18, pad=20, fontweight='bold')
ax.set_xlabel("Percentile (higher is better)", fontsize=14, labelpad=10)
# Add explanatory text
ax.text(50, -0.6, "β Lower rank (higher number) | Higher rank (lower number) β",
ha='center', va='center', fontsize=10, fontweight='bold', color='#666666')
# Add a vertical line at 90th percentile to highlight top 10 with improved styling
ax.axvline(x=90, color='#FF5252', linestyle='--', alpha=0.7, linewidth=2)
ax.text(92, len(categories)/2, 'Top 10', color='#D32F2F', fontsize=12,
rotation=90, va='center', fontweight='bold')
# Style the chart borders and background
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_linewidth(0.5)
ax.spines['bottom'].set_linewidth(0.5)
# Adjust tick parameters for better look
ax.tick_params(axis='x', labelsize=12)
ax.tick_params(axis='y', labelsize=14, pad=5)
# Add grid for better readability
ax.grid(axis='x', linestyle='--', alpha=0.5, color='#CCCCCC')
ax.set_axisbelow(True) # Grid lines behind bars
# Invert x-axis to show ranking position more intuitively
ax.invert_xaxis()
plt.tight_layout()
return fig
# Fetch trending accounts with a loading spinner (do this once at the beginning)
with st.spinner("Loading and analyzing top contributors... This may take a few moments."):
trending_accounts, top_owners_spaces, top_owners_models, user_stats = get_trending_accounts_with_commits(limit=100)
# Sidebar
with st.sidebar:
st.markdown('<h1 style="text-align: center; color: #1E88E5;">π€ Contributor</h1>', unsafe_allow_html=True)
# Create tabs for rankings
tab1, tab2 = st.tabs([
"Top 100 Overall",
"Top Spaces & Models"
])
with tab1:
# Show combined trending accounts list with commit-based ranking
st.markdown('<div class="subheader"><h3>π₯ Top 100 Contributors by Commits</h3></div>', unsafe_allow_html=True)
st.markdown('<p style="font-size: 0.9rem; color: #666; margin-bottom: 10px;">Ranked by total commit count</p>', unsafe_allow_html=True)
# Create a data frame for the table
if user_stats:
# Create the overall ranking dataframe with trophies for top 3
overall_data = []
for idx, stat in enumerate(user_stats[:100]):
# Add trophy emojis for top 3
rank_display = ""
if idx == 0:
rank_display = "π " # Gold trophy for 1st place
elif idx == 1:
rank_display = "π " # Silver trophy for 2nd place
elif idx == 2:
rank_display = "π " # Bronze trophy for 3rd place
overall_data.append([
f"{rank_display}{stat['username']}",
str(stat['estimated_commits']),
str(stat['models']),
str(stat['spaces']),
str(stat['datasets'])
])
ranking_data_overall = pd.DataFrame(
overall_data,
columns=["Contributor", "Total Commits", "Models", "Spaces", "Datasets"]
)
ranking_data_overall.index = ranking_data_overall.index + 1 # Start index from 1 for ranking
st.dataframe(
ranking_data_overall,
height=900, # μ½ 30ν μ λ 보μ΄λλ‘ ν½μ
λ¨μ λμ΄ μ€μ
column_config={
"Contributor": st.column_config.TextColumn("Contributor"),
"Total Commits": st.column_config.TextColumn("Total Commits"),
"Models": st.column_config.TextColumn("Models"),
"Spaces": st.column_config.TextColumn("Spaces"),
"Datasets": st.column_config.TextColumn("Datasets")
},
use_container_width=True,
hide_index=False
)
with tab2:
# Show trending accounts by Spaces & Models
st.markdown('<div class="subheader"><h3>π Spaces Leaders</h3></div>', unsafe_allow_html=True)
# Create a data frame for the Spaces table with medals for top 3
if top_owners_spaces:
spaces_data = []
for idx, (owner, count) in enumerate(top_owners_spaces[:50]):
# Add medal emojis for top 3
rank_display = ""
if idx == 0:
rank_display = "π₯ " # Gold medal for 1st place
elif idx == 1:
rank_display = "π₯ " # Silver medal for 2nd place
elif idx == 2:
rank_display = "π₯ " # Bronze medal for 3rd place
spaces_data.append([f"{rank_display}{owner}", count])
ranking_data_spaces = pd.DataFrame(spaces_data, columns=["Contributor", "Spaces Count"])
ranking_data_spaces.index = ranking_data_spaces.index + 1 # Start index from 1 for ranking
st.dataframe(
ranking_data_spaces,
column_config={
"Contributor": st.column_config.TextColumn("Contributor"),
"Spaces Count": st.column_config.NumberColumn("Spaces Count", format="%d")
},
use_container_width=True,
hide_index=False
)
# Display the top Models accounts list with medals for top 3
st.markdown('<div class="subheader"><h3>π§ Models Leaders</h3></div>', unsafe_allow_html=True)
# Create a data frame for the Models table with medals for top 3
if top_owners_models:
models_data = []
for idx, (owner, count) in enumerate(top_owners_models[:50]):
# Add medal emojis for top 3
rank_display = ""
if idx == 0:
rank_display = "π₯ " # Gold medal for 1st place
elif idx == 1:
rank_display = "π₯ " # Silver medal for 2nd place
elif idx == 2:
rank_display = "π₯ " # Bronze medal for 3rd place
models_data.append([f"{rank_display}{owner}", count])
ranking_data_models = pd.DataFrame(models_data, columns=["Contributor", "Models Count"])
ranking_data_models.index = ranking_data_models.index + 1 # Start index from 1 for ranking
st.dataframe(
ranking_data_models,
column_config={
"Contributor": st.column_config.TextColumn("Contributor"),
"Models Count": st.column_config.NumberColumn("Models Count", format="%d")
},
use_container_width=True,
hide_index=False
)
# Add visual divider
st.markdown('<hr style="margin: 2rem 0; border-color: #e0e0e0;">', unsafe_allow_html=True)
# Display contributor selection with enhanced styling
st.markdown('<div class="subheader"><h3>Select Contributor</h3></div>', unsafe_allow_html=True)
selected_trending = st.selectbox(
"Choose from trending accounts",
options=trending_accounts[:100], # Limit to top 100
index=0 if trending_accounts else None,
key="trending_selectbox"
)
# Custom account input option with enhanced styling
st.markdown('<div style="text-align: center; margin: 15px 0; font-weight: bold;">- OR -</div>', unsafe_allow_html=True)
custom = st.text_input("Enter a username/organization:", placeholder="e.g. facebook, google...")
# Add visual divider
st.markdown('<hr style="margin: 1.5rem 0; border-color: #e0e0e0;">', unsafe_allow_html=True)
# Set username based on selection or custom input
if custom.strip():
username = custom.strip()
elif selected_trending:
username = selected_trending
else:
username = "facebook" # Default fallback
# Year selection with enhanced styling
st.markdown('<div class="subheader"><h3>ποΈ Time Period</h3></div>', unsafe_allow_html=True)
year_options = list(range(datetime.now().year, 2017, -1))
selected_year = st.selectbox("Select Year:", options=year_options)
# Additional options for customization with enhanced styling
st.markdown('<div class="subheader"><h3>βοΈ Display Options</h3></div>', unsafe_allow_html=True)
show_models = st.checkbox("Show Models", value=True)
show_datasets = st.checkbox("Show Datasets", value=True)
show_spaces = st.checkbox("Show Spaces", value=True)
# Main Content
st.markdown(f'<h1 style="text-align: center; color: #1E88E5; margin-bottom: 2rem;">π€ Hugging Face Contributions</h1>', unsafe_allow_html=True)
if username:
# Find user's stats in the pre-calculated data
user_stat = next((stat for stat in user_stats if stat["username"] == username), None)
# Create a header card with contributor info
header_col1, header_col2 = st.columns([1, 2])
with header_col1:
score_display = f"Score: {user_stat['score']:.1f}" if user_stat else "Score: N/A"
st.markdown(f'<div style="background-color: #E3F2FD; padding: 20px; border-radius: 10px; border-left: 5px solid #1E88E5;">'
f'<h2 style="color: #1E88E5;">π€ {username}</h2>'
f'<p style="font-size: 16px;">Analyzing contributions for {selected_year}</p>'
f'<p style="font-size: 14px; font-weight: bold;">{score_display}</p>'
f'<p><a href="https://huggingface.co/{username}" target="_blank" style="color: #1E88E5; font-weight: bold;">View Profile</a></p>'
f'</div>', unsafe_allow_html=True)
with header_col2:
# Add explanation about the app
st.markdown(f'<div style="background-color: #F3E5F5; padding: 20px; border-radius: 10px; border-left: 5px solid #9C27B0;">'
f'<h3 style="color: #9C27B0;">About This Analysis</h3>'
f'<p>This dashboard analyzes {username}\'s contributions to Hugging Face in {selected_year}, including models, datasets, and spaces.</p>'
f'<p style="font-style: italic; font-size: 12px;">* Rankings are based on contribution scores combining repos and commit activity.</p>'
f'</div>', unsafe_allow_html=True)
with st.spinner(f"Fetching detailed contribution data for {username}..."):
# Initialize variables for tracking
overall_rank = None
spaces_rank = None
models_rank = None
spaces_count = 0
models_count = 0
datasets_count = 0
# Display contributor rank if in top 100
if username in trending_accounts[:100]:
overall_rank = trending_accounts.index(username) + 1
# Create a prominent ranking display
st.markdown(f'<div style="background-color: #FFF8E1; padding: 20px; border-radius: 10px; border-left: 5px solid #FFC107; margin: 1rem 0;">'
f'<h2 style="color: #FFA000; text-align: center;">π Ranked #{overall_rank} in Top Contributors</h2>'
f'</div>', unsafe_allow_html=True)
# Find user in spaces ranking
for i, (owner, count) in enumerate(top_owners_spaces):
if owner == username:
spaces_rank = i+1
spaces_count = count
break
# Find user in models ranking
for i, (owner, count) in enumerate(top_owners_models):
if owner == username:
models_rank = i+1
models_count = count
break
# Display ranking visualization
rank_chart = create_ranking_chart(username, overall_rank, spaces_rank, models_rank)
if rank_chart:
st.pyplot(rank_chart)
# Create a dictionary to store commits by type
commits_by_type = {}
commit_counts_by_type = {}
# Determine which types to fetch based on checkboxes
types_to_fetch = []
if show_models:
types_to_fetch.append("model")
if show_datasets:
types_to_fetch.append("dataset")
if show_spaces:
types_to_fetch.append("space")
if not types_to_fetch:
st.warning("Please select at least one content type to display (Models, Datasets, or Spaces)")
st.stop()
# Create a progress container
progress_container = st.container()
progress_container.markdown('<h3 style="color: #1E88E5;">Fetching Repository Data...</h3>', unsafe_allow_html=True)
progress_bar = progress_container.progress(0)
# Fetch commits for each selected type
for type_index, kind in enumerate(types_to_fetch):
try:
items = cached_list_items(username, kind)
# Update counts for radar chart
if kind == "model":
models_count = len(items)
elif kind == "dataset":
datasets_count = len(items)
elif kind == "space":
spaces_count = len(items)
repo_ids = [item.id for item in items]
progress_container.info(f"Found {len(repo_ids)} {kind}s for {username}")
# Process repos in chunks
chunk_size = 5
total_commits = 0
all_commit_dates = []
for i in range(0, len(repo_ids), chunk_size):
chunk = repo_ids[i:i + chunk_size]
with ThreadPoolExecutor(max_workers=min(5, len(chunk))) as executor:
future_to_repo = {
executor.submit(fetch_commits_for_repo, repo_id, kind, username, selected_year): repo_id
for repo_id in chunk
}
for future in as_completed(future_to_repo):
repo_commits, repo_count = future.result()
if repo_commits:
all_commit_dates.extend(repo_commits)
total_commits += repo_count
# Update progress for all types
progress_per_type = 1.0 / len(types_to_fetch)
current_type_progress = min(1.0, (i + len(chunk)) / max(1, len(repo_ids)))
overall_progress = (type_index * progress_per_type) + (current_type_progress * progress_per_type)
progress_bar.progress(overall_progress)
commits_by_type[kind] = all_commit_dates
commit_counts_by_type[kind] = total_commits
except Exception as e:
st.warning(f"Error fetching {kind}s for {username}: {str(e)}")
commits_by_type[kind] = []
commit_counts_by_type[kind] = 0
# Complete progress
progress_bar.progress(1.0)
progress_container.success("Data fetching complete!")
time.sleep(0.5) # Short pause for visual feedback
progress_container.empty() # Clear the progress indicators
# Calculate total commits across all types
total_commits = sum(commit_counts_by_type.values())
# Main dashboard layout with improved structure
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Activity Overview</h2>', unsafe_allow_html=True)
# Profile summary
profile_col1, profile_col2 = st.columns([1, 2])
with profile_col1:
# Create a stats card with key metrics
st.markdown(f'<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">'
f'<h3 style="color: #1E88E5; text-align: center; margin-bottom: 15px;">Contribution Stats</h3>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Total Commits:</span><span>{total_commits}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Models:</span><span>{models_count}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Datasets:</span><span>{datasets_count}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">'
f'<span style="font-weight: bold;">Spaces:</span><span>{spaces_count}</span></div>'
f'</div>', unsafe_allow_html=True)
# Type breakdown pie chart
model_commits = commit_counts_by_type.get("model", 0)
dataset_commits = commit_counts_by_type.get("dataset", 0)
space_commits = commit_counts_by_type.get("space", 0)
pie_chart = create_contribution_pie(model_commits, dataset_commits, space_commits)
if pie_chart:
st.pyplot(pie_chart)
with profile_col2:
# Display contribution radar chart
radar_fig = create_contribution_radar(username, models_count, spaces_count, datasets_count, total_commits)
st.pyplot(radar_fig)
# Create DataFrame for all commits
all_commits = []
for commits in commits_by_type.values():
all_commits.extend(commits)
all_df = pd.DataFrame(all_commits, columns=["date"])
if not all_df.empty:
all_df = all_df.drop_duplicates() # Remove any duplicate dates
# Calendar heatmap for all commits in a separate section
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Contribution Calendar</h2>', unsafe_allow_html=True)
if not all_df.empty:
make_calendar_heatmap(all_df, "All Contributions", selected_year)
else:
st.info(f"No contributions found for {username} in {selected_year}")
# Monthly activity chart
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Monthly Activity</h2>', unsafe_allow_html=True)
monthly_fig = create_monthly_activity(all_df, selected_year)
if monthly_fig:
st.pyplot(monthly_fig)
else:
st.info(f"No activity data available for {username} in {selected_year}")
# Follower growth simulation
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Growth Projection</h2>', unsafe_allow_html=True)
st.markdown('<div style="background-color: #EDE7F6; padding: 10px; border-radius: 5px; margin-bottom: 15px;">'
'<p style="font-style: italic; margin: 0;">π This is a simulation based on contribution metrics - for visualization purposes only</p>'
'</div>', unsafe_allow_html=True)
follower_chart = simulate_follower_data(username, spaces_count, models_count, total_commits)
st.pyplot(follower_chart)
# Analytics summary section
if total_commits > 0:
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">π Analytics Summary</h2>', unsafe_allow_html=True)
# Contribution pattern analysis
monthly_df = pd.DataFrame(all_commits, columns=["date"])
monthly_df['date'] = pd.to_datetime(monthly_df['date'])
monthly_df['month'] = monthly_df['date'].dt.month
if not monthly_df.empty:
most_active_month = monthly_df['month'].value_counts().idxmax()
month_name = datetime(2020, most_active_month, 1).strftime('%B')
# Create a summary card
st.markdown(f'<div style="background-color: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">'
f'<h3 style="color: #1E88E5; border-bottom: 1px solid #E0E0E0; padding-bottom: 10px;">Activity Analysis for {username}</h3>'
f'<ul style="list-style-type: none; padding-left: 5px;">'
f'<li style="margin: 15px 0; font-size: 16px;">π <strong>Total Activity:</strong> {total_commits} contributions in {selected_year}</li>'
f'<li style="margin: 15px 0; font-size: 16px;">ποΈ <strong>Most Active Month:</strong> {month_name} with {monthly_df["month"].value_counts().max()} contributions</li>'
f'<li style="margin: 15px 0; font-size: 16px;">π§© <strong>Repository Breakdown:</strong> {models_count} Models, {spaces_count} Spaces, {datasets_count} Datasets</li>'
f'</ul>', unsafe_allow_html=True)
# Add ranking context if available
if overall_rank:
percentile = 100 - overall_rank
st.markdown(f'<div style="margin-top: 20px;">'
f'<h3 style="color: #1E88E5; border-bottom: 1px solid #E0E0E0; padding-bottom: 10px;">Ranking Analysis</h3>'
f'<ul style="list-style-type: none; padding-left: 5px;">'
f'<li style="margin: 15px 0; font-size: 16px;">π <strong>Overall Ranking:</strong> #{overall_rank} (Top {percentile}% of contributors)</li>', unsafe_allow_html=True)
badge_html = '<div style="margin: 20px 0;">'
if spaces_rank and spaces_rank <= 10:
badge_html += f'<span style="background-color: #FFECB3; color: #FF6F00; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">π Elite Spaces Contributor (#{spaces_rank})</span>'
elif spaces_rank and spaces_rank <= 30:
badge_html += f'<span style="background-color: #E1F5FE; color: #0277BD; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">β¨ Outstanding Spaces Contributor (#{spaces_rank})</span>'
if models_rank and models_rank <= 10:
badge_html += f'<span style="background-color: #FFECB3; color: #FF6F00; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">π Elite Models Contributor (#{models_rank})</span>'
elif models_rank and models_rank <= 30:
badge_html += f'<span style="background-color: #E1F5FE; color: #0277BD; padding: 8px 15px; border-radius: 20px; font-weight: bold; margin-right: 10px; display: inline-block; margin-bottom: 10px;">β¨ Outstanding Models Contributor (#{models_rank})</span>'
badge_html += '</div>'
# Add achievement badges
if spaces_rank or models_rank:
st.markdown(badge_html, unsafe_allow_html=True)
st.markdown('</ul></div></div>', unsafe_allow_html=True)
# Detailed category analysis section
st.markdown(f'<h2 style="color: #1E88E5; border-bottom: 2px solid #E0E0E0; padding-bottom: 8px; margin-top: 2rem;">Detailed Category Analysis</h2>', unsafe_allow_html=True)
# Create category cards in columns
cols = st.columns(len(types_to_fetch)) if types_to_fetch else st.columns(1)
category_icons = {
"model": "π§ ",
"dataset": "π¦",
"space": "π"
}
category_colors = {
"model": "#FF9800",
"dataset": "#2196F3",
"space": "#4CAF50"
}
for i, kind in enumerate(types_to_fetch):
with cols[i]:
try:
emoji = category_icons.get(kind, "π")
label = kind.capitalize() + "s"
color = category_colors.get(kind, "#1E88E5")
total = len(cached_list_items(username, kind))
commits = commits_by_type.get(kind, [])
commit_count = commit_counts_by_type.get(kind, 0)
# Create styled card header
st.markdown(f'<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-top: 5px solid {color};">'
f'<h3 style="color: {color}; text-align: center;">{emoji} {label}</h3>'
f'<div style="display: flex; justify-content: space-between; margin: 15px 0;">'
f'<span style="font-weight: bold;">Total:</span><span>{total}</span></div>'
f'<div style="display: flex; justify-content: space-between; margin-bottom: 15px;">'
f'<span style="font-weight: bold;">Commits:</span><span>{commit_count}</span></div>'
f'</div>', unsafe_allow_html=True)
# Create calendar for this type
df_kind = pd.DataFrame(commits, columns=["date"])
if not df_kind.empty:
df_kind = df_kind.drop_duplicates() # Remove any duplicate dates
make_calendar_heatmap(df_kind, f"{label} Commits", selected_year)
else:
st.info(f"No {label.lower()} activity in {selected_year}")
except Exception as e:
st.warning(f"Error processing {kind.capitalize()}s: {str(e)}")
# Show empty placeholder
st.markdown(f'<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-top: 5px solid #9E9E9E; text-align: center;">'
f'<h3 style="color: #9E9E9E;">β οΈ Error</h3>'
f'<p>Could not load {kind.capitalize()}s data</p>'
f'</div>', unsafe_allow_html=True)
# Footer
st.markdown('<hr style="margin: 3rem 0 1rem 0;">', unsafe_allow_html=True)
st.markdown('<p style="text-align: center; color: #9E9E9E; font-size: 0.8rem;">Hugging Face Contributions Dashboard | Data fetched from Hugging Face API</p>', unsafe_allow_html=True)
else:
# If no username is selected, show welcome screen
st.markdown(f'<div style="text-align: center; margin: 50px 0;">'
f'<img src="https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.svg" style="width: 200px; margin-bottom: 30px;">'
f'<h2>Welcome to Hugging Face Contributions Dashboard</h2>'
f'<p style="font-size: 1.2rem;">Please select a contributor from the sidebar to view their activity.</p>'
f'</div>', unsafe_allow_html=True) |