File size: 356,971 Bytes
fac0856 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 | # coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import inspect
import json
import re
import struct
import warnings
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import datetime
from functools import wraps
from itertools import islice
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
Union,
overload,
)
from urllib.parse import quote, urlencode
import requests
from requests.exceptions import HTTPError
from tqdm.auto import tqdm as base_tqdm
from tqdm.contrib.concurrent import thread_map
from ._commit_api import (
CommitOperation,
CommitOperationAdd,
CommitOperationCopy,
CommitOperationDelete,
_fetch_lfs_files_to_copy,
_fetch_upload_modes,
_prepare_commit_payload,
_upload_lfs_files,
_warn_on_overwriting_operations,
)
from ._inference_endpoints import InferenceEndpoint, InferenceEndpointType
from ._multi_commits import (
MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE,
MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE,
MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE,
MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE,
MultiCommitException,
MultiCommitStep,
MultiCommitStrategy,
multi_commit_create_pull_request,
multi_commit_generate_comment,
multi_commit_parse_pr_description,
plan_multi_commits,
)
from ._space_api import SpaceHardware, SpaceRuntime, SpaceStorage, SpaceVariable
from .community import (
Discussion,
DiscussionComment,
DiscussionStatusChange,
DiscussionTitleChange,
DiscussionWithDetails,
deserialize_event,
)
from .constants import (
DEFAULT_ETAG_TIMEOUT,
DEFAULT_REQUEST_TIMEOUT,
DEFAULT_REVISION,
DISCUSSION_STATUS,
DISCUSSION_TYPES,
ENDPOINT,
INFERENCE_ENDPOINTS_ENDPOINT,
REGEX_COMMIT_OID,
REPO_TYPE_MODEL,
REPO_TYPES,
REPO_TYPES_MAPPING,
REPO_TYPES_URL_PREFIXES,
SAFETENSORS_INDEX_FILE,
SAFETENSORS_MAX_HEADER_LENGTH,
SAFETENSORS_SINGLE_FILE,
SPACES_SDK_TYPES,
DiscussionStatusFilter,
DiscussionTypeFilter,
)
from .file_download import HfFileMetadata, get_hf_file_metadata, hf_hub_url
from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData
from .utils import ( # noqa: F401 # imported for backward compatibility
IGNORE_GIT_FOLDER_PATTERNS,
BadRequestError,
EntryNotFoundError,
GatedRepoError,
HfFolder,
HfHubHTTPError,
LocalTokenNotFoundError,
NotASafetensorsRepoError,
RepositoryNotFoundError,
RevisionNotFoundError,
SafetensorsFileMetadata,
SafetensorsParsingError,
SafetensorsRepoMetadata,
TensorInfo,
build_hf_headers,
experimental,
filter_repo_objects,
get_session,
hf_raise_for_status,
logging,
paginate,
parse_datetime,
validate_hf_hub_args,
)
from .utils import tqdm as hf_tqdm
from .utils._deprecation import _deprecate_method
from .utils._typing import CallableT
from .utils.endpoint_helpers import (
DatasetFilter,
ModelFilter,
_is_emission_within_treshold,
)
R = TypeVar("R") # Return type
CollectionItemType_T = Literal["model", "dataset", "space", "paper"]
USERNAME_PLACEHOLDER = "hf_user"
_REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$")
_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = (
"\nNote: Creating a commit assumes that the repo already exists on the"
" Huggingface Hub. Please use `create_repo` if it's not the case."
)
logger = logging.get_logger(__name__)
def repo_type_and_id_from_hf_id(hf_id: str, hub_url: Optional[str] = None) -> Tuple[Optional[str], Optional[str], str]:
"""
Returns the repo type and ID from a huggingface.co URL linking to a
repository
Args:
hf_id (`str`):
An URL or ID of a repository on the HF hub. Accepted values are:
- https://huggingface.co/<repo_type>/<namespace>/<repo_id>
- https://huggingface.co/<namespace>/<repo_id>
- hf://<repo_type>/<namespace>/<repo_id>
- hf://<namespace>/<repo_id>
- <repo_type>/<namespace>/<repo_id>
- <namespace>/<repo_id>
- <repo_id>
hub_url (`str`, *optional*):
The URL of the HuggingFace Hub, defaults to https://huggingface.co
Returns:
A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
`None`) and repo_id (`str`).
Raises:
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If URL cannot be parsed.
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `repo_type` is unknown.
"""
input_hf_id = hf_id
hub_url = re.sub(r"https?://", "", hub_url if hub_url is not None else ENDPOINT)
is_hf_url = hub_url in hf_id and "@" not in hf_id
HFFS_PREFIX = "hf://"
if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists
hf_id = hf_id[len(HFFS_PREFIX) :]
url_segments = hf_id.split("/")
is_hf_id = len(url_segments) <= 3
namespace: Optional[str]
if is_hf_url:
namespace, repo_id = url_segments[-2:]
if namespace == hub_url:
namespace = None
if len(url_segments) > 2 and hub_url not in url_segments[-3]:
repo_type = url_segments[-3]
elif namespace in REPO_TYPES_MAPPING:
# Mean canonical dataset or model
repo_type = REPO_TYPES_MAPPING[namespace]
namespace = None
else:
repo_type = None
elif is_hf_id:
if len(url_segments) == 3:
# Passed <repo_type>/<user>/<model_id> or <repo_type>/<org>/<model_id>
repo_type, namespace, repo_id = url_segments[-3:]
elif len(url_segments) == 2:
if url_segments[0] in REPO_TYPES_MAPPING:
# Passed '<model_id>' or 'datasets/<dataset_id>' for a canonical model or dataset
repo_type = REPO_TYPES_MAPPING[url_segments[0]]
namespace = None
repo_id = hf_id.split("/")[-1]
else:
# Passed <user>/<model_id> or <org>/<model_id>
namespace, repo_id = hf_id.split("/")[-2:]
repo_type = None
else:
# Passed <model_id>
repo_id = url_segments[0]
namespace, repo_type = None, None
else:
raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}")
# Check if repo type is known (mapping "spaces" => "space" + empty value => `None`)
if repo_type in REPO_TYPES_MAPPING:
repo_type = REPO_TYPES_MAPPING[repo_type]
if repo_type == "":
repo_type = None
if repo_type not in REPO_TYPES:
raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')")
return repo_type, namespace, repo_id
class LastCommitInfo(TypedDict, total=False):
oid: str
title: str
date: datetime
class BlobLfsInfo(TypedDict, total=False):
size: int
sha256: str
pointer_size: int
class BlobSecurityInfo(TypedDict, total=False):
safe: bool
av_scan: Optional[Dict]
pickle_import_scan: Optional[Dict]
class TransformersInfo(TypedDict, total=False):
auto_model: str
custom_class: Optional[str]
# possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72
pipeline_tag: Optional[str]
processor: Optional[str]
class SafeTensorsInfo(TypedDict, total=False):
parameters: List[Dict[str, int]]
total: int
@dataclass
class CommitInfo(str):
"""Data structure containing information about a newly created commit.
Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
[`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
to `str` is deprecated.
Attributes:
commit_url (`str`):
Url where to find the commit.
commit_message (`str`):
The summary (first line) of the commit that has been created.
commit_description (`str`):
Description of the commit that has been created. Can be empty.
oid (`str`):
Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
pr_url (`str`, *optional*):
Url to the PR that has been created, if any. Populated when `create_pr=True`
is passed.
pr_revision (`str`, *optional*):
Revision of the PR that has been created, if any. Populated when
`create_pr=True` is passed. Example: `"refs/pr/1"`.
pr_num (`int`, *optional*):
Number of the PR discussion that has been created, if any. Populated when
`create_pr=True` is passed. Can be passed as `discussion_num` in
[`get_discussion_details`]. Example: `1`.
_url (`str`, *optional*):
Legacy url for `str` compatibility. Can be the url to the uploaded file on the Hub (if returned by
[`upload_file`]), to the uploaded folder on the Hub (if returned by [`upload_folder`]) or to the commit on
the Hub (if returned by [`create_commit`]). Defaults to `commit_url`. It is deprecated to use this
attribute. Please use `commit_url` instead.
"""
commit_url: str
commit_message: str
commit_description: str
oid: str
pr_url: Optional[str] = None
# Computed from `pr_url` in `__post_init__`
pr_revision: Optional[str] = field(init=False)
pr_num: Optional[str] = field(init=False)
# legacy url for `str` compatibility (ex: url to uploaded file, url to uploaded folder, url to PR, etc.)
_url: str = field(repr=False, default=None) # type: ignore # defaults to `commit_url`
def __new__(cls, *args, commit_url: str, _url: Optional[str] = None, **kwargs):
return str.__new__(cls, _url or commit_url)
def __post_init__(self):
"""Populate pr-related fields after initialization.
See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
"""
if self.pr_url is not None:
self.pr_revision = _parse_revision_from_pr_url(self.pr_url)
self.pr_num = int(self.pr_revision.split("/")[-1])
else:
self.pr_revision = None
self.pr_num = None
@dataclass
class AccessRequest:
"""Data structure containing information about a user access request.
Attributes:
username (`str`):
Username of the user who requested access.
fullname (`str`):
Fullname of the user who requested access.
email (`str`):
Email of the user who requested access.
timestamp (`datetime`):
Timestamp of the request.
status (`Literal["pending", "accepted", "rejected"]`):
Status of the request. Can be one of `["pending", "accepted", "rejected"]`.
fields (`Dict[str, Any]`, *optional*):
Additional fields filled by the user in the gate form.
"""
username: str
fullname: str
email: str
timestamp: datetime
status: Literal["pending", "accepted", "rejected"]
# Additional fields filled by the user in the gate form
fields: Optional[Dict[str, Any]] = None
class RepoUrl(str):
"""Subclass of `str` describing a repo URL on the Hub.
`RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
compatibility. At initialization, the URL is parsed to populate properties:
- endpoint (`str`)
- namespace (`Optional[str]`)
- repo_name (`str`)
- repo_id (`str`)
- repo_type (`Literal["model", "dataset", "space"]`)
- url (`str`)
Args:
url (`Any`):
String value of the repo url.
endpoint (`str`, *optional*):
Endpoint of the Hub. Defaults to <https://huggingface.co>.
Example:
```py
>>> RepoUrl('https://huggingface.co/gpt2')
RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
>>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset')
>>> RepoUrl('hf://datasets/my-user/my-dataset')
RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
>>> HfApi.create_repo("dummy_model")
RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
```
Raises:
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If URL cannot be parsed.
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `repo_type` is unknown.
"""
def __new__(cls, url: Any, endpoint: Optional[str] = None):
return super(RepoUrl, cls).__new__(cls, url)
def __init__(self, url: Any, endpoint: Optional[str] = None) -> None:
super().__init__()
# Parse URL
self.endpoint = endpoint or ENDPOINT
repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint)
# Populate fields
self.namespace = namespace
self.repo_name = repo_name
self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}"
self.repo_type = repo_type or REPO_TYPE_MODEL
self.url = str(self) # just in case it's needed
def __repr__(self) -> str:
return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')"
@dataclass
class RepoSibling:
"""
Contains basic information about a repo file inside a repo on the Hub.
<Tip>
All attributes of this class are optional except `rfilename`. This is because only the file names are returned when
listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more
information like file size, blob id or lfs details, you must request them specifically from one repo at a time
(using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to
retrieve these.
</Tip>
Attributes:
rfilename (str):
file name, relative to the repo root.
size (`int`, *optional*):
The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set
to `True`. It's `None` otherwise.
blob_id (`str`, *optional*):
The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to
`True`. It's `None` otherwise.
lfs (`BlobLfsInfo`, *optional*):
The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to
`True` and the file is stored with Git LFS. It's `None` otherwise.
"""
rfilename: str
size: Optional[int] = None
blob_id: Optional[str] = None
lfs: Optional[BlobLfsInfo] = None
@dataclass
class RepoFile:
"""
Contains information about a file on the Hub.
Attributes:
path (str):
file path relative to the repo root.
size (`int`):
The file's size, in bytes.
blob_id (`str`):
The file's git OID.
lfs (`BlobLfsInfo`):
The file's LFS metadata.
last_commit (`LastCommitInfo`, *optional*):
The file's last commit metadata. Only defined if [`list_files_info`], [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
security (`BlobSecurityInfo`, *optional*):
The file's security scan metadata. Only defined if [`list_files_info`], [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
"""
path: str
size: int
blob_id: str
lfs: Optional[BlobLfsInfo] = None
last_commit: Optional[LastCommitInfo] = None
security: Optional[BlobSecurityInfo] = None
def __init__(self, **kwargs):
self.path = kwargs.pop("path")
self.size = kwargs.pop("size")
self.blob_id = kwargs.pop("oid")
lfs = kwargs.pop("lfs", None)
if lfs is not None:
lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"])
self.lfs = lfs
last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
if last_commit is not None:
last_commit = LastCommitInfo(
oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
)
self.last_commit = last_commit
security = kwargs.pop("security", None)
if security is not None:
security = BlobSecurityInfo(
safe=security["safe"], av_scan=security["avScan"], pickle_import_scan=security["pickleImportScan"]
)
self.security = security
# backwards compatibility
self.rfilename = self.path
self.lastCommit = self.last_commit
@dataclass
class RepoFolder:
"""
Contains information about a folder on the Hub.
Attributes:
path (str):
folder path relative to the repo root.
tree_id (`str`):
The folder's git OID.
last_commit (`LastCommitInfo`, *optional*):
The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
"""
path: str
tree_id: str
last_commit: Optional[LastCommitInfo] = None
def __init__(self, **kwargs):
self.path = kwargs.pop("path")
self.tree_id = kwargs.pop("oid")
last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
if last_commit is not None:
last_commit = LastCommitInfo(
oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
)
self.last_commit = last_commit
@dataclass
class ModelInfo:
"""
Contains information about a model on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing models
using [`list_models`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of model.
author (`str`, *optional*):
Author of the model.
sha (`str`, *optional*):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
disabled (`bool`, *optional*):
Is the repo disabled.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
downloads (`int`):
Number of downloads of the model.
likes (`int`):
Number of likes of the model.
library_name (`str`, *optional*):
Library associated with the model.
tags (`List[str]`):
List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
(e.g. supported libraries, model's arXiv).
pipeline_tag (`str`, *optional*):
Pipeline tag associated with the model.
mask_token (`str`, *optional*):
Mask token used by the model.
widget_data (`Any`, *optional*):
Widget data associated with the model.
model_index (`Dict`, *optional*):
Model index for evaluation.
config (`Dict`, *optional*):
Model configuration.
transformers_info (`TransformersInfo`, *optional*):
Transformers-specific info (auto class, processor, etc.) associated with the model.
card_data (`ModelCardData`, *optional*):
Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
spaces (`List[str]`, *optional*):
List of spaces using the model.
safetensors (`SafeTensorsInfo`, *optional*):
Model's safetensors information.
"""
id: str
author: Optional[str]
sha: Optional[str]
created_at: Optional[datetime]
last_modified: Optional[datetime]
private: bool
gated: Optional[Literal["auto", "manual", False]]
disabled: Optional[bool]
downloads: int
likes: int
library_name: Optional[str]
tags: List[str]
pipeline_tag: Optional[str]
mask_token: Optional[str]
card_data: Optional[ModelCardData]
widget_data: Optional[Any]
model_index: Optional[Dict]
config: Optional[Dict]
transformers_info: Optional[TransformersInfo]
siblings: Optional[List[RepoSibling]]
spaces: Optional[List[str]]
safetensors: Optional[SafeTensorsInfo]
def __init__(self, **kwargs):
self.id = kwargs.pop("id")
self.author = kwargs.pop("author", None)
self.sha = kwargs.pop("sha", None)
last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
self.last_modified = parse_datetime(last_modified) if last_modified else None
created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
self.created_at = parse_datetime(created_at) if created_at else None
self.private = kwargs.pop("private")
self.gated = kwargs.pop("gated", None)
self.disabled = kwargs.pop("disabled", None)
self.downloads = kwargs.pop("downloads")
self.likes = kwargs.pop("likes")
self.library_name = kwargs.pop("library_name", None)
self.tags = kwargs.pop("tags")
self.pipeline_tag = kwargs.pop("pipeline_tag", None)
self.mask_token = kwargs.pop("mask_token", None)
card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
self.card_data = (
ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
)
self.widget_data = kwargs.pop("widget_data", None)
self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None)
self.config = kwargs.pop("config", None)
transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None)
self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None
siblings = kwargs.pop("siblings", None)
self.siblings = (
[
RepoSibling(
rfilename=sibling["rfilename"],
size=sibling.get("size"),
blob_id=sibling.get("blobId"),
lfs=(
BlobLfsInfo(
size=sibling["lfs"]["size"],
sha256=sibling["lfs"]["sha256"],
pointer_size=sibling["lfs"]["pointerSize"],
)
if sibling.get("lfs")
else None
),
)
for sibling in siblings
]
if siblings
else None
)
self.spaces = kwargs.pop("spaces", None)
safetensors = kwargs.pop("safetensors", None)
self.safetensors = SafeTensorsInfo(**safetensors) if safetensors else None
# backwards compatibility
self.lastModified = self.last_modified
self.cardData = self.card_data
self.transformersInfo = self.transformers_info
self.__dict__.update(**kwargs)
@dataclass
class DatasetInfo:
"""
Contains information about a dataset on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
using [`list_datasets`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of dataset.
author (`str`):
Author of the dataset.
sha (`str`):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
disabled (`bool`, *optional*):
Is the repo disabled.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
downloads (`int`):
Number of downloads of the dataset.
likes (`int`):
Number of likes of the dataset.
tags (`List[str]`):
List of tags of the dataset.
card_data (`DatasetCardData`, *optional*):
Model Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
"""
id: str
author: Optional[str]
sha: Optional[str]
created_at: Optional[datetime]
last_modified: Optional[datetime]
private: bool
gated: Optional[Literal["auto", "manual", False]]
disabled: Optional[bool]
downloads: int
likes: int
paperswithcode_id: Optional[str]
tags: List[str]
card_data: Optional[DatasetCardData]
siblings: Optional[List[RepoSibling]]
def __init__(self, **kwargs):
self.id = kwargs.pop("id")
self.author = kwargs.pop("author", None)
self.sha = kwargs.pop("sha", None)
created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
self.created_at = parse_datetime(created_at) if created_at else None
last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
self.last_modified = parse_datetime(last_modified) if last_modified else None
self.private = kwargs.pop("private")
self.gated = kwargs.pop("gated", None)
self.disabled = kwargs.pop("disabled", None)
self.downloads = kwargs.pop("downloads")
self.likes = kwargs.pop("likes")
self.paperswithcode_id = kwargs.pop("paperswithcode_id", None)
self.tags = kwargs.pop("tags")
card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
self.card_data = (
DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
)
siblings = kwargs.pop("siblings", None)
self.siblings = (
[
RepoSibling(
rfilename=sibling["rfilename"],
size=sibling.get("size"),
blob_id=sibling.get("blobId"),
lfs=(
BlobLfsInfo(
size=sibling["lfs"]["size"],
sha256=sibling["lfs"]["sha256"],
pointer_size=sibling["lfs"]["pointerSize"],
)
if sibling.get("lfs")
else None
),
)
for sibling in siblings
]
if siblings
else None
)
# backwards compatibility
self.lastModified = self.last_modified
self.cardData = self.card_data
self.__dict__.update(**kwargs)
@dataclass
class SpaceInfo:
"""
Contains information about a Space on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
using [`list_spaces`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of the Space.
author (`str`, *optional*):
Author of the Space.
sha (`str`, *optional*):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
disabled (`bool`, *optional*):
Is the Space disabled.
host (`str`, *optional*):
Host URL of the Space.
subdomain (`str`, *optional*):
Subdomain of the Space.
likes (`int`):
Number of likes of the Space.
tags (`List[str]`):
List of tags of the Space.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space.
card_data (`SpaceCardData`, *optional*):
Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object.
runtime (`SpaceRuntime`, *optional*):
Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object.
sdk (`str`, *optional*):
SDK used by the Space.
models (`List[str]`, *optional*):
List of models used by the Space.
datasets (`List[str]`, *optional*):
List of datasets used by the Space.
"""
id: str
author: Optional[str]
sha: Optional[str]
created_at: Optional[datetime]
last_modified: Optional[datetime]
private: bool
gated: Optional[Literal["auto", "manual", False]]
disabled: Optional[bool]
host: Optional[str]
subdomain: Optional[str]
likes: int
sdk: Optional[str]
tags: List[str]
siblings: Optional[List[RepoSibling]]
card_data: Optional[SpaceCardData]
runtime: Optional[SpaceRuntime]
models: Optional[List[str]]
datasets: Optional[List[str]]
def __init__(self, **kwargs):
self.id = kwargs.pop("id")
self.author = kwargs.pop("author", None)
self.sha = kwargs.pop("sha", None)
created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
self.created_at = parse_datetime(created_at) if created_at else None
last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
self.last_modified = parse_datetime(last_modified) if last_modified else None
self.private = kwargs.pop("private")
self.gated = kwargs.pop("gated", None)
self.disabled = kwargs.pop("disabled", None)
self.host = kwargs.pop("host", None)
self.subdomain = kwargs.pop("subdomain", None)
self.likes = kwargs.pop("likes")
self.sdk = kwargs.pop("sdk", None)
self.tags = kwargs.pop("tags")
card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
self.card_data = (
SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
)
siblings = kwargs.pop("siblings", None)
self.siblings = (
[
RepoSibling(
rfilename=sibling["rfilename"],
size=sibling.get("size"),
blob_id=sibling.get("blobId"),
lfs=(
BlobLfsInfo(
size=sibling["lfs"]["size"],
sha256=sibling["lfs"]["sha256"],
pointer_size=sibling["lfs"]["pointerSize"],
)
if sibling.get("lfs")
else None
),
)
for sibling in siblings
]
if siblings
else None
)
runtime = kwargs.pop("runtime", None)
self.runtime = SpaceRuntime(runtime) if runtime else None
self.models = kwargs.pop("models", None)
self.datasets = kwargs.pop("datasets", None)
# backwards compatibility
self.lastModified = self.last_modified
self.cardData = self.card_data
self.__dict__.update(**kwargs)
@dataclass
class MetricInfo:
"""
Contains information about a metric on the Hub.
Attributes:
id (`str`):
ID of the metric. E.g. `"accuracy"`.
space_id (`str`):
ID of the space associated with the metric. E.g. `"Accuracy"`.
description (`str`):
Description of the metric.
"""
id: str
space_id: str
description: Optional[str]
def __init__(self, **kwargs):
self.id = kwargs.pop("id")
self.space_id = kwargs.pop("spaceId")
self.description = kwargs.pop("description", None)
# backwards compatibility
self.spaceId = self.space_id
self.__dict__.update(**kwargs)
@dataclass
class CollectionItem:
"""
Contains information about an item of a Collection (model, dataset, Space or paper).
Attributes:
item_object_id (`str`):
Unique ID of the item in the collection.
item_id (`str`):
ID of the underlying object on the Hub. Can be either a repo_id or a paper id
e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`.
item_type (`str`):
Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`.
position (`int`):
Position of the item in the collection.
note (`str`, *optional*):
Note associated with the item, as plain text.
"""
item_object_id: str # id in database
item_id: str # repo_id or paper id
item_type: str
position: int
note: Optional[str] = None
def __init__(
self, _id: str, id: str, type: CollectionItemType_T, position: int, note: Optional[Dict] = None, **kwargs
) -> None:
self.item_object_id: str = _id # id in database
self.item_id: str = id # repo_id or paper id
self.item_type: CollectionItemType_T = type
self.position: int = position
self.note: str = note["text"] if note is not None else None
@dataclass
class Collection:
"""
Contains information about a Collection on the Hub.
Attributes:
slug (`str`):
Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
title (`str`):
Title of the collection. E.g. `"Recent models"`.
owner (`str`):
Owner of the collection. E.g. `"TheBloke"`.
items (`List[CollectionItem]`):
List of items in the collection.
last_updated (`datetime`):
Date of the last update of the collection.
position (`int`):
Position of the collection in the list of collections of the owner.
private (`bool`):
Whether the collection is private or not.
theme (`str`):
Theme of the collection. E.g. `"green"`.
upvotes (`int`):
Number of upvotes of the collection.
description (`str`, *optional*):
Description of the collection, as plain text.
url (`str`):
(property) URL of the collection on the Hub.
"""
slug: str
title: str
owner: str
items: List[CollectionItem]
last_updated: datetime
position: int
private: bool
theme: str
upvotes: int
description: Optional[str] = None
def __init__(self, **kwargs) -> None:
self.slug = kwargs.pop("slug")
self.title = kwargs.pop("title")
self.owner = kwargs.pop("owner")
self.items = [CollectionItem(**item) for item in kwargs.pop("items")]
self.last_updated = parse_datetime(kwargs.pop("lastUpdated"))
self.position = kwargs.pop("position")
self.private = kwargs.pop("private")
self.theme = kwargs.pop("theme")
self.upvotes = kwargs.pop("upvotes")
self.description = kwargs.pop("description", None)
endpoint = kwargs.pop("endpoint", None)
if endpoint is None:
endpoint = ENDPOINT
self._url = f"{endpoint}/collections/{self.slug}"
@property
def url(self) -> str:
"""Returns the URL of the collection on the Hub."""
return self._url
@dataclass
class GitRefInfo:
"""
Contains information about a git reference for a repo on the Hub.
Attributes:
name (`str`):
Name of the reference (e.g. tag name or branch name).
ref (`str`):
Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`).
target_commit (`str`):
OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
"""
name: str
ref: str
target_commit: str
@dataclass
class GitRefs:
"""
Contains information about all git references for a repo on the Hub.
Object is returned by [`list_repo_refs`].
Attributes:
branches (`List[GitRefInfo]`):
A list of [`GitRefInfo`] containing information about branches on the repo.
converts (`List[GitRefInfo]`):
A list of [`GitRefInfo`] containing information about "convert" refs on the repo.
Converts are refs used (internally) to push preprocessed data in Dataset repos.
tags (`List[GitRefInfo]`):
A list of [`GitRefInfo`] containing information about tags on the repo.
pull_requests (`List[GitRefInfo]`, *optional*):
A list of [`GitRefInfo`] containing information about pull requests on the repo.
Only returned if `include_prs=True` is set.
"""
branches: List[GitRefInfo]
converts: List[GitRefInfo]
tags: List[GitRefInfo]
pull_requests: Optional[List[GitRefInfo]]
@dataclass
class GitCommitInfo:
"""
Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details.
Attributes:
commit_id (`str`):
OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`)
authors (`List[str]`):
List of authors of the commit.
created_at (`datetime`):
Datetime when the commit was created.
title (`str`):
Title of the commit. This is a free-text value entered by the authors.
message (`str`):
Description of the commit. This is a free-text value entered by the authors.
formatted_title (`str`):
Title of the commit formatted as HTML. Only returned if `formatted=True` is set.
formatted_message (`str`):
Description of the commit formatted as HTML. Only returned if `formatted=True` is set.
"""
commit_id: str
authors: List[str]
created_at: datetime
title: str
message: str
formatted_title: Optional[str]
formatted_message: Optional[str]
@dataclass
class UserLikes:
"""
Contains information about a user likes on the Hub.
Attributes:
user (`str`):
Name of the user for which we fetched the likes.
total (`int`):
Total number of likes.
datasets (`List[str]`):
List of datasets liked by the user (as repo_ids).
models (`List[str]`):
List of models liked by the user (as repo_ids).
spaces (`List[str]`):
List of spaces liked by the user (as repo_ids).
"""
# Metadata
user: str
total: int
# User likes
datasets: List[str]
models: List[str]
spaces: List[str]
@dataclass
class User:
"""
Contains information about a user on the Hub.
Attributes:
avatar_url (`str`):
URL of the user's avatar.
username (`str`):
Name of the user on the Hub (unique).
fullname (`str`):
User's full name.
"""
# Metadata
avatar_url: str
username: str
fullname: str
def future_compatible(fn: CallableT) -> CallableT:
"""Wrap a method of `HfApi` to handle `run_as_future=True`.
A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a
`concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result.
"""
sig = inspect.signature(fn)
args_params = list(sig.parameters)[1:] # remove "self" from list
@wraps(fn)
def _inner(self, *args, **kwargs):
# Get `run_as_future` value if provided (default to False)
if "run_as_future" in kwargs:
run_as_future = kwargs["run_as_future"]
kwargs["run_as_future"] = False # avoid recursion error
else:
run_as_future = False
for param, value in zip(args_params, args):
if param == "run_as_future":
run_as_future = value
break
# Call the function in a thread if `run_as_future=True`
if run_as_future:
return self.run_as_future(fn, self, *args, **kwargs)
# Otherwise, call the function normally
return fn(self, *args, **kwargs)
_inner.is_future_compatible = True # type: ignore
return _inner # type: ignore
class HfApi:
def __init__(
self,
endpoint: Optional[str] = None,
token: Optional[str] = None,
library_name: Optional[str] = None,
library_version: Optional[str] = None,
user_agent: Union[Dict, str, None] = None,
) -> None:
"""Create a HF client to interact with the Hub via HTTP.
The client is initialized with some high-level settings used in all requests
made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi`
client is preferred but not mandatory as all of its public methods are exposed
directly at the root of `huggingface_hub`.
Args:
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if
not provided.
library_name (`str`, *optional*):
The name of the library that is making the HTTP request. Will be added to
the user-agent header. Example: `"transformers"`.
library_version (`str`, *optional*):
The version of the library that is making the HTTP request. Will be added
to the user-agent header. Example: `"4.24.0"`.
user_agent (`str`, `dict`, *optional*):
The user agent info in the form of a dictionary or a single string. It will
be completed with information about the installed packages.
"""
self.endpoint = endpoint if endpoint is not None else ENDPOINT
self.token = token
self.library_name = library_name
self.library_version = library_version
self.user_agent = user_agent
self._thread_pool: Optional[ThreadPoolExecutor] = None
def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]:
"""
Run a method in the background and return a Future instance.
The main goal is to run methods without blocking the main thread (e.g. to push data during a training).
Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts
by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor).
Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool`
argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them
but less verbose.
Args:
fn (`Callable`):
The method to run in the background.
*args, **kwargs:
Arguments with which the method will be called.
Return:
`Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to
get the result of the task.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> future = api.run_as_future(api.whoami) # instant
>>> future.done()
False
>>> future.result() # wait until complete and return result
(...)
>>> future.done()
True
```
"""
if self._thread_pool is None:
self._thread_pool = ThreadPoolExecutor(max_workers=1)
self._thread_pool
return self._thread_pool.submit(fn, *args, **kwargs)
@validate_hf_hub_args
def whoami(self, token: Optional[str] = None) -> Dict:
"""
Call HF API to know "whoami".
Args:
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if
not provided.
"""
r = get_session().get(
f"{self.endpoint}/api/whoami-v2",
headers=self._build_hf_headers(
# If `token` is provided and not `None`, it will be used by default.
# Otherwise, the token must be retrieved from cache or env variable.
token=(token or self.token or True),
),
)
try:
hf_raise_for_status(r)
except HTTPError as e:
raise HTTPError(
"Invalid user token. If you didn't pass a user token, make sure you "
"are properly logged in by executing `huggingface-cli login`, and "
"if you did pass a user token, double-check it's correct.",
request=e.request,
response=e.response,
) from e
return r.json()
def get_token_permission(self, token: Optional[str] = None) -> Literal["read", "write", None]:
"""
Check if a given `token` is valid and return its permissions.
For more details about tokens, please refer to https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens.
Args:
token (`str`, *optional*):
The token to check for validity. Defaults to the one saved locally.
Returns:
`Literal["read", "write", None]`: Permission granted by the token ("read" or "write"). Returns `None` if no
token passed or token is invalid.
"""
try:
return self.whoami(token=token)["auth"]["accessToken"]["role"]
except (LocalTokenNotFoundError, HTTPError):
return None
def get_model_tags(self) -> Dict:
"""
List all valid model tags as a nested namespace object
"""
path = f"{self.endpoint}/api/models-tags-by-type"
r = get_session().get(path)
hf_raise_for_status(r)
return r.json()
def get_dataset_tags(self) -> Dict:
"""
List all valid dataset tags as a nested namespace object.
"""
path = f"{self.endpoint}/api/datasets-tags-by-type"
r = get_session().get(path)
hf_raise_for_status(r)
return r.json()
@validate_hf_hub_args
def list_models(
self,
*,
filter: Union[ModelFilter, str, Iterable[str], None] = None,
author: Optional[str] = None,
search: Optional[str] = None,
emissions_thresholds: Optional[Tuple[float, float]] = None,
sort: Union[Literal["last_modified"], str, None] = None,
direction: Optional[Literal[-1]] = None,
limit: Optional[int] = None,
full: Optional[bool] = None,
cardData: bool = False,
fetch_config: bool = False,
token: Optional[Union[bool, str]] = None,
) -> Iterable[ModelInfo]:
"""
List models hosted on the Huggingface Hub, given some filters.
Args:
filter ([`ModelFilter`] or `str` or `Iterable`, *optional*):
A string or [`ModelFilter`] which can be used to identify models
on the Hub.
author (`str`, *optional*):
A string which identify the author (user or organization) of the
returned models
search (`str`, *optional*):
A string that will be contained in the returned model ids.
emissions_thresholds (`Tuple`, *optional*):
A tuple of two ints or floats representing a minimum and maximum
carbon footprint to filter the resulting models with in grams.
sort (`Literal["last_modified"]` or `str`, *optional*):
The key with which to sort the resulting models. Possible values
are the properties of the [`huggingface_hub.hf_api.ModelInfo`] class.
direction (`Literal[-1]` or `int`, *optional*):
Direction in which to sort. The value `-1` sorts by descending
order while all other values sort by ascending order.
limit (`int`, *optional*):
The limit on the number of models fetched. Leaving this option
to `None` fetches all models.
full (`bool`, *optional*):
Whether to fetch all model data, including the `last_modified`,
the `sha`, the files and the `tags`. This is set to `True` by
default when using a filter.
cardData (`bool`, *optional*):
Whether to grab the metadata for the model as well. Can contain
useful information such as carbon emissions, metrics, and
datasets trained on.
fetch_config (`bool`, *optional*):
Whether to fetch the model configs as well. This is not included
in `full` due to its size.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
`Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects.
Example usage with the `filter` argument:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> # List all models
>>> api.list_models()
>>> # List only the text classification models
>>> api.list_models(filter="text-classification")
>>> # Using the `ModelFilter`
>>> filt = ModelFilter(task="text-classification")
>>> # List only models from the AllenNLP library
>>> api.list_models(filter="allennlp")
```
Example usage with the `search` argument:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> # List all models with "bert" in their name
>>> api.list_models(search="bert")
>>> # List all models with "bert" in their name made by google
>>> api.list_models(search="bert", author="google")
```
"""
if emissions_thresholds is not None and cardData is None:
raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.")
path = f"{self.endpoint}/api/models"
headers = self._build_hf_headers(token=token)
params = {}
if filter is not None:
if isinstance(filter, ModelFilter):
params = self._unpack_model_filter(filter)
else:
params.update({"filter": filter})
params.update({"full": True})
if author is not None:
params.update({"author": author})
if search is not None:
params.update({"search": search})
if sort is not None:
params.update({"sort": "lastModified" if sort == "last_modified" else sort})
if direction is not None:
params.update({"direction": direction})
if limit is not None:
params.update({"limit": limit})
if full is not None:
if full:
params.update({"full": True})
elif "full" in params:
del params["full"]
if fetch_config:
params.update({"config": True})
if cardData:
params.update({"cardData": True})
# `items` is a generator
items = paginate(path, params=params, headers=headers)
if limit is not None:
items = islice(items, limit) # Do not iterate over all pages
for item in items:
if "siblings" not in item:
item["siblings"] = None
model_info = ModelInfo(**item)
if emissions_thresholds is None or _is_emission_within_treshold(model_info, *emissions_thresholds):
yield model_info
def _unpack_model_filter(self, model_filter: ModelFilter):
"""
Unpacks a [`ModelFilter`] into something readable for `list_models`
"""
model_str = ""
# Handling author
if model_filter.author is not None:
model_str = f"{model_filter.author}/"
# Handling model_name
if model_filter.model_name is not None:
model_str += model_filter.model_name
filter_list: List[str] = []
# Handling tasks
if model_filter.task is not None:
filter_list.extend([model_filter.task] if isinstance(model_filter.task, str) else model_filter.task)
# Handling dataset
if model_filter.trained_dataset is not None:
if not isinstance(model_filter.trained_dataset, (list, tuple)):
model_filter.trained_dataset = [model_filter.trained_dataset]
for dataset in model_filter.trained_dataset:
if "dataset:" not in dataset:
dataset = f"dataset:{dataset}"
filter_list.append(dataset)
# Handling library
if model_filter.library:
filter_list.extend(
[model_filter.library] if isinstance(model_filter.library, str) else model_filter.library
)
# Handling tags
if model_filter.tags:
filter_list.extend([model_filter.tags] if isinstance(model_filter.tags, str) else model_filter.tags)
query_dict: Dict[str, Any] = {}
if model_str is not None:
query_dict["search"] = model_str
if isinstance(model_filter.language, list):
filter_list.extend(model_filter.language)
elif isinstance(model_filter.language, str):
filter_list.append(model_filter.language)
query_dict["filter"] = tuple(filter_list)
return query_dict
@validate_hf_hub_args
def list_datasets(
self,
*,
filter: Union[DatasetFilter, str, Iterable[str], None] = None,
author: Optional[str] = None,
search: Optional[str] = None,
sort: Union[Literal["last_modified"], str, None] = None,
direction: Optional[Literal[-1]] = None,
limit: Optional[int] = None,
full: Optional[bool] = None,
token: Optional[str] = None,
) -> Iterable[DatasetInfo]:
"""
List datasets hosted on the Huggingface Hub, given some filters.
Args:
filter ([`DatasetFilter`] or `str` or `Iterable`, *optional*):
A string or [`DatasetFilter`] which can be used to identify
datasets on the hub.
author (`str`, *optional*):
A string which identify the author of the returned datasets.
search (`str`, *optional*):
A string that will be contained in the returned datasets.
sort (`Literal["last_modified"]` or `str`, *optional*):
The key with which to sort the resulting datasets. Possible
values are the properties of the [`huggingface_hub.hf_api.DatasetInfo`] class.
direction (`Literal[-1]` or `int`, *optional*):
Direction in which to sort. The value `-1` sorts by descending
order while all other values sort by ascending order.
limit (`int`, *optional*):
The limit on the number of datasets fetched. Leaving this option
to `None` fetches all datasets.
full (`bool`, *optional*):
Whether to fetch all dataset data, including the `last_modified`,
the `card_data` and the files. Can contain useful information such as the
PapersWithCode ID.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
`Iterable[DatasetInfo]`: an iterable of [`huggingface_hub.hf_api.DatasetInfo`] objects.
Example usage with the `filter` argument:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> # List all datasets
>>> api.list_datasets()
>>> # List only the text classification datasets
>>> api.list_datasets(filter="task_categories:text-classification")
>>> # Using the `DatasetFilter`
>>> filt = DatasetFilter(task_categories="text-classification")
>>> # List only the datasets in russian for language modeling
>>> api.list_datasets(
... filter=("language:ru", "task_ids:language-modeling")
... )
>>> # Using the `DatasetFilter`
>>> filt = DatasetFilter(language="ru", task_ids="language-modeling")
>>> api.list_datasets(filter=filt)
```
Example usage with the `search` argument:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> # List all datasets with "text" in their name
>>> api.list_datasets(search="text")
>>> # List all datasets with "text" in their name made by google
>>> api.list_datasets(search="text", author="google")
```
"""
path = f"{self.endpoint}/api/datasets"
headers = self._build_hf_headers(token=token)
params = {}
if filter is not None:
if isinstance(filter, DatasetFilter):
params = self._unpack_dataset_filter(filter)
else:
params.update({"filter": filter})
if author is not None:
params.update({"author": author})
if search is not None:
params.update({"search": search})
if sort is not None:
params.update({"sort": "lastModified" if sort == "last_modified" else sort})
if direction is not None:
params.update({"direction": direction})
if limit is not None:
params.update({"limit": limit})
if full:
params.update({"full": True})
items = paginate(path, params=params, headers=headers)
if limit is not None:
items = islice(items, limit) # Do not iterate over all pages
for item in items:
if "siblings" not in item:
item["siblings"] = None
yield DatasetInfo(**item)
def _unpack_dataset_filter(self, dataset_filter: DatasetFilter):
"""
Unpacks a [`DatasetFilter`] into something readable for `list_datasets`
"""
dataset_str = ""
# Handling author
if dataset_filter.author is not None:
dataset_str = f"{dataset_filter.author}/"
# Handling dataset_name
if dataset_filter.dataset_name is not None:
dataset_str += dataset_filter.dataset_name
filter_list = []
data_attributes = [
"benchmark",
"language_creators",
"language",
"multilinguality",
"size_categories",
"task_categories",
"task_ids",
]
for attr in data_attributes:
curr_attr = getattr(dataset_filter, attr)
if curr_attr is not None:
if not isinstance(curr_attr, (list, tuple)):
curr_attr = [curr_attr]
for data in curr_attr:
if f"{attr}:" not in data:
data = f"{attr}:{data}"
filter_list.append(data)
query_dict: Dict[str, Any] = {}
if dataset_str is not None:
query_dict["search"] = dataset_str
query_dict["filter"] = tuple(filter_list)
return query_dict
def list_metrics(self) -> List[MetricInfo]:
"""
Get the public list of all the metrics on huggingface.co
Returns:
`List[MetricInfo]`: a list of [`MetricInfo`] objects which.
"""
path = f"{self.endpoint}/api/metrics"
r = get_session().get(path)
hf_raise_for_status(r)
d = r.json()
return [MetricInfo(**x) for x in d]
@validate_hf_hub_args
def list_spaces(
self,
*,
filter: Union[str, Iterable[str], None] = None,
author: Optional[str] = None,
search: Optional[str] = None,
sort: Union[Literal["last_modified"], str, None] = None,
direction: Optional[Literal[-1]] = None,
limit: Optional[int] = None,
datasets: Union[str, Iterable[str], None] = None,
models: Union[str, Iterable[str], None] = None,
linked: bool = False,
full: Optional[bool] = None,
token: Optional[str] = None,
) -> Iterable[SpaceInfo]:
"""
List spaces hosted on the Huggingface Hub, given some filters.
Args:
filter (`str` or `Iterable`, *optional*):
A string tag or list of tags that can be used to identify Spaces on the Hub.
author (`str`, *optional*):
A string which identify the author of the returned Spaces.
search (`str`, *optional*):
A string that will be contained in the returned Spaces.
sort (`Literal["last_modified"]` or `str`, *optional*):
The key with which to sort the resulting Spaces. Possible
values are the properties of the [`huggingface_hub.hf_api.SpaceInfo`]` class.
direction (`Literal[-1]` or `int`, *optional*):
Direction in which to sort. The value `-1` sorts by descending
order while all other values sort by ascending order.
limit (`int`, *optional*):
The limit on the number of Spaces fetched. Leaving this option
to `None` fetches all Spaces.
datasets (`str` or `Iterable`, *optional*):
Whether to return Spaces that make use of a dataset.
The name of a specific dataset can be passed as a string.
models (`str` or `Iterable`, *optional*):
Whether to return Spaces that make use of a model.
The name of a specific model can be passed as a string.
linked (`bool`, *optional*):
Whether to return Spaces that make use of either a model or a dataset.
full (`bool`, *optional*):
Whether to fetch all Spaces data, including the `last_modified`, `siblings`
and `card_data` fields.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
`Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects.
"""
path = f"{self.endpoint}/api/spaces"
headers = self._build_hf_headers(token=token)
params: Dict[str, Any] = {}
if filter is not None:
params.update({"filter": filter})
if author is not None:
params.update({"author": author})
if search is not None:
params.update({"search": search})
if sort is not None:
params.update({"sort": "lastModified" if sort == "last_modified" else sort})
if direction is not None:
params.update({"direction": direction})
if limit is not None:
params.update({"limit": limit})
if full:
params.update({"full": True})
if linked:
params.update({"linked": True})
if datasets is not None:
params.update({"datasets": datasets})
if models is not None:
params.update({"models": models})
items = paginate(path, params=params, headers=headers)
if limit is not None:
items = islice(items, limit) # Do not iterate over all pages
for item in items:
if "siblings" not in item:
item["siblings"] = None
yield SpaceInfo(**item)
@validate_hf_hub_args
def like(
self,
repo_id: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> None:
"""
Like a given repo on the Hub (e.g. set as favorite).
See also [`unlike`] and [`list_liked_repos`].
Args:
repo_id (`str`):
The repository to like. Example: `"user/my-cool-model"`.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if liking a dataset or space, `None` or
`"model"` if liking a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
Example:
```python
>>> from huggingface_hub import like, list_liked_repos, unlike
>>> like("gpt2")
>>> "gpt2" in list_liked_repos().models
True
>>> unlike("gpt2")
>>> "gpt2" in list_liked_repos().models
False
```
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
response = get_session().post(
url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
@validate_hf_hub_args
def unlike(
self,
repo_id: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> None:
"""
Unlike a given repo on the Hub (e.g. remove from favorite list).
See also [`like`] and [`list_liked_repos`].
Args:
repo_id (`str`):
The repository to unlike. Example: `"user/my-cool-model"`.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or
`"model"` if unliking a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
Example:
```python
>>> from huggingface_hub import like, list_liked_repos, unlike
>>> like("gpt2")
>>> "gpt2" in list_liked_repos().models
True
>>> unlike("gpt2")
>>> "gpt2" in list_liked_repos().models
False
```
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
response = get_session().delete(
url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token)
)
hf_raise_for_status(response)
@validate_hf_hub_args
def list_liked_repos(
self,
user: Optional[str] = None,
*,
token: Optional[str] = None,
) -> UserLikes:
"""
List all public repos liked by a user on huggingface.co.
This list is public so token is optional. If `user` is not passed, it defaults to
the logged in user.
See also [`like`] and [`unlike`].
Args:
user (`str`, *optional*):
Name of the user for which you want to fetch the likes.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Used only if `user` is not passed to implicitly determine the current
user name.
Returns:
[`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for
models, 1 for datasets and 1 for Spaces).
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `user` is not passed and no token found (either from argument or from machine).
Example:
```python
>>> from huggingface_hub import list_liked_repos
>>> likes = list_liked_repos("julien-c")
>>> likes.user
"julien-c"
>>> likes.models
["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]
```
"""
# User is either provided explicitly or retrieved from current token.
if user is None:
me = self.whoami(token=token)
if me["type"] == "user":
user = me["name"]
else:
raise ValueError(
"Cannot list liked repos. You must provide a 'user' as input or be logged in as a user."
)
path = f"{self.endpoint}/api/users/{user}/likes"
headers = self._build_hf_headers(token=token)
likes = list(paginate(path, params={}, headers=headers))
# Looping over a list of items similar to:
# {
# 'createdAt': '2021-09-09T21:53:27.000Z',
# 'repo': {
# 'name': 'PaddlePaddle/PaddleOCR',
# 'type': 'space'
# }
# }
# Let's loop 3 times over the received list. Less efficient but more straightforward to read.
return UserLikes(
user=user,
total=len(likes),
models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"],
datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"],
spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"],
)
@validate_hf_hub_args
def list_repo_likers(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> List[User]:
"""
List all users who liked a given repo on the hugging Face Hub.
See also [`like`] and [`list_liked_repos`].
Args:
repo_id (`str`):
The repository to retrieve . Example: `"user/my-cool-model"`.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns:
`List[User]`: a list of [`User`] objects.
"""
# Construct the API endpoint
if repo_type is None:
repo_type = REPO_TYPE_MODEL
path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers"
headers = self._build_hf_headers(token=token)
# Make the request
response = get_session().get(path, headers=headers)
hf_raise_for_status(response)
# Parse the results into User objects
likers_data = response.json()
return [
User(
username=user_data["user"],
fullname=user_data["fullname"],
avatar_url=user_data["avatarUrl"],
)
for user_data in likers_data
]
@validate_hf_hub_args
def model_info(
self,
repo_id: str,
*,
revision: Optional[str] = None,
timeout: Optional[float] = None,
securityStatus: Optional[bool] = None,
files_metadata: bool = False,
token: Optional[Union[bool, str]] = None,
) -> ModelInfo:
"""
Get info on one specific model on huggingface.co
Model can be private if you pass an acceptable token or are logged in.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the model repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
securityStatus (`bool`, *optional*):
Whether to retrieve the security status from the model
repository as well.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
[`huggingface_hub.hf_api.ModelInfo`]: The model repository information.
<Tip>
Raises the following errors:
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
</Tip>
"""
headers = self._build_hf_headers(token=token)
path = (
f"{self.endpoint}/api/models/{repo_id}"
if revision is None
else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}")
)
params = {}
if securityStatus:
params["securityStatus"] = True
if files_metadata:
params["blobs"] = True
r = get_session().get(path, headers=headers, timeout=timeout, params=params)
hf_raise_for_status(r)
data = r.json()
return ModelInfo(**data)
@validate_hf_hub_args
def dataset_info(
self,
repo_id: str,
*,
revision: Optional[str] = None,
timeout: Optional[float] = None,
files_metadata: bool = False,
token: Optional[Union[bool, str]] = None,
) -> DatasetInfo:
"""
Get info on one specific dataset on huggingface.co.
Dataset can be private if you pass an acceptable token.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the dataset repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
[`hf_api.DatasetInfo`]: The dataset repository information.
<Tip>
Raises the following errors:
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
</Tip>
"""
headers = self._build_hf_headers(token=token)
path = (
f"{self.endpoint}/api/datasets/{repo_id}"
if revision is None
else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}")
)
params = {}
if files_metadata:
params["blobs"] = True
r = get_session().get(path, headers=headers, timeout=timeout, params=params)
hf_raise_for_status(r)
data = r.json()
return DatasetInfo(**data)
@validate_hf_hub_args
def space_info(
self,
repo_id: str,
*,
revision: Optional[str] = None,
timeout: Optional[float] = None,
files_metadata: bool = False,
token: Optional[Union[bool, str]] = None,
) -> SpaceInfo:
"""
Get info on one specific Space on huggingface.co.
Space can be private if you pass an acceptable token.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the space repository from which to get the
information.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
[`~hf_api.SpaceInfo`]: The space repository information.
<Tip>
Raises the following errors:
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
</Tip>
"""
headers = self._build_hf_headers(token=token)
path = (
f"{self.endpoint}/api/spaces/{repo_id}"
if revision is None
else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}")
)
params = {}
if files_metadata:
params["blobs"] = True
r = get_session().get(path, headers=headers, timeout=timeout, params=params)
hf_raise_for_status(r)
data = r.json()
return SpaceInfo(**data)
@validate_hf_hub_args
def repo_info(
self,
repo_id: str,
*,
revision: Optional[str] = None,
repo_type: Optional[str] = None,
timeout: Optional[float] = None,
files_metadata: bool = False,
token: Optional[Union[bool, str]] = None,
) -> Union[ModelInfo, DatasetInfo, SpaceInfo]:
"""
Get the info object for a given repo of a given type.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
revision (`str`, *optional*):
The revision of the repository from which to get the
information.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
timeout (`float`, *optional*):
Whether to set a timeout for the request to the Hub.
files_metadata (`bool`, *optional*):
Whether or not to retrieve metadata for files in the repository
(size, LFS metadata, etc). Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
`Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a
[`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`]
or [`huggingface_hub.hf_api.SpaceInfo`] object.
<Tip>
Raises the following errors:
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
</Tip>
"""
if repo_type is None or repo_type == "model":
method = self.model_info
elif repo_type == "dataset":
method = self.dataset_info # type: ignore
elif repo_type == "space":
method = self.space_info # type: ignore
else:
raise ValueError("Unsupported repo type.")
return method(
repo_id,
revision=revision,
token=token,
timeout=timeout,
files_metadata=files_metadata,
)
@validate_hf_hub_args
def repo_exists(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> bool:
"""
Checks if a repository exists on the Hugging Face Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
True if the repository exists, False otherwise.
<Tip>
Examples:
```py
>>> from huggingface_hub import repo_exists
>>> repo_exists("huggingface/transformers")
True
>>> repo_exists("huggingface/not-a-repo")
False
```
</Tip>
"""
try:
self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
return True
except GatedRepoError:
return True # we don't have access but it exists
except RepositoryNotFoundError:
return False
@validate_hf_hub_args
def file_exists(
self,
repo_id: str,
filename: str,
*,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
token: Optional[str] = None,
) -> bool:
"""
Checks if a file exists in a repository on the Hugging Face Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
filename (`str`):
The name of the file to check, for example:
`"config.json"`
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space,
`None` or `"model"` if getting repository info from a model. Default is `None`.
revision (`str`, *optional*):
The revision of the repository from which to get the information. Defaults to `"main"` branch.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
True if the file exists, False otherwise.
<Tip>
Examples:
```py
>>> from huggingface_hub import file_exists
>>> file_exists("bigcode/starcoder", "config.json")
True
>>> file_exists("bigcode/starcoder", "not-a-file")
False
>>> file_exists("bigcode/not-a-repo", "config.json")
False
```
</Tip>
"""
url = hf_hub_url(
repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint
)
try:
if token is None:
token = self.token
get_hf_file_metadata(url, token=token)
return True
except GatedRepoError: # raise specifically on gated repo
raise
except (RepositoryNotFoundError, EntryNotFoundError, RevisionNotFoundError):
return False
@validate_hf_hub_args
@_deprecate_method(version="0.23", message="Use `list_repo_tree` and `get_paths_info` instead.")
def list_files_info(
self,
repo_id: str,
paths: Union[List[str], str, None] = None,
*,
expand: bool = False,
revision: Optional[str] = None,
repo_type: Optional[str] = None,
token: Optional[Union[bool, str]] = None,
) -> Iterable[RepoFile]:
"""
List files on a repo and get information about them.
Takes as input a list of paths. Those paths can be either files or folders. Two server endpoints are called:
1. POST "/paths-info" to get information about the provided paths. Called once.
2. GET "/tree?recursive=True" to paginate over the input folders. Called only if a folder path is provided as
input. Will be called multiple times to follow pagination.
If no path is provided as input, step 1. is ignored and all files from the repo are listed.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
paths (`Union[List[str], str, None]`, *optional*):
The paths to get information about. Paths to files are directly resolved. Paths to folders are resolved
recursively which means that information is returned about all files in the folder and its subfolders.
If `None`, all files are returned (the default). If a path do not exist, it is ignored without raising
an exception.
expand (`bool`, *optional*, defaults to `False`):
Whether to fetch more information about the files (e.g. last commit and security scan results). This
operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
takes to get the results.
revision (`str`, *optional*):
The revision of the repository from which to get the information. Defaults to `"main"` branch.
repo_type (`str`, *optional*):
The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
Defaults to `"model"`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
retrieved from the cache. If `False`, token is not sent in the request header.
Returns:
`Iterable[RepoFile]`:
The information about the files, as an iterable of [`RepoFile`] objects. The order of the files is
not guaranteed.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
Examples:
Get information about files on a repo.
```py
>>> from huggingface_hub import list_files_info
>>> files_info = list_files_info("lysandre/arxiv-nlp", ["README.md", "config.json"])
>>> files_info
<generator object HfApi.list_files_info at 0x7f93b848e730>
>>> list(files_info)
[
RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None)
]
```
Get even more information about files on a repo (last commit and security scan results)
```py
>>> from huggingface_hub import list_files_info
>>> files_info = list_files_info("prompthero/openjourney-v4", expand=True)
>>> list(files_info)
[
RepoFile(
path='safety_checker/pytorch_model.bin',
size=1216064769,
blob_id='c8835557a0d3af583cb06c7c154b7e54a069c41d',
lfs={
'size': 1216064769,
'sha256': '16d28f2b37109f222cdc33620fdd262102ac32112be0352a7f77e9614b35a394',
'pointer_size': 135
},
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)
},
security={
'safe': True,
'av_scan': {
'virusFound': False,
'virusNames': None
},
'pickle_import_scan': {
'highestSafetyLevel': 'innocuous',
'imports': [
{'module': 'torch', 'name': 'FloatStorage', 'safety': 'innocuous'},
{'module': 'collections', 'name': 'OrderedDict', 'safety': 'innocuous'},
{'module': 'torch', 'name': 'LongStorage', 'safety': 'innocuous'},
{'module': 'torch._utils', 'name': '_rebuild_tensor_v2', 'safety': 'innocuous'}
]
}
}
),
RepoFile(
path='scheduler/scheduler_config.json',
size=465,
blob_id='70d55e3e9679f41cbc66222831b38d5abce683dd',
lfs=None,
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)},
security={
'safe': True,
'av_scan': {
'virusFound': False,
'virusNames': None
},
'pickle_import_scan': None
}
),
...
]
```
List LFS files from the "vae/" folder in "stabilityai/stable-diffusion-2" repository.
```py
>>> from huggingface_hub import list_files_info
>>> [info.path for info in list_files_info("stabilityai/stable-diffusion-2", "vae") if info.lfs is not None]
['vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors']
```
List all files on a repo.
```py
>>> from huggingface_hub import list_files_info
>>> [info.path for info in list_files_info("glue", repo_type="dataset")]
['.gitattributes', 'README.md', 'dataset_infos.json', 'glue.py']
```
"""
repo_type = repo_type or REPO_TYPE_MODEL
revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION
headers = self._build_hf_headers(token=token)
folder_paths = []
if paths is None:
# `paths` is not provided => list all files from the repo
folder_paths.append("")
elif paths == []:
# corner case: server would return a 400 error if `paths` is an empty list. Let's return early.
return
else:
# `paths` is provided => get info about those
response = get_session().post(
f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}",
data={
"paths": paths if isinstance(paths, list) else [paths],
"expand": expand,
},
headers=headers,
)
hf_raise_for_status(response)
paths_info = response.json()
# List top-level files first
for path_info in paths_info:
if path_info["type"] == "file":
yield RepoFile(**path_info)
else:
folder_paths.append(path_info["path"])
# List files in subdirectories
for path in folder_paths:
encoded_path = "/" + quote(path, safe="") if path else ""
tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path}"
for subpath_info in paginate(path=tree_url, headers=headers, params={"recursive": True, "expand": expand}):
if subpath_info["type"] == "file":
yield RepoFile(**subpath_info)
@validate_hf_hub_args
def list_repo_files(
self,
repo_id: str,
*,
revision: Optional[str] = None,
repo_type: Optional[str] = None,
token: Optional[Union[bool, str]] = None,
) -> List[str]:
"""
Get the list of files in a given repo.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
revision (`str`, *optional*):
The revision of the model repository from which to get the information.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
retrieved from the cache. If `False`, token is not sent in the request header.
Returns:
`List[str]`: the list of files in a given repository.
"""
return [
f.rfilename
for f in self.list_repo_tree(
repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token
)
if isinstance(f, RepoFile)
]
@validate_hf_hub_args
def list_repo_tree(
self,
repo_id: str,
path_in_repo: Optional[str] = None,
*,
recursive: bool = False,
expand: bool = False,
revision: Optional[str] = None,
repo_type: Optional[str] = None,
token: Optional[Union[bool, str]] = None,
) -> Iterable[Union[RepoFile, RepoFolder]]:
"""
List a repo tree's files and folders and get information about them.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
path_in_repo (`str`, *optional*):
Relative path of the tree (folder) in the repo, for example:
`"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository.
recursive (`bool`, *optional*, defaults to `False`):
Whether to list tree's files and folders recursively.
expand (`bool`, *optional*, defaults to `False`):
Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This
operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
takes to get the results.
revision (`str`, *optional*):
The revision of the repository from which to get the tree. Defaults to `"main"` branch.
repo_type (`str`, *optional*):
The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`.
Defaults to `"model"`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
retrieved from the cache. If `False`, token is not sent in the request header.
Returns:
`Iterable[Union[RepoFile, RepoFolder]]`:
The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is
not guaranteed.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
[`~utils.EntryNotFoundError`]:
If the tree (folder) does not exist (error 404) on the repo.
Examples:
Get information about a repo's tree.
```py
>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
>>> repo_tree
<generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
>>> list(repo_tree)
[
RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
RepoFile(
path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
),
RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
RepoFile(
path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
),
RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
]
```
Get even more information about a repo's tree (last commit and files' security scan results)
```py
>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
>>> list(repo_tree)
[
RepoFolder(
path='feature_extractor',
tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
}
),
RepoFolder(
path='safety_checker',
tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
}
),
RepoFile(
path='model_index.json',
size=582,
blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
lfs=None,
last_commit={
'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
},
security={
'safe': True,
'av_scan': {'virusFound': False, 'virusNames': None},
'pickle_import_scan': None
}
)
...
]
```
"""
repo_type = repo_type or REPO_TYPE_MODEL
revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION
headers = self._build_hf_headers(token=token)
encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else ""
tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}"
for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}):
yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info))
@validate_hf_hub_args
def list_repo_refs(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
include_pull_requests: bool = False,
token: Optional[Union[bool, str]] = None,
) -> GitRefs:
"""
Get the list of refs of a given repo (both tags and branches).
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if listing refs from a dataset or a Space,
`None` or `"model"` if listing from a model. Default is `None`.
include_pull_requests (`bool`, *optional*):
Whether to include refs from pull requests in the list. Defaults to `False`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_repo_refs("gpt2")
GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
>>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
GitRefs(
branches=[
GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
],
converts=[],
tags=[
GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
]
)
```
Returns:
[`GitRefs`]: object containing all information about branches and tags for a
repo on the Hub.
"""
repo_type = repo_type or REPO_TYPE_MODEL
response = get_session().get(
f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs",
headers=self._build_hf_headers(token=token),
params={"include_prs": 1} if include_pull_requests else {},
)
hf_raise_for_status(response)
data = response.json()
def _format_as_git_ref_info(item: Dict) -> GitRefInfo:
return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"])
return GitRefs(
branches=[_format_as_git_ref_info(item) for item in data["branches"]],
converts=[_format_as_git_ref_info(item) for item in data["converts"]],
tags=[_format_as_git_ref_info(item) for item in data["tags"]],
pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]]
if include_pull_requests
else None,
)
@validate_hf_hub_args
def list_repo_commits(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
formatted: bool = False,
) -> List[GitCommitInfo]:
"""
Get the list of commits of a given revision for a repo on the Hub.
Commits are sorted by date (last commit first).
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
listing from a model. Default is `None`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
formatted (`bool`):
Whether to return the HTML-formatted title and description of the commits. Defaults to False.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Commits are sorted by date (last commit first)
>>> initial_commit = api.list_repo_commits("gpt2")[-1]
# Initial commit is always a system commit containing the `.gitattributes` file.
>>> initial_commit
GitCommitInfo(
commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
authors=['system'],
created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
title='initial commit',
message='',
formatted_title=None,
formatted_message=None
)
# Create an empty branch by deriving from initial commit
>>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)
```
Returns:
List[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
"""
repo_type = repo_type or REPO_TYPE_MODEL
revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION
# Paginate over results and return the list of commits.
return [
GitCommitInfo(
commit_id=item["id"],
authors=[author["user"] for author in item["authors"]],
created_at=parse_datetime(item["date"]),
title=item["title"],
message=item["message"],
formatted_title=item.get("formatted", {}).get("title"),
formatted_message=item.get("formatted", {}).get("message"),
)
for item in paginate(
f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}",
headers=self._build_hf_headers(token=token),
params={"expand[]": "formatted"} if formatted else {},
)
]
@validate_hf_hub_args
def get_paths_info(
self,
repo_id: str,
paths: Union[List[str], str],
*,
expand: bool = False,
revision: Optional[str] = None,
repo_type: Optional[str] = None,
token: Optional[Union[bool, str]] = None,
) -> List[Union[RepoFile, RepoFolder]]:
"""
Get information about a repo's paths.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
paths (`Union[List[str], str]`, *optional*):
The paths to get information about. If a path do not exist, it is ignored without raising
an exception.
expand (`bool`, *optional*, defaults to `False`):
Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This
operation is more expensive for the server so only 50 results are returned per page (instead of 1000).
As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it
takes to get the results.
revision (`str`, *optional*):
The revision of the repository from which to get the information. Defaults to `"main"` branch.
repo_type (`str`, *optional*):
The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`.
Defaults to `"model"`.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
retrieved from the cache. If `False`, token is not sent in the request header.
Returns:
`List[Union[RepoFile, RepoFolder]]`:
The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
Example:
```py
>>> from huggingface_hub import get_paths_info
>>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
>>> paths_info
[
RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
]
```
"""
repo_type = repo_type or REPO_TYPE_MODEL
revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION
headers = self._build_hf_headers(token=token)
response = get_session().post(
f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}",
data={
"paths": paths if isinstance(paths, list) else [paths],
"expand": expand,
},
headers=headers,
)
hf_raise_for_status(response)
paths_info = response.json()
return [
RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)
for path_info in paths_info
]
@validate_hf_hub_args
def super_squash_history(
self,
repo_id: str,
*,
branch: Optional[str] = None,
commit_message: Optional[str] = None,
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> None:
"""Squash commit history on a branch for a repo on the Hub.
Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to
clutter the history. Squashing commits can only be performed from the head of a branch.
<Tip warning={true}>
Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.
</Tip>
<Tip warning={true}>
Once the history of a branch has been squashed, it is not possible to merge it back into another branch since
their history will have diverged.
</Tip>
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated by a `/`.
branch (`str`, *optional*):
The branch to squash. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The commit message to use for the squashed commit.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if
listing from a model. Default is `None`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If the machine is logged in
(through `huggingface-cli login` or [`~huggingface_hub.login`]), token can be automatically retrieved
from the cache.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo
does not exist.
[`~utils.RevisionNotFoundError`]:
If the branch to squash cannot be found.
[`~utils.BadRequestError`]:
If invalid reference for a branch. You cannot squash history on tags.
Example:
```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Create repo
>>> repo_id = api.create_repo("test-squash").repo_id
# Make a lot of commits.
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
# Squash history
>>> api.super_squash_history(repo_id=repo_id)
```
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
if repo_type not in REPO_TYPES:
raise ValueError("Invalid repo type")
if branch is None:
branch = DEFAULT_REVISION
# Prepare request
url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{branch}"
headers = self._build_hf_headers(token=token, is_write_action=True)
commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub"
# Super-squash
response = get_session().post(url=url, headers=headers, json={"message": commit_message})
hf_raise_for_status(response)
@validate_hf_hub_args
def create_repo(
self,
repo_id: str,
*,
token: Optional[str] = None,
private: bool = False,
repo_type: Optional[str] = None,
exist_ok: bool = False,
space_sdk: Optional[str] = None,
space_hardware: Optional[SpaceHardware] = None,
space_storage: Optional[SpaceStorage] = None,
space_sleep_time: Optional[int] = None,
space_secrets: Optional[List[Dict[str, str]]] = None,
space_variables: Optional[List[Dict[str, str]]] = None,
) -> RepoUrl:
"""Create an empty repo on the HuggingFace Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
private (`bool`, *optional*, defaults to `False`):
Whether the model repo should be private.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo already exists.
space_sdk (`str`, *optional*):
Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".
space_hardware (`SpaceHardware` or `str`, *optional*):
Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list.
space_storage (`SpaceStorage` or `str`, *optional*):
Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
space_sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
space_secrets (`List[Dict[str, str]]`, *optional*):
A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
space_variables (`List[Dict[str, str]]`, *optional*):
A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
Returns:
[`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
attributes like `endpoint`, `repo_type` and `repo_id`.
"""
organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
path = f"{self.endpoint}/api/repos/create"
if repo_type not in REPO_TYPES:
raise ValueError("Invalid repo type")
json: Dict[str, Any] = {"name": name, "organization": organization, "private": private}
if repo_type is not None:
json["type"] = repo_type
if repo_type == "space":
if space_sdk is None:
raise ValueError(
"No space_sdk provided. `create_repo` expects space_sdk to be one"
f" of {SPACES_SDK_TYPES} when repo_type is 'space'`"
)
if space_sdk not in SPACES_SDK_TYPES:
raise ValueError(f"Invalid space_sdk. Please choose one of {SPACES_SDK_TYPES}.")
json["sdk"] = space_sdk
if space_sdk is not None and repo_type != "space":
warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.")
function_args = [
"space_hardware",
"space_storage",
"space_sleep_time",
"space_secrets",
"space_variables",
]
json_keys = ["hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"]
values = [space_hardware, space_storage, space_sleep_time, space_secrets, space_variables]
if repo_type == "space":
json.update({k: v for k, v in zip(json_keys, values) if v is not None})
else:
provided_space_args = [key for key, value in zip(function_args, values) if value is not None]
if provided_space_args:
warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.")
if getattr(self, "_lfsmultipartthresh", None):
# Testing purposes only.
# See https://github.com/huggingface/huggingface_hub/pull/733/files#r820604472
json["lfsmultipartthresh"] = self._lfsmultipartthresh # type: ignore
headers = self._build_hf_headers(token=token, is_write_action=True)
while True:
r = get_session().post(path, headers=headers, json=json)
if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text:
# Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to
# concurrently create repos on the Hub for a same user. This is rarely an issue, except when running
# tests. To avoid any inconvenience, we retry to create the repo for this specific error.
# NOTE: This could have being fixed directly in the tests but adding it here should fixed CIs for all
# dependent libraries.
# NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism.
logger.debug("Create repo failed due to a concurrency issue. Retrying...")
continue
break
try:
hf_raise_for_status(r)
except HTTPError as err:
if exist_ok and err.response.status_code == 409:
# Repo already exists and `exist_ok=True`
pass
elif exist_ok and err.response.status_code == 403:
# No write permission on the namespace but repo might already exist
try:
self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token)
if repo_type is None or repo_type == REPO_TYPE_MODEL:
return RepoUrl(f"{self.endpoint}/{repo_id}")
return RepoUrl(f"{self.endpoint}/{repo_type}/{repo_id}")
except HfHubHTTPError:
raise
else:
raise
d = r.json()
return RepoUrl(d["url"], endpoint=self.endpoint)
@validate_hf_hub_args
def delete_repo(
self,
repo_id: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
missing_ok: bool = False,
) -> None:
"""
Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model.
missing_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo does not exist.
Raises:
- [`~utils.RepositoryNotFoundError`]
If the repository to delete from cannot be found and `missing_ok` is set to False (default).
"""
organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
path = f"{self.endpoint}/api/repos/delete"
if repo_type not in REPO_TYPES:
raise ValueError("Invalid repo type")
json = {"name": name, "organization": organization}
if repo_type is not None:
json["type"] = repo_type
headers = self._build_hf_headers(token=token, is_write_action=True)
r = get_session().delete(path, headers=headers, json=json)
try:
hf_raise_for_status(r)
except RepositoryNotFoundError:
if not missing_ok:
raise
@validate_hf_hub_args
def update_repo_visibility(
self,
repo_id: str,
private: bool = False,
*,
token: Optional[str] = None,
organization: Optional[str] = None,
repo_type: Optional[str] = None,
name: Optional[str] = None,
) -> Dict[str, bool]:
"""Update the visibility setting of a repository.
Args:
repo_id (`str`, *optional*):
A namespace (user or an organization) and a repo name separated
by a `/`.
private (`bool`, *optional*, defaults to `False`):
Whether the model repo should be private.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns:
The HTTP response in json.
<Tip>
Raises the following errors:
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
if repo_type not in REPO_TYPES:
raise ValueError("Invalid repo type")
organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id)
if organization is None:
namespace = self.whoami(token)["name"]
else:
namespace = organization
if repo_type is None:
repo_type = REPO_TYPE_MODEL # default repo type
r = get_session().put(
url=f"{self.endpoint}/api/{repo_type}s/{namespace}/{name}/settings",
headers=self._build_hf_headers(token=token, is_write_action=True),
json={"private": private},
)
hf_raise_for_status(r)
return r.json()
def move_repo(
self,
from_id: str,
to_id: str,
*,
repo_type: Optional[str] = None,
token: Optional[str] = None,
):
"""
Moving a repository from namespace1/repo_name1 to namespace2/repo_name2
Note there are certain limitations. For more information about moving
repositories, please see
https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.
Args:
from_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`. Original repository identifier.
to_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`. Final repository identifier.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
<Tip>
Raises the following errors:
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
if len(from_id.split("/")) != 2:
raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)")
if len(to_id.split("/")) != 2:
raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)")
if repo_type is None:
repo_type = REPO_TYPE_MODEL # Hub won't accept `None`.
json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type}
path = f"{self.endpoint}/api/repos/move"
headers = self._build_hf_headers(token=token, is_write_action=True)
r = get_session().post(path, headers=headers, json=json)
try:
hf_raise_for_status(r)
except HfHubHTTPError as e:
e.append_to_message(
"\nFor additional documentation please see"
" https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo."
)
raise
@overload
def create_commit( # type: ignore
self,
repo_id: str,
operations: Iterable[CommitOperation],
*,
commit_message: str,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
num_threads: int = 5,
parent_commit: Optional[str] = None,
run_as_future: Literal[False] = ...,
) -> CommitInfo:
...
@overload
def create_commit(
self,
repo_id: str,
operations: Iterable[CommitOperation],
*,
commit_message: str,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
num_threads: int = 5,
parent_commit: Optional[str] = None,
run_as_future: Literal[True] = ...,
) -> Future[CommitInfo]:
...
@validate_hf_hub_args
@future_compatible
def create_commit(
self,
repo_id: str,
operations: Iterable[CommitOperation],
*,
commit_message: str,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
num_threads: int = 5,
parent_commit: Optional[str] = None,
run_as_future: bool = False,
) -> Union[CommitInfo, Future[CommitInfo]]:
"""
Creates a commit in the given repo, deleting & uploading files as needed.
<Tip warning={true}>
The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects
for multiple commits.
</Tip>
<Tip warning={true}>
`create_commit` assumes that the repo already exists on the Hub. If you get a
Client error 404, please make sure you are authenticated and that `repo_id` and
`repo_type` are set correctly. If repo does not exist, create it first using
[`~hf_api.create_repo`].
</Tip>
<Tip warning={true}>
`create_commit` is limited to 25k LFS files and a 1GB payload for regular files.
</Tip>
Args:
repo_id (`str`):
The repository in which the commit will be created, for example:
`"username/custom_transformers"`
operations (`Iterable` of [`~hf_api.CommitOperation`]):
An iterable of operations to include in the commit, either:
- [`~hf_api.CommitOperationAdd`] to upload a file
- [`~hf_api.CommitOperationDelete`] to delete a file
- [`~hf_api.CommitOperationCopy`] to copy a file
Operation objects will be mutated to include information relative to the upload. Do not reuse the
same objects for multiple commits.
commit_message (`str`):
The summary (first line) of the commit that will be created.
commit_description (`str`, *optional*):
The description of the commit that will be created
token (`str`, *optional*):
Authentication token, obtained with `HfApi.login` method. Will
default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
num_threads (`int`, *optional*):
Number of concurrent threads for uploading files. Defaults to 5.
Setting it to 2 means at most 2 files will be uploaded concurrently.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string.
Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`,
the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr`
is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit`
ensures the repo has not changed before committing the changes, and can be especially useful
if the repo is updated / committed to concurrently.
run_as_future (`bool`, *optional*):
Whether or not to run this method in the background. Background jobs are run sequentially without
blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
object. Defaults to `False`.
Returns:
[`CommitInfo`] or `Future`:
Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
contain the result when executed.
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If commit message is empty.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If parent commit is not a valid commit OID.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If the Hub API returns an HTTP 400 error (bad request)
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `create_pr` is `True` and revision is neither `None` nor `"main"`.
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
"""
if parent_commit is not None and not REGEX_COMMIT_OID.fullmatch(parent_commit):
raise ValueError(
f"`parent_commit` is not a valid commit OID. It must match the following regex: {REGEX_COMMIT_OID}"
)
if commit_message is None or len(commit_message) == 0:
raise ValueError("`commit_message` can't be empty, please pass a value.")
commit_description = commit_description if commit_description is not None else ""
repo_type = repo_type if repo_type is not None else REPO_TYPE_MODEL
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
unquoted_revision = revision or DEFAULT_REVISION
revision = quote(unquoted_revision, safe="")
create_pr = create_pr if create_pr is not None else False
operations = list(operations)
additions = [op for op in operations if isinstance(op, CommitOperationAdd)]
copies = [op for op in operations if isinstance(op, CommitOperationCopy)]
nb_additions = len(additions)
nb_copies = len(copies)
nb_deletions = len(operations) - nb_additions - nb_copies
for addition in additions:
if addition._is_committed:
raise ValueError(
f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a"
" new CommitOperationAdd object if you want to create a new commit."
)
logger.debug(
f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copie(s) and"
f" {nb_deletions} deletion(s)."
)
# If updating twice the same file or update then delete a file in a single commit
_warn_on_overwriting_operations(operations)
self.preupload_lfs_files(
repo_id=repo_id,
additions=additions,
token=token,
repo_type=repo_type,
revision=unquoted_revision, # first-class methods take unquoted revision
create_pr=create_pr,
num_threads=num_threads,
free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users
)
files_to_copy = _fetch_lfs_files_to_copy(
copies=copies,
repo_type=repo_type,
repo_id=repo_id,
token=token or self.token,
revision=revision,
endpoint=self.endpoint,
)
commit_payload = _prepare_commit_payload(
operations=operations,
files_to_copy=files_to_copy,
commit_message=commit_message,
commit_description=commit_description,
parent_commit=parent_commit,
)
commit_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
def _payload_as_ndjson() -> Iterable[bytes]:
for item in commit_payload:
yield json.dumps(item).encode()
yield b"\n"
headers = {
# See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
"Content-Type": "application/x-ndjson",
**self._build_hf_headers(token=token, is_write_action=True),
}
data = b"".join(_payload_as_ndjson())
params = {"create_pr": "1"} if create_pr else None
try:
commit_resp = get_session().post(url=commit_url, headers=headers, data=data, params=params)
hf_raise_for_status(commit_resp, endpoint_name="commit")
except RepositoryNotFoundError as e:
e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
raise
except EntryNotFoundError as e:
if nb_deletions > 0 and "A file with this name doesn't exist" in str(e):
e.append_to_message(
"\nMake sure to differentiate file and folder paths in delete"
" operations with a trailing '/' or using `is_folder=True/False`."
)
raise
# Mark additions as committed (cannot be reused in another commit)
for addition in additions:
addition._is_committed = True
commit_data = commit_resp.json()
return CommitInfo(
commit_url=commit_data["commitUrl"],
commit_message=commit_message,
commit_description=commit_description,
oid=commit_data["commitOid"],
pr_url=commit_data["pullRequestUrl"] if create_pr else None,
)
@experimental
@validate_hf_hub_args
def create_commits_on_pr(
self,
*,
repo_id: str,
addition_commits: List[List[CommitOperationAdd]],
deletion_commits: List[List[CommitOperationDelete]],
commit_message: str,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
merge_pr: bool = True,
num_threads: int = 5, # TODO: use to multithread uploads
verbose: bool = False,
) -> str:
"""Push changes to the Hub in multiple commits.
Commits are pushed to a draft PR branch. If the upload fails or gets interrupted, it can be resumed. Progress
is tracked in the PR description. At the end of the process, the PR is set as open and the title is updated to
match the initial commit message. If `merge_pr=True` is passed, the PR is merged automatically.
All deletion commits are pushed first, followed by the addition commits. The order of the commits is not
guaranteed as we might implement parallel commits in the future. Be sure that your are not updating several
times the same file.
<Tip warning={true}>
`create_commits_on_pr` is experimental. Its API and behavior is subject to change in the future without prior notice.
</Tip>
<Tip warning={true}>
`create_commits_on_pr` assumes that the repo already exists on the Hub. If you get a Client error 404, please
make sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist,
create it first using [`~hf_api.create_repo`].
</Tip>
Args:
repo_id (`str`):
The repository in which the commits will be pushed. Example: `"username/my-cool-model"`.
addition_commits (`List` of `List` of [`~hf_api.CommitOperationAdd`]):
A list containing lists of [`~hf_api.CommitOperationAdd`]. Each sublist will result in a commit on the
PR.
deletion_commits
A list containing lists of [`~hf_api.CommitOperationDelete`]. Each sublist will result in a commit on
the PR. Deletion commits are pushed before addition commits.
commit_message (`str`):
The summary (first line) of the commit that will be created. Will also be the title of the PR.
commit_description (`str`, *optional*):
The description of the commit that will be created. The description will be added to the PR.
token (`str`, *optional*):
Authentication token, obtained with `HfApi.login` method. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
a model. Default is `None`.
merge_pr (`bool`):
If set to `True`, the Pull Request is merged at the end of the process. Defaults to `True`.
num_threads (`int`, *optional*):
Number of concurrent threads for uploading files. Defaults to 5.
verbose (`bool`):
If set to `True`, process will run on verbose mode i.e. print information about the ongoing tasks.
Defaults to `False`.
Returns:
`str`: URL to the created PR.
Example:
```python
>>> from huggingface_hub import HfApi, plan_multi_commits
>>> addition_commits, deletion_commits = plan_multi_commits(
... operations=[
... CommitOperationAdd(...),
... CommitOperationAdd(...),
... CommitOperationDelete(...),
... CommitOperationDelete(...),
... CommitOperationAdd(...),
... ],
... )
>>> HfApi().create_commits_on_pr(
... repo_id="my-cool-model",
... addition_commits=addition_commits,
... deletion_commits=deletion_commits,
... (...)
... verbose=True,
... )
```
Raises:
[`MultiCommitException`]:
If an unexpected issue occur in the process: empty commits, unexpected commits in a PR, unexpected PR
description, etc.
"""
logger = logging.get_logger(__name__ + ".create_commits_on_pr")
if verbose:
logger.setLevel("INFO")
# 1. Get strategy ID
logger.info(
f"Will create {len(deletion_commits)} deletion commit(s) and {len(addition_commits)} addition commit(s),"
f" totalling {sum(len(ops) for ops in addition_commits+deletion_commits)} atomic operations."
)
strategy = MultiCommitStrategy(
addition_commits=[MultiCommitStep(operations=operations) for operations in addition_commits], # type: ignore
deletion_commits=[MultiCommitStep(operations=operations) for operations in deletion_commits], # type: ignore
)
logger.info(f"Multi-commits strategy with ID {strategy.id}.")
# 2. Get or create a PR with this strategy ID
for discussion in self.get_repo_discussions(repo_id=repo_id, repo_type=repo_type, token=token):
# search for a draft PR with strategy ID
if discussion.is_pull_request and discussion.status == "draft" and strategy.id in discussion.title:
pr = self.get_discussion_details(
repo_id=repo_id, discussion_num=discussion.num, repo_type=repo_type, token=token
)
logger.info(f"PR already exists: {pr.url}. Will resume process where it stopped.")
break
else:
# did not find a PR matching the strategy ID
pr = multi_commit_create_pull_request(
self,
repo_id=repo_id,
commit_message=commit_message,
commit_description=commit_description,
strategy=strategy,
token=token,
repo_type=repo_type,
)
logger.info(f"New PR created: {pr.url}")
# 3. Parse PR description to check consistency with strategy (e.g. same commits are scheduled)
for event in pr.events:
if isinstance(event, DiscussionComment):
pr_comment = event
break
else:
raise MultiCommitException(f"PR #{pr.num} must have at least 1 comment")
description_commits = multi_commit_parse_pr_description(pr_comment.content)
if len(description_commits) != len(strategy.all_steps):
raise MultiCommitException(
f"Corrupted multi-commit PR #{pr.num}: got {len(description_commits)} steps in"
f" description but {len(strategy.all_steps)} in strategy."
)
for step_id in strategy.all_steps:
if step_id not in description_commits:
raise MultiCommitException(
f"Corrupted multi-commit PR #{pr.num}: expected step {step_id} but didn't find"
f" it (have {', '.join(description_commits)})."
)
# 4. Retrieve commit history (and check consistency)
commits_on_main_branch = {
commit.commit_id
for commit in self.list_repo_commits(
repo_id=repo_id, repo_type=repo_type, token=token, revision=DEFAULT_REVISION
)
}
pr_commits = [
commit
for commit in self.list_repo_commits(
repo_id=repo_id, repo_type=repo_type, token=token, revision=pr.git_reference
)
if commit.commit_id not in commits_on_main_branch
]
if len(pr_commits) > 0:
logger.info(f"Found {len(pr_commits)} existing commits on the PR.")
# At this point `pr_commits` is a list of commits pushed to the PR. We expect all of these commits (if any) to have
# a step_id as title. We raise exception if an unexpected commit has been pushed.
if len(pr_commits) > len(strategy.all_steps):
raise MultiCommitException(
f"Corrupted multi-commit PR #{pr.num}: scheduled {len(strategy.all_steps)} steps but"
f" {len(pr_commits)} commits have already been pushed to the PR."
)
# Check which steps are already completed
remaining_additions = {step.id: step for step in strategy.addition_commits}
remaining_deletions = {step.id: step for step in strategy.deletion_commits}
for commit in pr_commits:
if commit.title in remaining_additions:
step = remaining_additions.pop(commit.title)
step.completed = True
elif commit.title in remaining_deletions:
step = remaining_deletions.pop(commit.title)
step.completed = True
if len(remaining_deletions) > 0 and len(remaining_additions) < len(strategy.addition_commits):
raise MultiCommitException(
f"Corrupted multi-commit PR #{pr.num}: some addition commits have already been pushed to the PR but"
" deletion commits are not all completed yet."
)
nb_remaining = len(remaining_deletions) + len(remaining_additions)
if len(pr_commits) > 0:
logger.info(
f"{nb_remaining} commits remaining ({len(remaining_deletions)} deletion commits and"
f" {len(remaining_additions)} addition commits)"
)
# 5. Push remaining commits to the PR + update description
# TODO: multi-thread this
for step in list(remaining_deletions.values()) + list(remaining_additions.values()):
# Push new commit
self.create_commit(
repo_id=repo_id,
repo_type=repo_type,
token=token,
commit_message=step.id,
revision=pr.git_reference,
num_threads=num_threads,
operations=step.operations,
create_pr=False,
)
step.completed = True
nb_remaining -= 1
logger.info(f" step {step.id} completed (still {nb_remaining} to go).")
# Update PR description
self.edit_discussion_comment(
repo_id=repo_id,
repo_type=repo_type,
token=token,
discussion_num=pr.num,
comment_id=pr_comment.id,
new_content=multi_commit_generate_comment(
commit_message=commit_message, commit_description=commit_description, strategy=strategy
),
)
logger.info("All commits have been pushed.")
# 6. Update PR (and merge)
self.rename_discussion(
repo_id=repo_id,
repo_type=repo_type,
token=token,
discussion_num=pr.num,
new_title=commit_message,
)
self.change_discussion_status(
repo_id=repo_id,
repo_type=repo_type,
token=token,
discussion_num=pr.num,
new_status="open",
comment=MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE,
)
logger.info("PR is now open for reviews.")
if merge_pr: # User don't want a PR => merge it
try:
self.merge_pull_request(
repo_id=repo_id,
repo_type=repo_type,
token=token,
discussion_num=pr.num,
comment=MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE,
)
logger.info("PR has been automatically merged (`merge_pr=True` was passed).")
except BadRequestError as error:
if error.server_message is not None and "no associated changes" in error.server_message:
# PR cannot be merged as no changes are associated. We close the PR without merging with a comment to
# explain.
self.change_discussion_status(
repo_id=repo_id,
repo_type=repo_type,
token=token,
discussion_num=pr.num,
comment=MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE,
new_status="closed",
)
logger.warning("Couldn't merge the PR: no associated changes.")
else:
# PR cannot be merged for another reason (conflicting files for example). We comment the PR to explain
# and re-raise the exception.
self.comment_discussion(
repo_id=repo_id,
repo_type=repo_type,
token=token,
discussion_num=pr.num,
comment=MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE.format(
error_message=error.server_message
),
)
raise MultiCommitException(
f"Couldn't merge Pull Request in multi-commit: {error.server_message}"
) from error
return pr.url
def preupload_lfs_files(
self,
repo_id: str,
additions: Iterable[CommitOperationAdd],
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
num_threads: int = 5,
free_memory: bool = True,
gitignore_content: Optional[str] = None,
):
"""Pre-upload LFS files to S3 in preparation on a future commit.
This method is useful if you are generating the files to upload on-the-fly and you don't want to store them
in memory before uploading them all at once.
<Tip warning={true}>
This is a power-user method. You shouldn't need to call it directly to make a normal commit.
Use [`create_commit`] directly instead.
</Tip>
<Tip warning={true}>
Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be
removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same
objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the
commit operation object, pass `free_memory=False`.
</Tip>
Args:
repo_id (`str`):
The repository in which you will commit the files, for example: `"username/custom_transformers"`.
operations (`Iterable` of [`CommitOperationAdd`]):
The list of files to upload. Warning: the objects in this list will be mutated to include information
relative to the upload. Do not reuse the same objects for multiple commits.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`).
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
create_pr (`boolean`, *optional*):
Whether or not you plan to create a Pull Request with that commit. Defaults to `False`.
num_threads (`int`, *optional*):
Number of concurrent threads for uploading files. Defaults to 5.
Setting it to 2 means at most 2 files will be uploaded concurrently.
gitignore_content (`str`, *optional*):
The content of the `.gitignore` file to know which files should be ignored. The order of priority
is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
(if any).
Example:
```py
>>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
>>> repo_id = create_repo("test_preupload").repo_id
# Generate and preupload LFS files one by one
>>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
>>> for i in range(5):
... content = ... # generate binary content
... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
... operations.append(addition)
# Create commit
>>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")
```
"""
repo_type = repo_type if repo_type is not None else REPO_TYPE_MODEL
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION
create_pr = create_pr if create_pr is not None else False
# Check if a `gitignore` file is being committed to the Hub.
additions = list(additions)
if gitignore_content is None:
for addition in additions:
if addition.path_in_repo == ".gitignore":
with addition.as_file() as f:
gitignore_content = f.read().decode()
break
# Filter out already uploaded files
new_additions = [addition for addition in additions if not addition._is_uploaded]
# Check which new files are LFS
try:
_fetch_upload_modes(
additions=new_additions,
repo_type=repo_type,
repo_id=repo_id,
token=token or self.token,
revision=revision,
endpoint=self.endpoint,
create_pr=create_pr or False,
gitignore_content=gitignore_content,
)
except RepositoryNotFoundError as e:
e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
raise
# Filter out regular files
new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"]
# Filter out files listed in .gitignore
new_lfs_additions_to_upload = []
for addition in new_lfs_additions:
if addition._should_ignore:
logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).")
else:
new_lfs_additions_to_upload.append(addition)
if len(new_lfs_additions) != len(new_lfs_additions_to_upload):
logger.info(
f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) "
"(ignored by gitignore file)."
)
# Upload new LFS files
_upload_lfs_files(
additions=new_lfs_additions_to_upload,
repo_type=repo_type,
repo_id=repo_id,
token=token or self.token,
endpoint=self.endpoint,
num_threads=num_threads,
# If `create_pr`, we don't want to check user permission on the revision as users with read permission
# should still be able to create PRs even if they don't have write permission on the target branch of the
# PR (i.e. `revision`).
revision=revision if not create_pr else None,
)
for addition in new_lfs_additions_to_upload:
addition._is_uploaded = True
if free_memory:
addition.path_or_fileobj = b""
@overload
def upload_file( # type: ignore
self,
*,
path_or_fileobj: Union[str, Path, bytes, BinaryIO],
path_in_repo: str,
repo_id: str,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
run_as_future: Literal[False] = ...,
) -> CommitInfo:
...
@overload
def upload_file(
self,
*,
path_or_fileobj: Union[str, Path, bytes, BinaryIO],
path_in_repo: str,
repo_id: str,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
run_as_future: Literal[True] = ...,
) -> Future[CommitInfo]:
...
@validate_hf_hub_args
@future_compatible
def upload_file(
self,
*,
path_or_fileobj: Union[str, Path, bytes, BinaryIO],
path_in_repo: str,
repo_id: str,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
run_as_future: bool = False,
) -> Union[CommitInfo, Future[CommitInfo]]:
"""
Upload a local file (up to 50 GB) to the given repo. The upload is done
through a HTTP post request, and doesn't require git or git-lfs to be
installed.
Args:
path_or_fileobj (`str`, `Path`, `bytes`, or `IO`):
Path to a file on the local machine or binary data stream /
fileobj / buffer.
path_in_repo (`str`):
Relative filepath in the repo, for example:
`"checkpoints/1fec34a/weights.bin"`
repo_id (`str`):
The repository to which the file will be uploaded, for example:
`"username/custom_transformers"`
token (`str`, *optional*):
Authentication token, obtained with `HfApi.login` method. Will
default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit
commit_description (`str` *optional*)
The description of the generated commit
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
run_as_future (`bool`, *optional*):
Whether or not to run this method in the background. Background jobs are run sequentially without
blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
object. Defaults to `False`.
Returns:
[`CommitInfo`] or `Future`:
Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
contain the result when executed.
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
</Tip>
<Tip warning={true}>
`upload_file` assumes that the repo already exists on the Hub. If you get a
Client error 404, please make sure you are authenticated and that `repo_id` and
`repo_type` are set correctly. If repo does not exist, create it first using
[`~hf_api.create_repo`].
</Tip>
Example:
```python
>>> from huggingface_hub import upload_file
>>> with open("./local/filepath", "rb") as fobj:
... upload_file(
... path_or_fileobj=fileobj,
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-dataset",
... repo_type="dataset",
... token="my_token",
... )
"https://huggingface.co/datasets/username/my-dataset/blob/main/remote/file/path.h5"
>>> upload_file(
... path_or_fileobj=".\\\\local\\\\file\\\\path",
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-model",
... token="my_token",
... )
"https://huggingface.co/username/my-model/blob/main/remote/file/path.h5"
>>> upload_file(
... path_or_fileobj=".\\\\local\\\\file\\\\path",
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-model",
... token="my_token",
... create_pr=True,
... )
"https://huggingface.co/username/my-model/blob/refs%2Fpr%2F1/remote/file/path.h5"
```
"""
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
commit_message = (
commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub"
)
operation = CommitOperationAdd(
path_or_fileobj=path_or_fileobj,
path_in_repo=path_in_repo,
)
commit_info = self.create_commit(
repo_id=repo_id,
repo_type=repo_type,
operations=[operation],
commit_message=commit_message,
commit_description=commit_description,
token=token,
revision=revision,
create_pr=create_pr,
parent_commit=parent_commit,
)
if commit_info.pr_url is not None:
revision = quote(_parse_revision_from_pr_url(commit_info.pr_url), safe="")
if repo_type in REPO_TYPES_URL_PREFIXES:
repo_id = REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
revision = revision if revision is not None else DEFAULT_REVISION
return CommitInfo(
commit_url=commit_info.commit_url,
commit_message=commit_info.commit_message,
commit_description=commit_info.commit_description,
oid=commit_info.oid,
pr_url=commit_info.pr_url,
# Similar to `hf_hub_url` but it's "blob" instead of "resolve"
# TODO: remove this in v1.0
_url=f"{self.endpoint}/{repo_id}/blob/{revision}/{path_in_repo}",
)
@overload
def upload_folder( # type: ignore
self,
*,
repo_id: str,
folder_path: Union[str, Path],
path_in_repo: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
delete_patterns: Optional[Union[List[str], str]] = None,
multi_commits: Literal[False] = ...,
multi_commits_verbose: bool = False,
run_as_future: Literal[False] = ...,
) -> CommitInfo:
...
@overload
def upload_folder( # type: ignore
self,
*,
repo_id: str,
folder_path: Union[str, Path],
path_in_repo: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
delete_patterns: Optional[Union[List[str], str]] = None,
multi_commits: Literal[True] = ...,
multi_commits_verbose: bool = False,
run_as_future: Literal[False] = ...,
) -> str: # Only the PR url in multi-commits mode
...
@overload
def upload_folder( # type: ignore
self,
*,
repo_id: str,
folder_path: Union[str, Path],
path_in_repo: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
delete_patterns: Optional[Union[List[str], str]] = None,
multi_commits: Literal[False] = ...,
multi_commits_verbose: bool = False,
run_as_future: Literal[True] = ...,
) -> Future[CommitInfo]:
...
@overload
def upload_folder(
self,
*,
repo_id: str,
folder_path: Union[str, Path],
path_in_repo: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
delete_patterns: Optional[Union[List[str], str]] = None,
multi_commits: Literal[True] = ...,
multi_commits_verbose: bool = False,
run_as_future: Literal[True] = ...,
) -> Future[str]: # Only the PR url in multi-commits mode
...
@validate_hf_hub_args
@future_compatible
def upload_folder(
self,
*,
repo_id: str,
folder_path: Union[str, Path],
path_in_repo: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
delete_patterns: Optional[Union[List[str], str]] = None,
multi_commits: bool = False,
multi_commits_verbose: bool = False,
run_as_future: bool = False,
) -> Union[CommitInfo, str, Future[CommitInfo], Future[str]]:
"""
Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or
git-lfs to be installed.
The structure of the folder will be preserved. Files with the same name already present in the repository will
be overwritten. Others will be left untouched.
Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters
accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as
documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and
`ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded.
Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for
`allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths
relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")`
will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted
even if it matches the patterns.
Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore`
file is not taken into account.
Uses `HfApi.create_commit` under the hood.
Args:
repo_id (`str`):
The repository to which the file will be uploaded, for example:
`"username/custom_transformers"`
folder_path (`str` or `Path`):
Path to the folder to upload on the local file system
path_in_repo (`str`, *optional*):
Relative path of the directory in the repo, for example:
`"checkpoints/1fec34a/results"`. Will default to the root folder of the repository.
token (`str`, *optional*):
Authentication token, obtained with `HfApi.login` method. Will
default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to:
`f"Upload {path_in_repo} with huggingface_hub"`
commit_description (`str` *optional*):
The description of the generated commit
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not
set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened
against this branch. If `revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server. If both `multi_commits` and `create_pr` are True,
the PR created in the multi-commit process is kept opened.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
allow_patterns (`List[str]` or `str`, *optional*):
If provided, only files matching at least one pattern are uploaded.
ignore_patterns (`List[str]` or `str`, *optional*):
If provided, files matching any of the patterns are not uploaded.
delete_patterns (`List[str]` or `str`, *optional*):
If provided, remote files matching any of the patterns will be deleted from the repo while committing
new files. This is useful if you don't know which files have already been uploaded.
Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern.
multi_commits (`bool`):
If True, changes are pushed to a PR using a multi-commit process. Defaults to `False`.
multi_commits_verbose (`bool`):
If True and `multi_commits` is used, more information will be displayed to the user.
run_as_future (`bool`, *optional*):
Whether or not to run this method in the background. Background jobs are run sequentially without
blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects)
object. Defaults to `False`.
Returns:
[`CommitInfo`] or `Future`:
Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit
url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will
contain the result when executed.
[`str`] or `Future`:
If `multi_commits=True`, returns the url of the PR created to push the changes. If `run_as_future=True`
is passed, returns a Future object which will contain the result when executed.
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
</Tip>
<Tip warning={true}>
`upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make
sure you are authenticated and that `repo_id` and `repo_type` are set correctly. If repo does not exist, create
it first using [`~hf_api.create_repo`].
</Tip>
<Tip warning={true}>
`multi_commits` is experimental. Its API and behavior is subject to change in the future without prior notice.
</Tip>
Example:
```python
# Upload checkpoints folder except the log files
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... ignore_patterns="**/logs/*.txt",
... )
# "https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints"
# Upload checkpoints folder including logs while deleting existing logs from the repo
# Useful if you don't know exactly which log files have already being pushed
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... delete_patterns="**/logs/*.txt",
... )
"https://huggingface.co/datasets/username/my-dataset/tree/main/remote/experiment/checkpoints"
# Upload checkpoints folder while creating a PR
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... create_pr=True,
... )
"https://huggingface.co/datasets/username/my-dataset/tree/refs%2Fpr%2F1/remote/experiment/checkpoints"
```
"""
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if multi_commits:
if revision is not None and revision != DEFAULT_REVISION:
raise ValueError("Cannot use `multi_commit` to commit changes other than the main branch.")
# By default, upload folder to the root directory in repo.
if path_in_repo is None:
path_in_repo = ""
# Do not upload .git folder
if ignore_patterns is None:
ignore_patterns = []
elif isinstance(ignore_patterns, str):
ignore_patterns = [ignore_patterns]
ignore_patterns += IGNORE_GIT_FOLDER_PATTERNS
delete_operations = self._prepare_upload_folder_deletions(
repo_id=repo_id,
repo_type=repo_type,
revision=DEFAULT_REVISION if create_pr else revision,
token=token,
path_in_repo=path_in_repo,
delete_patterns=delete_patterns,
)
add_operations = _prepare_upload_folder_additions(
folder_path,
path_in_repo,
allow_patterns=allow_patterns,
ignore_patterns=ignore_patterns,
)
# Optimize operations: if some files will be overwritten, we don't need to delete them first
if len(add_operations) > 0:
added_paths = set(op.path_in_repo for op in add_operations)
delete_operations = [
delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths
]
commit_operations = delete_operations + add_operations
commit_message = commit_message or "Upload folder using huggingface_hub"
if multi_commits:
addition_commits, deletion_commits = plan_multi_commits(operations=commit_operations)
pr_url = self.create_commits_on_pr(
repo_id=repo_id,
repo_type=repo_type,
addition_commits=addition_commits,
deletion_commits=deletion_commits,
commit_message=commit_message,
commit_description=commit_description,
token=token,
merge_pr=not create_pr,
verbose=multi_commits_verbose,
)
# Defining a CommitInfo object is not really relevant in this case
# Let's return early with pr_url only (as string).
return pr_url
commit_info = self.create_commit(
repo_type=repo_type,
repo_id=repo_id,
operations=commit_operations,
commit_message=commit_message,
commit_description=commit_description,
token=token,
revision=revision,
create_pr=create_pr,
parent_commit=parent_commit,
)
# Create url to uploaded folder (for legacy return value)
if create_pr and commit_info.pr_url is not None:
revision = quote(_parse_revision_from_pr_url(commit_info.pr_url), safe="")
if repo_type in REPO_TYPES_URL_PREFIXES:
repo_id = REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
revision = revision if revision is not None else DEFAULT_REVISION
return CommitInfo(
commit_url=commit_info.commit_url,
commit_message=commit_info.commit_message,
commit_description=commit_info.commit_description,
oid=commit_info.oid,
pr_url=commit_info.pr_url,
# Similar to `hf_hub_url` but it's "tree" instead of "resolve"
# TODO: remove this in v1.0
_url=f"{self.endpoint}/{repo_id}/tree/{revision}/{path_in_repo}",
)
@validate_hf_hub_args
def delete_file(
self,
path_in_repo: str,
repo_id: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
) -> CommitInfo:
"""
Deletes a file in the given repo.
Args:
path_in_repo (`str`):
Relative filepath in the repo, for example:
`"checkpoints/1fec34a/weights.bin"`
repo_id (`str`):
The repository from which the file will be deleted, for example:
`"username/custom_transformers"`
token (`str`, *optional*):
Authentication token, obtained with `HfApi.login` method. Will
default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or
space, `None` or `"model"` if in a model. Default is `None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to
`f"Delete {path_in_repo} with huggingface_hub"`.
commit_description (`str` *optional*)
The description of the generated commit
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
- [`~utils.EntryNotFoundError`]
If the file to download cannot be found.
</Tip>
"""
commit_message = (
commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub"
)
operations = [CommitOperationDelete(path_in_repo=path_in_repo)]
return self.create_commit(
repo_id=repo_id,
repo_type=repo_type,
token=token,
operations=operations,
revision=revision,
commit_message=commit_message,
commit_description=commit_description,
create_pr=create_pr,
parent_commit=parent_commit,
)
@validate_hf_hub_args
def delete_folder(
self,
path_in_repo: str,
repo_id: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
create_pr: Optional[bool] = None,
parent_commit: Optional[str] = None,
) -> CommitInfo:
"""
Deletes a folder in the given repo.
Simple wrapper around [`create_commit`] method.
Args:
path_in_repo (`str`):
Relative folder path in the repo, for example: `"checkpoints/1fec34a"`.
repo_id (`str`):
The repository from which the folder will be deleted, for example:
`"username/custom_transformers"`
token (`str`, *optional*):
Authentication token, obtained with `HfApi.login` method. Will default
to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the folder is in a dataset or
space, `None` or `"model"` if in a model. Default is `None`.
revision (`str`, *optional*):
The git revision to commit from. Defaults to the head of the `"main"` branch.
commit_message (`str`, *optional*):
The summary / title / first line of the generated commit. Defaults to
`f"Delete folder {path_in_repo} with huggingface_hub"`.
commit_description (`str` *optional*)
The description of the generated commit.
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request with that commit. Defaults to `False`.
If `revision` is not set, PR is opened against the `"main"` branch. If
`revision` is set and is a branch, PR is opened against this branch. If
`revision` is set and is not a branch name (example: a commit oid), an
`RevisionNotFoundError` is returned by the server.
parent_commit (`str`, *optional*):
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
especially useful if the repo is updated / committed to concurrently.
"""
return self.create_commit(
repo_id=repo_id,
repo_type=repo_type,
token=token,
operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)],
revision=revision,
commit_message=(
commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub"
),
commit_description=commit_description,
create_pr=create_pr,
parent_commit=parent_commit,
)
@validate_hf_hub_args
def get_hf_file_metadata(
self,
*,
url: str,
token: Union[bool, str, None] = None,
proxies: Optional[Dict] = None,
timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT,
) -> HfFileMetadata:
"""Fetch metadata of a file versioned on the Hub for a given url.
Args:
url (`str`):
File url, for example returned by [`hf_hub_url`].
token (`str` or `bool`, *optional*):
A token to be used for the download.
- If `True`, the token is read from the HuggingFace config
folder.
- If `False` or `None`, no token is provided.
- If a string, it's used as the authentication token.
proxies (`dict`, *optional*):
Dictionary mapping protocol to the URL of the proxy passed to `requests.request`.
timeout (`float`, *optional*, defaults to 10):
How many seconds to wait for the server to send metadata before giving up.
Returns:
A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash.
"""
if token is None:
# Cannot do `token = token or self.token` as token can be `False`.
token = self.token
return get_hf_file_metadata(
url=url,
token=token,
proxies=proxies,
timeout=timeout,
library_name=self.library_name,
library_version=self.library_version,
user_agent=self.user_agent,
)
@validate_hf_hub_args
def hf_hub_download(
self,
repo_id: str,
filename: str,
*,
subfolder: Optional[str] = None,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
cache_dir: Union[str, Path, None] = None,
local_dir: Union[str, Path, None] = None,
local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
force_download: bool = False,
force_filename: Optional[str] = None,
proxies: Optional[Dict] = None,
etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
resume_download: bool = False,
token: Optional[Union[str, bool]] = None,
local_files_only: bool = False,
legacy_cache_layout: bool = False,
) -> str:
"""Download a given file if it's not already present in the local cache.
The new cache file layout looks like this:
- The cache directory contains one subfolder per repo_id (namespaced by repo type)
- inside each repo folder:
- refs is a list of the latest known revision => commit_hash pairs
- blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
whether they're LFS files or not)
- snapshots contains one subfolder per commit, each "commit" contains the subset of the files
that have been resolved at that particular commit. Each filename is a symlink to the blob
at that particular commit.
If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure
how you want to move those files:
- If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
is to be able to manually edit and save small files without corrupting the cache while saving disk space for
binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
environment variable.
- If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
This is optimal in term of disk usage but files must not be manually edited.
- If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
local dir. This means disk usage is not optimized.
- Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
they will be re-downloaded entirely.
```
[ 96] .
└── [ 160] models--julien-c--EsperBERTo-small
├── [ 160] blobs
│ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
│ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
│ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
├── [ 96] refs
│ └── [ 40] main
└── [ 128] snapshots
├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
│ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
│ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
└── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
└── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
```
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
filename (`str`):
The name of the file in the repo.
subfolder (`str`, *optional*):
An optional value corresponding to a folder inside the model repo.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if downloading from a dataset or space,
`None` or `"model"` if downloading from a model. Default is `None`.
revision (`str`, *optional*):
An optional Git revision id which can be a branch name, a tag, or a
commit hash.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_dir (`str` or `Path`, *optional*):
If provided, the downloaded file will be placed under this directory, either as a symlink (default) or
a regular file (see description for more details).
local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
already exists) or downloaded from the Hub and not cached. See description for more details.
force_download (`bool`, *optional*, defaults to `False`):
Whether the file should be downloaded even if it already exists in
the local cache.
proxies (`dict`, *optional*):
Dictionary mapping protocol to the URL of the proxy passed to
`requests.request`.
etag_timeout (`float`, *optional*, defaults to `10`):
When fetching ETag, how many seconds to wait for the server to send
data before giving up which is passed to `requests.request`.
resume_download (`bool`, *optional*, defaults to `False`):
If `True`, resume a previously interrupted download.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, avoid downloading the file and return the path to the
local cached file if it exists.
legacy_cache_layout (`bool`, *optional*, defaults to `False`):
If `True`, uses the legacy file cache layout i.e. just call [`hf_hub_url`]
then `cached_download`. This is deprecated as the new cache layout is
more powerful.
Returns:
Local path (string) of file or if networking is off, last version of
file cached on disk.
<Tip>
Raises the following errors:
- [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
if `token=True` and the token cannot be found.
- [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
if ETag cannot be determined.
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
- [`~utils.RevisionNotFoundError`]
If the revision to download from cannot be found.
- [`~utils.EntryNotFoundError`]
If the file to download cannot be found.
- [`~utils.LocalEntryNotFoundError`]
If network is disabled or unavailable and file is not found in cache.
</Tip>
"""
from .file_download import hf_hub_download
if token is None:
# Cannot do `token = token or self.token` as token can be `False`.
token = self.token
return hf_hub_download(
repo_id=repo_id,
filename=filename,
subfolder=subfolder,
repo_type=repo_type,
revision=revision,
endpoint=self.endpoint,
library_name=self.library_name,
library_version=self.library_version,
cache_dir=cache_dir,
local_dir=local_dir,
local_dir_use_symlinks=local_dir_use_symlinks,
user_agent=self.user_agent,
force_download=force_download,
force_filename=force_filename,
proxies=proxies,
etag_timeout=etag_timeout,
resume_download=resume_download,
token=token,
local_files_only=local_files_only,
legacy_cache_layout=legacy_cache_layout,
)
@validate_hf_hub_args
def snapshot_download(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
cache_dir: Union[str, Path, None] = None,
local_dir: Union[str, Path, None] = None,
local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
proxies: Optional[Dict] = None,
etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
resume_download: bool = False,
force_download: bool = False,
token: Optional[Union[str, bool]] = None,
local_files_only: bool = False,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
max_workers: int = 8,
tqdm_class: Optional[base_tqdm] = None,
) -> str:
"""Download repo files.
Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
to keep their actual filename relative to that folder. You can also filter which files to download using
`allow_patterns` and `ignore_patterns`.
If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure
how you want to move those files:
- If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
is to be able to manually edit and save small files without corrupting the cache while saving disk space for
binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
environment variable.
- If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
This is optimal in term of disk usage but files must not be manually edited.
- If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
local dir. This means disk usage is not optimized.
- Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
they will be re-downloaded entirely.
An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
configured. It is also not possible to filter which files to download when cloning a repository using git.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if downloading from a dataset or space,
`None` or `"model"` if downloading from a model. Default is `None`.
revision (`str`, *optional*):
An optional Git revision id which can be a branch name, a tag, or a
commit hash.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_dir (`str` or `Path`, *optional*):
If provided, the downloaded files will be placed under this directory, either as symlinks (default) or
regular files (see description for more details).
local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
already exists) or downloaded from the Hub and not cached. See description for more details.
proxies (`dict`, *optional*):
Dictionary mapping protocol to the URL of the proxy passed to
`requests.request`.
etag_timeout (`float`, *optional*, defaults to `10`):
When fetching ETag, how many seconds to wait for the server to send
data before giving up which is passed to `requests.request`.
resume_download (`bool`, *optional*, defaults to `False):
If `True`, resume a previously interrupted download.
force_download (`bool`, *optional*, defaults to `False`):
Whether the file should be downloaded even if it already exists in the local cache.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, avoid downloading the file and return the path to the
local cached file if it exists.
allow_patterns (`List[str]` or `str`, *optional*):
If provided, only files matching at least one pattern are downloaded.
ignore_patterns (`List[str]` or `str`, *optional*):
If provided, files matching any of the patterns are not downloaded.
max_workers (`int`, *optional*):
Number of concurrent threads to download files (1 thread = 1 file download).
Defaults to 8.
tqdm_class (`tqdm`, *optional*):
If provided, overwrites the default behavior for the progress bar. Passed
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
Note that the `tqdm_class` is not passed to each individual download.
Defaults to the custom HF progress bar that can be disabled by setting
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
Returns:
Local folder path (string) of repo snapshot
<Tip>
Raises the following errors:
- [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
if `token=True` and the token cannot be found.
- [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
ETag cannot be determined.
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
</Tip>
"""
from ._snapshot_download import snapshot_download
if token is None:
# Cannot do `token = token or self.token` as token can be `False`.
token = self.token
return snapshot_download(
repo_id=repo_id,
repo_type=repo_type,
revision=revision,
endpoint=self.endpoint,
cache_dir=cache_dir,
local_dir=local_dir,
local_dir_use_symlinks=local_dir_use_symlinks,
library_name=self.library_name,
library_version=self.library_version,
user_agent=self.user_agent,
proxies=proxies,
etag_timeout=etag_timeout,
resume_download=resume_download,
force_download=force_download,
token=token,
local_files_only=local_files_only,
allow_patterns=allow_patterns,
ignore_patterns=ignore_patterns,
max_workers=max_workers,
tqdm_class=tqdm_class,
)
def get_safetensors_metadata(
self,
repo_id: str,
*,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
token: Optional[str] = None,
) -> SafetensorsRepoMetadata:
"""
Parse metadata for a safetensors repo on the Hub.
We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single
safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the
metadata from the index file and then parse the metadata from each shard.
To parse metadata from a single safetensors file, use [`get_safetensors_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
filename (`str`):
The name of the file in the repo.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
model. Default is `None`.
revision (`str`, *optional*):
The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
head of the `"main"` branch.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
retrieved from the cache. If `False`, token is not sent in the request header.
Returns:
[`SafetensorsRepoMetadata`]: information related to safetensors repo.
Raises:
- [`NotASafetensorsRepoError`]: if the repo is not a safetensors repo i.e. doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file.
- [`SafetensorsParsingError`]: if a safetensors file header couldn't be parsed correctly.
Example:
```py
# Parse repo with single weights file
>>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
>>> metadata
SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
)
>>> metadata.files_metadata["model.safetensors"].metadata
{'format': 'pt'}
# Parse repo with sharded model
>>> metadata = get_safetensors_metadata("bigscience/bloom")
Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
>>> metadata
SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
72 # All safetensors files have been fetched
# Parse repo with sharded model
>>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
```
"""
if self.file_exists( # Single safetensors file => non-sharded model
repo_id=repo_id, filename=SAFETENSORS_SINGLE_FILE, repo_type=repo_type, revision=revision, token=token
):
file_metadata = self.parse_safetensors_file_metadata(
repo_id=repo_id, filename=SAFETENSORS_SINGLE_FILE, repo_type=repo_type, revision=revision, token=token
)
return SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={tensor_name: SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys()},
files_metadata={SAFETENSORS_SINGLE_FILE: file_metadata},
)
elif self.file_exists( # Multiple safetensors files => sharded with index
repo_id=repo_id, filename=SAFETENSORS_INDEX_FILE, repo_type=repo_type, revision=revision, token=token
):
# Fetch index
index_file = self.hf_hub_download(
repo_id=repo_id, filename=SAFETENSORS_INDEX_FILE, repo_type=repo_type, revision=revision, token=token
)
with open(index_file) as f:
index = json.load(f)
weight_map = index.get("weight_map", {})
# Fetch metadata per shard
files_metadata = {}
def _parse(filename: str) -> None:
files_metadata[filename] = self.parse_safetensors_file_metadata(
repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token
)
thread_map(
_parse,
set(weight_map.values()),
desc="Parse safetensors files",
tqdm_class=hf_tqdm,
)
return SafetensorsRepoMetadata(
metadata=index.get("metadata", None),
sharded=True,
weight_map=weight_map,
files_metadata=files_metadata,
)
else:
# Not a safetensors repo
raise NotASafetensorsRepoError(
f"'{repo_id}' is not a safetensors repo. Couldn't find '{SAFETENSORS_INDEX_FILE}' or '{SAFETENSORS_SINGLE_FILE}' files."
)
def parse_safetensors_file_metadata(
self,
repo_id: str,
filename: str,
*,
repo_type: Optional[str] = None,
revision: Optional[str] = None,
token: Optional[str] = None,
) -> SafetensorsFileMetadata:
"""
Parse metadata from a safetensors file on the Hub.
To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`].
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Args:
repo_id (`str`):
A user or an organization name and a repo name separated by a `/`.
filename (`str`):
The name of the file in the repo.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
model. Default is `None`.
revision (`str`, *optional*):
The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the
head of the `"main"` branch.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token). If `None` or `True` and
machine is logged in (through `huggingface-cli login` or [`~huggingface_hub.login`]), token will be
retrieved from the cache. If `False`, token is not sent in the request header.
Returns:
[`SafetensorsFileMetadata`]: information related to a safetensors file.
Raises:
- [`NotASafetensorsRepoError`]: if the repo is not a safetensors repo i.e. doesn't have either a
`model.safetensors` or a `model.safetensors.index.json` file.
- [`SafetensorsParsingError`]: if a safetensors file header couldn't be parsed correctly.
"""
url = hf_hub_url(
repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint
)
_headers = self._build_hf_headers(token=token)
# 1. Fetch first 100kb
# Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub).
# We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to
# avoid the 2nd GET in most cases.
# See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419.
response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"})
hf_raise_for_status(response)
# 2. Parse metadata size
metadata_size = struct.unpack("<Q", response.content[:8])[0]
if metadata_size > SAFETENSORS_MAX_HEADER_LENGTH:
raise SafetensorsParsingError(
f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
f"'{revision or DEFAULT_REVISION}'): safetensors header is too big. Maximum supported size is "
f"{SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})."
)
# 3.a. Get metadata from payload
if metadata_size <= 100000:
metadata_as_bytes = response.content[8 : 8 + metadata_size]
else: # 3.b. Request full metadata
response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size+7}"})
hf_raise_for_status(response)
metadata_as_bytes = response.content
# 4. Parse json header
try:
metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore"))
except json.JSONDecodeError as e:
raise SafetensorsParsingError(
f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
f"'{revision or DEFAULT_REVISION}'): header is not json-encoded string. Please make sure this is a "
"correctly formatted safetensors file."
) from e
try:
return SafetensorsFileMetadata(
metadata=metadata_as_dict.get("__metadata__", {}),
tensors={
key: TensorInfo(
dtype=tensor["dtype"],
shape=tensor["shape"],
data_offsets=tuple(tensor["data_offsets"]), # type: ignore
)
for key, tensor in metadata_as_dict.items()
if key != "__metadata__"
},
)
except (KeyError, IndexError) as e:
raise SafetensorsParsingError(
f"Failed to parse safetensors header for '{filename}' (repo '{repo_id}', revision "
f"'{revision or DEFAULT_REVISION}'): header format not recognized. Please make sure this is a correctly"
" formatted safetensors file."
) from e
@validate_hf_hub_args
def create_branch(
self,
repo_id: str,
*,
branch: str,
revision: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
exist_ok: bool = False,
) -> None:
"""
Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`).
To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`].
Args:
repo_id (`str`):
The repository in which the branch will be created.
Example: `"user/my-cool-model"`.
branch (`str`):
The name of the branch to create.
revision (`str`, *optional*):
The git revision to create the branch from. It can be a branch name or
the OID/SHA of a commit, as a hexadecimal string. Defaults to the head
of the `"main"` branch.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if creating a branch on a dataset or
space, `None` or `"model"` if tagging a model. Default is `None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if branch already exists.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.BadRequestError`]:
If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'.
[`~utils.HfHubHTTPError`]:
If the branch already exists on the repo (error 409) and `exist_ok` is
set to `False`.
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
branch = quote(branch, safe="")
# Prepare request
branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
headers = self._build_hf_headers(token=token, is_write_action=True)
payload = {}
if revision is not None:
payload["startingPoint"] = revision
# Create branch
response = get_session().post(url=branch_url, headers=headers, json=payload)
try:
hf_raise_for_status(response)
except HfHubHTTPError as e:
if not (e.response.status_code == 409 and exist_ok):
raise
@validate_hf_hub_args
def delete_branch(
self,
repo_id: str,
*,
branch: str,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> None:
"""
Delete a branch from a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a branch will be deleted.
Example: `"user/my-cool-model"`.
branch (`str`):
The name of the branch to delete.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if creating a branch on a dataset or
space, `None` or `"model"` if tagging a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.HfHubHTTPError`]:
If trying to delete a protected branch. Ex: `main` cannot be deleted.
[`~utils.HfHubHTTPError`]:
If trying to delete a branch that does not exist.
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
branch = quote(branch, safe="")
# Prepare request
branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}"
headers = self._build_hf_headers(token=token, is_write_action=True)
# Delete branch
response = get_session().delete(url=branch_url, headers=headers)
hf_raise_for_status(response)
@validate_hf_hub_args
def create_tag(
self,
repo_id: str,
*,
tag: str,
tag_message: Optional[str] = None,
revision: Optional[str] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
exist_ok: bool = False,
) -> None:
"""
Tag a given commit of a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a commit will be tagged.
Example: `"user/my-cool-model"`.
tag (`str`):
The name of the tag to create.
tag_message (`str`, *optional*):
The description of the tag to create.
revision (`str`, *optional*):
The git revision to tag. It can be a branch name or the OID/SHA of a
commit, as a hexadecimal string. Shorthands (7 first characters) are
also supported. Defaults to the head of the `"main"` branch.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if tagging a dataset or
space, `None` or `"model"` if tagging a model. Default is
`None`.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if tag already exists.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.RevisionNotFoundError`]:
If revision is not found (error 404) on the repo.
[`~utils.HfHubHTTPError`]:
If the branch already exists on the repo (error 409) and `exist_ok` is
set to `False`.
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
revision = quote(revision, safe="") if revision is not None else DEFAULT_REVISION
# Prepare request
tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}"
headers = self._build_hf_headers(token=token, is_write_action=True)
payload = {"tag": tag}
if tag_message is not None:
payload["message"] = tag_message
# Tag
response = get_session().post(url=tag_url, headers=headers, json=payload)
try:
hf_raise_for_status(response)
except HfHubHTTPError as e:
if not (e.response.status_code == 409 and exist_ok):
raise
@validate_hf_hub_args
def delete_tag(
self,
repo_id: str,
*,
tag: str,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> None:
"""
Delete a tag from a repo on the Hub.
Args:
repo_id (`str`):
The repository in which a tag will be deleted.
Example: `"user/my-cool-model"`.
tag (`str`):
The name of the tag to delete.
token (`str`, *optional*):
Authentication token. Will default to the stored token.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or
`"model"` if tagging a model. Default is `None`.
Raises:
[`~utils.RepositoryNotFoundError`]:
If repository is not found (error 404): wrong repo_id/repo_type, private
but not authenticated or repo does not exist.
[`~utils.RevisionNotFoundError`]:
If tag is not found.
"""
if repo_type is None:
repo_type = REPO_TYPE_MODEL
tag = quote(tag, safe="")
# Prepare request
tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}"
headers = self._build_hf_headers(token=token, is_write_action=True)
# Un-tag
response = get_session().delete(url=tag_url, headers=headers)
hf_raise_for_status(response)
@validate_hf_hub_args
def get_full_repo_name(
self,
model_id: str,
*,
organization: Optional[str] = None,
token: Optional[Union[bool, str]] = None,
):
"""
Returns the repository name for a given model ID and optional
organization.
Args:
model_id (`str`):
The name of the model.
organization (`str`, *optional*):
If passed, the repository name will be in the organization
namespace instead of the user namespace.
token (`bool` or `str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
If `None` or `True` and machine is logged in (through `huggingface-cli login`
or [`~huggingface_hub.login`]), token will be retrieved from the cache.
If `False`, token is not sent in the request header.
Returns:
`str`: The repository name in the user's namespace
({username}/{model_id}) if no organization is passed, and under the
organization namespace ({organization}/{model_id}) otherwise.
"""
if organization is None:
if "/" in model_id:
username = model_id.split("/")[0]
else:
username = self.whoami(token=token)["name"] # type: ignore
return f"{username}/{model_id}"
else:
return f"{organization}/{model_id}"
@validate_hf_hub_args
def get_repo_discussions(
self,
repo_id: str,
*,
author: Optional[str] = None,
discussion_type: Optional[DiscussionTypeFilter] = None,
discussion_status: Optional[DiscussionStatusFilter] = None,
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> Iterator[Discussion]:
"""
Fetches Discussions and Pull Requests for the given repo.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
author (`str`, *optional*):
Pass a value to filter by discussion author. `None` means no filter.
Default is `None`.
discussion_type (`str`, *optional*):
Set to `"pull_request"` to fetch only pull requests, `"discussion"`
to fetch only discussions. Set to `"all"` or `None` to fetch both.
Default is `None`.
discussion_status (`str`, *optional*):
Set to `"open"` (respectively `"closed"`) to fetch only open
(respectively closed) discussions. Set to `"all"` or `None`
to fetch both.
Default is `None`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if fetching from a dataset or
space, `None` or `"model"` if fetching from a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
`Iterator[Discussion]`: An iterator of [`Discussion`] objects.
Example:
Collecting all discussions of a repo in a list:
```python
>>> from huggingface_hub import get_repo_discussions
>>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))
```
Iterating over discussions of a repo:
```python
>>> from huggingface_hub import get_repo_discussions
>>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
... print(discussion.num, discussion.title)
```
"""
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
if discussion_type is not None and discussion_type not in DISCUSSION_TYPES:
raise ValueError(f"Invalid discussion_type, must be one of {DISCUSSION_TYPES}")
if discussion_status is not None and discussion_status not in DISCUSSION_STATUS:
raise ValueError(f"Invalid discussion_status, must be one of {DISCUSSION_STATUS}")
headers = self._build_hf_headers(token=token)
query_dict: Dict[str, str] = {}
if discussion_type is not None:
query_dict["type"] = discussion_type
if discussion_status is not None:
query_dict["status"] = discussion_status
if author is not None:
query_dict["author"] = author
def _fetch_discussion_page(page_index: int):
query_string = urlencode({**query_dict, "page_index": page_index})
path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions?{query_string}"
resp = get_session().get(path, headers=headers)
hf_raise_for_status(resp)
paginated_discussions = resp.json()
total = paginated_discussions["count"]
start = paginated_discussions["start"]
discussions = paginated_discussions["discussions"]
has_next = (start + len(discussions)) < total
return discussions, has_next
has_next, page_index = True, 0
while has_next:
discussions, has_next = _fetch_discussion_page(page_index=page_index)
for discussion in discussions:
yield Discussion(
title=discussion["title"],
num=discussion["num"],
author=discussion.get("author", {}).get("name", "deleted"),
created_at=parse_datetime(discussion["createdAt"]),
status=discussion["status"],
repo_id=discussion["repo"]["name"],
repo_type=discussion["repo"]["type"],
is_pull_request=discussion["isPullRequest"],
endpoint=self.endpoint,
)
page_index = page_index + 1
@validate_hf_hub_args
def get_discussion_details(
self,
repo_id: str,
discussion_num: int,
*,
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> DiscussionWithDetails:
"""Fetches a Discussion's / Pull Request 's details from the Hub.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns: [`DiscussionWithDetails`]
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
if not isinstance(discussion_num, int) or discussion_num <= 0:
raise ValueError("Invalid discussion_num, must be a positive integer")
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}"
headers = self._build_hf_headers(token=token)
resp = get_session().get(path, params={"diff": "1"}, headers=headers)
hf_raise_for_status(resp)
discussion_details = resp.json()
is_pull_request = discussion_details["isPullRequest"]
target_branch = discussion_details["changes"]["base"] if is_pull_request else None
conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None
merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None
return DiscussionWithDetails(
title=discussion_details["title"],
num=discussion_details["num"],
author=discussion_details.get("author", {}).get("name", "deleted"),
created_at=parse_datetime(discussion_details["createdAt"]),
status=discussion_details["status"],
repo_id=discussion_details["repo"]["name"],
repo_type=discussion_details["repo"]["type"],
is_pull_request=discussion_details["isPullRequest"],
events=[deserialize_event(evt) for evt in discussion_details["events"]],
conflicting_files=conflicting_files,
target_branch=target_branch,
merge_commit_oid=merge_commit_oid,
diff=discussion_details.get("diff"),
endpoint=self.endpoint,
)
@validate_hf_hub_args
def create_discussion(
self,
repo_id: str,
title: str,
*,
token: Optional[str] = None,
description: Optional[str] = None,
repo_type: Optional[str] = None,
pull_request: bool = False,
) -> DiscussionWithDetails:
"""Creates a Discussion or Pull Request.
Pull Requests created programmatically will be in `"draft"` status.
Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`].
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
title (`str`):
The title of the discussion. It can be up to 200 characters long,
and must be at least 3 characters long. Leading and trailing whitespaces
will be stripped.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
description (`str`, *optional*):
An optional description for the Pull Request.
Defaults to `"Discussion opened with the huggingface_hub Python library"`
pull_request (`bool`, *optional*):
Whether to create a Pull Request or discussion. If `True`, creates a Pull Request.
If `False`, creates a discussion. Defaults to `False`.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns: [`DiscussionWithDetails`]
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>"""
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
if description is not None:
description = description.strip()
description = (
description
if description
else (
f"{'Pull Request' if pull_request else 'Discussion'} opened with the"
" [huggingface_hub Python"
" library](https://huggingface.co/docs/huggingface_hub)"
)
)
headers = self._build_hf_headers(token=token, is_write_action=True)
resp = get_session().post(
f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions",
json={
"title": title.strip(),
"description": description,
"pullRequest": pull_request,
},
headers=headers,
)
hf_raise_for_status(resp)
num = resp.json()["num"]
return self.get_discussion_details(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=num,
token=token,
)
@validate_hf_hub_args
def create_pull_request(
self,
repo_id: str,
title: str,
*,
token: Optional[str] = None,
description: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionWithDetails:
"""Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status.
Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`];
This is a wrapper around [`HfApi.create_discussion`].
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
title (`str`):
The title of the discussion. It can be up to 200 characters long,
and must be at least 3 characters long. Leading and trailing whitespaces
will be stripped.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
description (`str`, *optional*):
An optional description for the Pull Request.
Defaults to `"Discussion opened with the huggingface_hub Python library"`
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
Returns: [`DiscussionWithDetails`]
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>"""
return self.create_discussion(
repo_id=repo_id,
title=title,
token=token,
description=description,
repo_type=repo_type,
pull_request=True,
)
def _post_discussion_changes(
self,
*,
repo_id: str,
discussion_num: int,
resource: str,
body: Optional[dict] = None,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> requests.Response:
"""Internal utility to POST changes to a Discussion or Pull Request"""
if not isinstance(discussion_num, int) or discussion_num <= 0:
raise ValueError("Invalid discussion_num, must be a positive integer")
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
repo_id = f"{repo_type}s/{repo_id}"
path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}"
headers = self._build_hf_headers(token=token, is_write_action=True)
resp = requests.post(path, headers=headers, json=body)
hf_raise_for_status(resp)
return resp
@validate_hf_hub_args
def comment_discussion(
self,
repo_id: str,
discussion_num: int,
comment: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionComment:
"""Creates a new comment on the given Discussion.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment (`str`):
The content of the comment to create. Comments support markdown formatting.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns:
[`DiscussionComment`]: the newly created comment
Examples:
```python
>>> comment = \"\"\"
... Hello @otheruser!
...
... # This is a title
...
... **This is bold**, *this is italic* and ~this is strikethrough~
... And [this](http://url) is a link
... \"\"\"
>>> HfApi().comment_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... comment=comment
... )
# DiscussionComment(id='deadbeef0000000', type='comment', ...)
```
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="comment",
body={"comment": comment},
)
return deserialize_event(resp.json()["newMessage"]) # type: ignore
@validate_hf_hub_args
def rename_discussion(
self,
repo_id: str,
discussion_num: int,
new_title: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionTitleChange:
"""Renames a Discussion.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
new_title (`str`):
The new title for the discussion
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns:
[`DiscussionTitleChange`]: the title change event
Examples:
```python
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
```
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="title",
body={"title": new_title},
)
return deserialize_event(resp.json()["newTitle"]) # type: ignore
@validate_hf_hub_args
def change_discussion_status(
self,
repo_id: str,
discussion_num: int,
new_status: Literal["open", "closed"],
*,
token: Optional[str] = None,
comment: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionStatusChange:
"""Closes or re-opens a Discussion or Pull Request.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
new_status (`str`):
The new status for the discussion, either `"open"` or `"closed"`.
comment (`str`, *optional*):
An optional comment to post with the status change.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns:
[`DiscussionStatusChange`]: the status change event
Examples:
```python
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
```
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
if new_status not in ["open", "closed"]:
raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'")
body: Dict[str, str] = {"status": new_status}
if comment and comment.strip():
body["comment"] = comment.strip()
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="status",
body=body,
)
return deserialize_event(resp.json()["newStatus"]) # type: ignore
@validate_hf_hub_args
def merge_pull_request(
self,
repo_id: str,
discussion_num: int,
*,
token: Optional[str] = None,
comment: Optional[str] = None,
repo_type: Optional[str] = None,
):
"""Merges a Pull Request.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment (`str`, *optional*):
An optional comment to post with the status change.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns:
[`DiscussionStatusChange`]: the status change event
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource="merge",
body={"comment": comment.strip()} if comment and comment.strip() else None,
)
@validate_hf_hub_args
def edit_discussion_comment(
self,
repo_id: str,
discussion_num: int,
comment_id: str,
new_content: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionComment:
"""Edits a comment on a Discussion / Pull Request.
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment_id (`str`):
The ID of the comment to edit.
new_content (`str`):
The new content of the comment. Comments support markdown formatting.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns:
[`DiscussionComment`]: the edited comment
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource=f"comment/{comment_id.lower()}/edit",
body={"content": new_content},
)
return deserialize_event(resp.json()["updatedComment"]) # type: ignore
@validate_hf_hub_args
def hide_discussion_comment(
self,
repo_id: str,
discussion_num: int,
comment_id: str,
*,
token: Optional[str] = None,
repo_type: Optional[str] = None,
) -> DiscussionComment:
"""Hides a comment on a Discussion / Pull Request.
<Tip warning={true}>
Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.
</Tip>
Args:
repo_id (`str`):
A namespace (user or an organization) and a repo name separated
by a `/`.
discussion_num (`int`):
The number of the Discussion or Pull Request . Must be a strictly positive integer.
comment_id (`str`):
The ID of the comment to edit.
repo_type (`str`, *optional*):
Set to `"dataset"` or `"space"` if uploading to a dataset or
space, `None` or `"model"` if uploading to a model. Default is
`None`.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token)
Returns:
[`DiscussionComment`]: the hidden comment
<Tip>
Raises the following errors:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid
- [`~utils.RepositoryNotFoundError`]
If the repository to download from cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
</Tip>
"""
warnings.warn(
"Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.",
UserWarning,
)
resp = self._post_discussion_changes(
repo_id=repo_id,
repo_type=repo_type,
discussion_num=discussion_num,
token=token,
resource=f"comment/{comment_id.lower()}/hide",
)
return deserialize_event(resp.json()["updatedComment"]) # type: ignore
@validate_hf_hub_args
def add_space_secret(
self, repo_id: str, key: str, value: str, *, description: Optional[str] = None, token: Optional[str] = None
) -> None:
"""Adds or updates a secret in a Space.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Secret key. Example: `"GITHUB_API_KEY"`
value (`str`):
Secret value. Example: `"your_github_api_key"`.
description (`str`, *optional*):
Secret description. Example: `"Github API key to access the Github API"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
"""
payload = {"key": key, "value": value}
if description is not None:
payload["description"] = description
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/secrets",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r)
@validate_hf_hub_args
def delete_space_secret(self, repo_id: str, key: str, *, token: Optional[str] = None) -> None:
"""Deletes a secret from a Space.
Secrets allow to set secret keys or tokens to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Secret key. Example: `"GITHUB_API_KEY"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
"""
r = get_session().delete(
f"{self.endpoint}/api/spaces/{repo_id}/secrets",
headers=self._build_hf_headers(token=token),
json={"key": key},
)
hf_raise_for_status(r)
@validate_hf_hub_args
def get_space_variables(self, repo_id: str, *, token: Optional[str] = None) -> Dict[str, SpaceVariable]:
"""Gets all variables from a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to query. Example: `"bigcode/in-the-stack"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
"""
r = get_session().get(
f"{self.endpoint}/api/spaces/{repo_id}/variables",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(r)
return {k: SpaceVariable(k, v) for k, v in r.json().items()}
@validate_hf_hub_args
def add_space_variable(
self, repo_id: str, key: str, value: str, *, description: Optional[str] = None, token: Optional[str] = None
) -> Dict[str, SpaceVariable]:
"""Adds or updates a variable in a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Variable key. Example: `"MODEL_REPO_ID"`
value (`str`):
Variable value. Example: `"the_model_repo_id"`.
description (`str`):
Description of the variable. Example: `"Model Repo ID of the implemented model"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
"""
payload = {"key": key, "value": value}
if description is not None:
payload["description"] = description
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/variables",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r)
return {k: SpaceVariable(k, v) for k, v in r.json().items()}
@validate_hf_hub_args
def delete_space_variable(
self, repo_id: str, key: str, *, token: Optional[str] = None
) -> Dict[str, SpaceVariable]:
"""Deletes a variable from a Space.
Variables allow to set environment variables to a Space without hardcoding them.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
key (`str`):
Variable key. Example: `"MODEL_REPO_ID"`
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
"""
r = get_session().delete(
f"{self.endpoint}/api/spaces/{repo_id}/variables",
headers=self._build_hf_headers(token=token),
json={"key": key},
)
hf_raise_for_status(r)
return {k: SpaceVariable(k, v) for k, v in r.json().items()}
@validate_hf_hub_args
def get_space_runtime(self, repo_id: str, *, token: Optional[str] = None) -> SpaceRuntime:
"""Gets runtime information about a Space.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if
not provided.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
"""
r = get_session().get(
f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token)
)
hf_raise_for_status(r)
return SpaceRuntime(r.json())
@validate_hf_hub_args
def request_space_hardware(
self,
repo_id: str,
hardware: SpaceHardware,
*,
token: Optional[str] = None,
sleep_time: Optional[int] = None,
) -> SpaceRuntime:
"""Request new hardware for a Space.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
hardware (`str` or [`SpaceHardware`]):
Hardware on which to run the Space. Example: `"t4-medium"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
<Tip>
It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details.
</Tip>
"""
if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
warnings.warn(
"If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
" than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
" you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
UserWarning,
)
payload: Dict[str, Any] = {"flavor": hardware}
if sleep_time is not None:
payload["sleepTimeSeconds"] = sleep_time
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/hardware",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r)
return SpaceRuntime(r.json())
@validate_hf_hub_args
def set_space_sleep_time(self, repo_id: str, sleep_time: int, *, token: Optional[str] = None) -> SpaceRuntime:
"""Set a custom sleep time for a Space running on upgraded hardware..
Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep"
mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a
configurable sleep time. To know more about the sleep stage, please refer to
https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
Args:
repo_id (`str`):
ID of the repo to update. Example: `"bigcode/in-the-stack"`.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
<Tip>
It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`].
</Tip>
"""
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/sleeptime",
headers=self._build_hf_headers(token=token),
json={"seconds": sleep_time},
)
hf_raise_for_status(r)
runtime = SpaceRuntime(r.json())
hardware = runtime.requested_hardware or runtime.hardware
if hardware == SpaceHardware.CPU_BASIC:
warnings.warn(
"If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
" than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
" you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
UserWarning,
)
return runtime
@validate_hf_hub_args
def pause_space(self, repo_id: str, *, token: Optional[str] = None) -> SpaceRuntime:
"""Pause your Space.
A paused Space stops executing until manually restarted by its owner. This is different from the sleeping
state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the
hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page.
For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
Args:
repo_id (`str`):
ID of the Space to pause. Example: `"Salesforce/BLIP2"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns:
[`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware.
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
"""
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token)
)
hf_raise_for_status(r)
return SpaceRuntime(r.json())
@validate_hf_hub_args
def restart_space(
self, repo_id: str, *, token: Optional[str] = None, factory_reboot: bool = False
) -> SpaceRuntime:
"""Restart your Space.
This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You
must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be
billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.
For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause).
Args:
repo_id (`str`):
ID of the Space to restart. Example: `"Salesforce/BLIP2"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
factory_reboot (`bool`, *optional*):
If `True`, the Space will be rebuilt from scratch without caching any requirements.
Returns:
[`SpaceRuntime`]: Runtime information about your Space.
Raises:
[`~utils.RepositoryNotFoundError`]:
If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you
are not authenticated.
[`~utils.HfHubHTTPError`]:
403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't
own, either ask the owner by opening a Discussion or duplicate the Space.
[`~utils.BadRequestError`]:
If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide
a static Space, you can set it to private.
"""
params = {}
if factory_reboot:
params["factory"] = "true"
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params
)
hf_raise_for_status(r)
return SpaceRuntime(r.json())
@validate_hf_hub_args
def duplicate_space(
self,
from_id: str,
to_id: Optional[str] = None,
*,
private: Optional[bool] = None,
token: Optional[str] = None,
exist_ok: bool = False,
hardware: Optional[SpaceHardware] = None,
storage: Optional[SpaceStorage] = None,
sleep_time: Optional[int] = None,
secrets: Optional[List[Dict[str, str]]] = None,
variables: Optional[List[Dict[str, str]]] = None,
) -> RepoUrl:
"""Duplicate a Space.
Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state
as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.
Args:
from_id (`str`):
ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`.
to_id (`str`, *optional*):
ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same
name as the original Space, but in your account.
private (`bool`, *optional*):
Whether the new Space should be private or not. Defaults to the same privacy as the original Space.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
exist_ok (`bool`, *optional*, defaults to `False`):
If `True`, do not raise an error if repo already exists.
hardware (`SpaceHardware` or `str`, *optional*):
Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list.
storage (`SpaceStorage` or `str`, *optional*):
Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list.
sleep_time (`int`, *optional*):
Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want
your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure
the sleep time (value is fixed to 48 hours of inactivity).
See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.
secrets (`List[Dict[str, str]]`, *optional*):
A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.
variables (`List[Dict[str, str]]`, *optional*):
A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional.
For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.
Returns:
[`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing
attributes like `endpoint`, `repo_type` and `repo_id`.
Raises:
- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`~utils.RepositoryNotFoundError`]
If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist,
or because it is set to `private` and you do not have access.
Example:
```python
>>> from huggingface_hub import duplicate_space
# Duplicate a Space to your account
>>> duplicate_space("multimodalart/dreambooth-training")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
# Can set custom destination id and visibility flag.
>>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", private=True)
RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
```
"""
# Parse to_id if provided
parsed_to_id = RepoUrl(to_id) if to_id is not None else None
# Infer target repo_id
to_namespace = ( # set namespace manually or default to username
parsed_to_id.namespace
if parsed_to_id is not None and parsed_to_id.namespace is not None
else self.whoami(token)["name"]
)
to_repo_name = parsed_to_id.repo_name if to_id is not None else RepoUrl(from_id).repo_name # type: ignore
# repository must be a valid repo_id (namespace/repo_name).
payload: Dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"}
keys = ["private", "hardware", "storageTier", "sleepTimeSeconds", "secrets", "variables"]
values = [private, hardware, storage, sleep_time, secrets, variables]
payload.update({k: v for k, v in zip(keys, values) if v is not None})
if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC:
warnings.warn(
"If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more"
" than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if"
" you want to set a custom sleep time, you need to upgrade to a paid Hardware.",
UserWarning,
)
r = get_session().post(
f"{self.endpoint}/api/spaces/{from_id}/duplicate",
headers=self._build_hf_headers(token=token, is_write_action=True),
json=payload,
)
try:
hf_raise_for_status(r)
except HTTPError as err:
if exist_ok and err.response.status_code == 409:
# Repo already exists and `exist_ok=True`
pass
else:
raise
return RepoUrl(r.json()["url"], endpoint=self.endpoint)
@validate_hf_hub_args
def request_space_storage(
self,
repo_id: str,
storage: SpaceStorage,
*,
token: Optional[str] = None,
) -> SpaceRuntime:
"""Request persistent storage for a Space.
Args:
repo_id (`str`):
ID of the Space to update. Example: `"HuggingFaceH4/open_llm_leaderboard"`.
storage (`str` or [`SpaceStorage`]):
Storage tier. Either 'small', 'medium', or 'large'.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
<Tip>
It is not possible to decrease persistent storage after its granted. To do so, you must delete it
via [`delete_space_storage`].
</Tip>
"""
payload: Dict[str, SpaceStorage] = {"tier": storage}
r = get_session().post(
f"{self.endpoint}/api/spaces/{repo_id}/storage",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(r)
return SpaceRuntime(r.json())
@validate_hf_hub_args
def delete_space_storage(
self,
repo_id: str,
*,
token: Optional[str] = None,
) -> SpaceRuntime:
"""Delete persistent storage for a Space.
Args:
repo_id (`str`):
ID of the Space to update. Example: `"HuggingFaceH4/open_llm_leaderboard"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns:
[`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware.
Raises:
[`BadRequestError`]
If space has no persistent storage.
"""
r = get_session().delete(
f"{self.endpoint}/api/spaces/{repo_id}/storage",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(r)
return SpaceRuntime(r.json())
#######################
# Inference Endpoints #
#######################
def list_inference_endpoints(
self, namespace: Optional[str] = None, *, token: Optional[str] = None
) -> List[InferenceEndpoint]:
"""Lists all inference endpoints for the given namespace.
Args:
namespace (`str`, *optional*):
The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints
from all namespaces (i.e. personal namespace and all orgs the user belongs to).
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
List[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_inference_endpoints()
[InferenceEndpoint(name='my-endpoint', ...), ...]
```
"""
# Special case: list all endpoints for all namespaces the user has access to
if namespace == "*":
user = self.whoami(token=token)
# List personal endpoints first
endpoints: List[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token))
# Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access)
for org in user.get("orgs", []):
try:
endpoints += list_inference_endpoints(namespace=org["name"], token=token)
except HfHubHTTPError as error:
if error.response.status_code == 401: # Either no billing or user don't have access)
logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error)
pass
return endpoints
# Normal case: list endpoints for a specific namespace
namespace = namespace or self._get_namespace(token=token)
response = get_session().get(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
return [
InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token)
for endpoint in response.json()["items"]
]
def create_inference_endpoint(
self,
name: str,
*,
repository: str,
framework: str,
accelerator: str,
instance_size: str,
instance_type: str,
region: str,
vendor: str,
account_id: Optional[str] = None,
min_replica: int = 0,
max_replica: int = 1,
revision: Optional[str] = None,
task: Optional[str] = None,
custom_image: Optional[Dict] = None,
type: InferenceEndpointType = InferenceEndpointType.PROTECTED,
namespace: Optional[str] = None,
token: Optional[str] = None,
) -> InferenceEndpoint:
"""Create a new Inference Endpoint.
Args:
name (`str`):
The unique name for the new Inference Endpoint.
repository (`str`):
The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
framework (`str`):
The machine learning framework used for the model (e.g. `"custom"`).
accelerator (`str`):
The hardware accelerator to be used for inference (e.g. `"cpu"`).
instance_size (`str`):
The size or type of the instance to be used for hosting the model (e.g. `"large"`).
instance_type (`str`):
The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`).
region (`str`):
The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`).
vendor (`str`):
The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`).
account_id (`str`, *optional*):
The account ID used to link a VPC to a private Inference Endpoint (if applicable).
min_replica (`int`, *optional*):
The minimum number of replicas (instances) to keep running for the Inference Endpoint. Defaults to 0.
max_replica (`int`, *optional*):
The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
revision (`str`, *optional*):
The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
task (`str`, *optional*):
The task on which to deploy the model (e.g. `"text-classification"`).
custom_image (`Dict`, *optional*):
A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
type ([`InferenceEndpointType]`, *optional*):
The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`.
namespace (`str`, *optional*):
The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
[`InferenceEndpoint`]: information about the updated Inference Endpoint.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> create_inference_endpoint(
... "my-endpoint-name",
... repository="gpt2",
... framework="pytorch",
... task="text-generation",
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="medium",
... instance_type="c6i",
... )
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', status="pending",...)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
"..."
```
```python
# Start an Inference Endpoint running Zephyr-7b-beta on TGI
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> create_inference_endpoint(
... "aws-zephyr-7b-beta-0486",
... repository="HuggingFaceH4/zephyr-7b-beta",
... framework="pytorch",
... task="text-generation",
... accelerator="gpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="medium",
... instance_type="g5.2xlarge",
... custom_image={
... "health_route": "/health",
... "env": {
... "MAX_BATCH_PREFILL_TOKENS": "2048",
... "MAX_INPUT_LENGTH": "1024",
... "MAX_TOTAL_TOKENS": "1512",
... "MODEL_ID": "/repository"
... },
... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
... },
... )
```
"""
namespace = namespace or self._get_namespace(token=token)
image = {"custom": custom_image} if custom_image is not None else {"huggingface": {}}
payload: Dict = {
"accountId": account_id,
"compute": {
"accelerator": accelerator,
"instanceSize": instance_size,
"instanceType": instance_type,
"scaling": {
"maxReplica": max_replica,
"minReplica": min_replica,
},
},
"model": {
"framework": framework,
"repository": repository,
"revision": revision,
"task": task,
"image": image,
},
"name": name,
"provider": {
"region": region,
"vendor": vendor,
},
"type": type,
}
response = get_session().post(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(response)
return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
def get_inference_endpoint(
self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None
) -> InferenceEndpoint:
"""Get information about an Inference Endpoint.
Args:
name (`str`):
The name of the Inference Endpoint to retrieve information about.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
[`InferenceEndpoint`]: information about the requested Inference Endpoint.
Example:
```python
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.get_inference_endpoint("my-text-to-image")
>>> endpoint
InferenceEndpoint(name='my-text-to-image', ...)
# Get status
>>> endpoint.status
'running'
>>> endpoint.url
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
# Run inference
>>> endpoint.client.text_to_image(...)
```
"""
namespace = namespace or self._get_namespace(token=token)
response = get_session().get(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
def update_inference_endpoint(
self,
name: str,
*,
# Compute update
accelerator: Optional[str] = None,
instance_size: Optional[str] = None,
instance_type: Optional[str] = None,
min_replica: Optional[int] = None,
max_replica: Optional[int] = None,
# Model update
repository: Optional[str] = None,
framework: Optional[str] = None,
revision: Optional[str] = None,
task: Optional[str] = None,
# Other
namespace: Optional[str] = None,
token: Optional[str] = None,
) -> InferenceEndpoint:
"""Update an Inference Endpoint.
This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
optional but at least one must be provided.
For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`].
Args:
name (`str`):
The name of the Inference Endpoint to update.
accelerator (`str`, *optional*):
The hardware accelerator to be used for inference (e.g. `"cpu"`).
instance_size (`str`, *optional*):
The size or type of the instance to be used for hosting the model (e.g. `"large"`).
instance_type (`str`, *optional*):
The cloud instance type where the Inference Endpoint will be deployed (e.g. `"c6i"`).
min_replica (`int`, *optional*):
The minimum number of replicas (instances) to keep running for the Inference Endpoint.
max_replica (`int`, *optional*):
The maximum number of replicas (instances) to scale to for the Inference Endpoint.
repository (`str`, *optional*):
The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
framework (`str`, *optional*):
The machine learning framework used for the model (e.g. `"custom"`).
revision (`str`, *optional*):
The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
task (`str`, *optional*):
The task on which to deploy the model (e.g. `"text-classification"`).
namespace (`str`, *optional*):
The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
[`InferenceEndpoint`]: information about the updated Inference Endpoint.
"""
namespace = namespace or self._get_namespace(token=token)
payload: Dict = {}
if any(value is not None for value in (accelerator, instance_size, instance_type, min_replica, max_replica)):
payload["compute"] = {
"accelerator": accelerator,
"instanceSize": instance_size,
"instanceType": instance_type,
"scaling": {
"maxReplica": max_replica,
"minReplica": min_replica,
},
}
if any(value is not None for value in (repository, framework, revision, task)):
payload["model"] = {
"framework": framework,
"repository": repository,
"revision": revision,
"task": task,
"image": {"huggingface": {}},
}
response = get_session().put(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
headers=self._build_hf_headers(token=token),
json=payload,
)
hf_raise_for_status(response)
return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
def delete_inference_endpoint(
self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None
) -> None:
"""Delete an Inference Endpoint.
This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`].
For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`].
Args:
name (`str`):
The name of the Inference Endpoint to delete.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
"""
namespace = namespace or self._get_namespace(token=token)
response = get_session().delete(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
def pause_inference_endpoint(
self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None
) -> InferenceEndpoint:
"""Pause an Inference Endpoint.
A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`].
This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which
would be automatically restarted when a request is made to it.
For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`].
Args:
name (`str`):
The name of the Inference Endpoint to pause.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
[`InferenceEndpoint`]: information about the paused Inference Endpoint.
"""
namespace = namespace or self._get_namespace(token=token)
response = get_session().post(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
def resume_inference_endpoint(
self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None
) -> InferenceEndpoint:
"""Resume an Inference Endpoint.
For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`].
Args:
name (`str`):
The name of the Inference Endpoint to resume.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
[`InferenceEndpoint`]: information about the resumed Inference Endpoint.
"""
namespace = namespace or self._get_namespace(token=token)
response = get_session().post(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
def scale_to_zero_inference_endpoint(
self, name: str, *, namespace: Optional[str] = None, token: Optional[str] = None
) -> InferenceEndpoint:
"""Scale Inference Endpoint to zero.
An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which
would require a manual resume with [`resume_inference_endpoint`].
For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`].
Args:
name (`str`):
The name of the Inference Endpoint to scale to zero.
namespace (`str`, *optional*):
The namespace in which the Inference Endpoint is located. Defaults to the current user.
token (`str`, *optional*):
An authentication token (See https://huggingface.co/settings/token).
Returns:
[`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint.
"""
namespace = namespace or self._get_namespace(token=token)
response = get_session().post(
f"{INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token)
def _get_namespace(self, token: Optional[str] = None) -> str:
"""Get the default namespace for the current user."""
me = self.whoami(token=token)
if me["type"] == "user":
return me["name"]
else:
raise ValueError(
"Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a"
" user."
)
########################
# Collection Endpoints #
########################
@validate_hf_hub_args
def list_collections(
self,
*,
owner: Union[List[str], str, None] = None,
item: Union[List[str], str, None] = None,
sort: Optional[Literal["lastModified", "trending", "upvotes"]] = None,
limit: Optional[int] = None,
token: Optional[Union[bool, str]] = None,
) -> Iterable[Collection]:
"""List collections on the Huggingface Hub, given some filters.
<Tip warning={true}>
When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items
from a collection, you must use [`get_collection`].
</Tip>
Args:
owner (`List[str]` or `str`, *optional*):
Filter by owner's username.
item (`List[str]` or `str`, *optional*):
Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`.
sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*):
Sort collections by last modified, trending or upvotes.
limit (`int`, *optional*):
Maximum number of collections to be returned.
token (`bool` or `str`, *optional*):
An authentication token (see https://huggingface.co/settings/token).
Returns:
`Iterable[Collection]`: an iterable of [`Collection`] objects.
"""
# Construct the API endpoint
path = f"{self.endpoint}/api/collections"
headers = self._build_hf_headers(token=token)
params: Dict = {}
if owner is not None:
params.update({"owner": owner})
if item is not None:
params.update({"item": item})
if sort is not None:
params.update({"sort": sort})
if limit is not None:
params.update({"limit": limit})
# Paginate over the results until limit is reached
items = paginate(path, headers=headers, params=params)
if limit is not None:
items = islice(items, limit) # Do not iterate over all pages
# Parse as Collection and return
for position, collection_data in enumerate(items):
yield Collection(position=position, **collection_data)
def get_collection(self, collection_slug: str, *, token: Optional[str] = None) -> Collection:
"""Gets information about a Collection on the Hub.
Args:
collection_slug (`str`):
Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import get_collection
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
>>> collection.title
'Recent models'
>>> len(collection.items)
37
>>> collection.items[0]
CollectionItem(
item_object_id='651446103cd773a050bf64c2',
item_id='TheBloke/U-Amethyst-20B-AWQ',
item_type='model',
position=88,
note=None
)
```
"""
r = get_session().get(
f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
)
hf_raise_for_status(r)
return Collection(**{**r.json(), "endpoint": self.endpoint})
def create_collection(
self,
title: str,
*,
namespace: Optional[str] = None,
description: Optional[str] = None,
private: bool = False,
exists_ok: bool = False,
token: Optional[str] = None,
) -> Collection:
"""Create a new Collection on the Hub.
Args:
title (`str`):
Title of the collection to create. Example: `"Recent models"`.
namespace (`str`, *optional*):
Namespace of the collection to create (username or org). Will default to the owner name.
description (`str`, *optional*):
Description of the collection to create.
private (`bool`, *optional*):
Whether the collection should be private or not. Defaults to `False` (i.e. public collection).
exists_ok (`bool`, *optional*):
If `True`, do not raise an error if collection already exists.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import create_collection
>>> collection = create_collection(
... title="ICCV 2023",
... description="Portfolio of models, papers and demos I presented at ICCV 2023",
... )
>>> collection.slug
"username/iccv-2023-64f9a55bb3115b4f513ec026"
```
"""
if namespace is None:
namespace = self.whoami(token)["name"]
payload = {
"title": title,
"namespace": namespace,
"private": private,
}
if description is not None:
payload["description"] = description
r = get_session().post(
f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload
)
try:
hf_raise_for_status(r)
except HTTPError as err:
if exists_ok and err.response.status_code == 409:
# Collection already exists and `exists_ok=True`
slug = r.json()["slug"]
return self.get_collection(slug, token=token)
else:
raise
return Collection(**{**r.json(), "endpoint": self.endpoint})
def update_collection_metadata(
self,
collection_slug: str,
*,
title: Optional[str] = None,
description: Optional[str] = None,
position: Optional[int] = None,
private: Optional[bool] = None,
theme: Optional[str] = None,
token: Optional[str] = None,
) -> Collection:
"""Update metadata of a collection on the Hub.
All arguments are optional. Only provided metadata will be updated.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
title (`str`):
Title of the collection to update.
description (`str`, *optional*):
Description of the collection to update.
position (`int`, *optional*):
New position of the collection in the list of collections of the user.
private (`bool`, *optional*):
Whether the collection should be private or not.
theme (`str`, *optional*):
Theme of the collection on the Hub.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import update_collection_metadata
>>> collection = update_collection_metadata(
... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
... title="ICCV Oct. 2023"
... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
... private=False,
... theme="pink",
... )
>>> collection.slug
"username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
# ^collection slug got updated but not the trailing ID
```
"""
payload = {
"position": position,
"private": private,
"theme": theme,
"title": title,
"description": description,
}
r = get_session().patch(
f"{self.endpoint}/api/collections/{collection_slug}",
headers=self._build_hf_headers(token=token),
# Only send not-none values to the API
json={key: value for key, value in payload.items() if value is not None},
)
hf_raise_for_status(r)
return Collection(**{**r.json()["data"], "endpoint": self.endpoint})
def delete_collection(
self, collection_slug: str, *, missing_ok: bool = False, token: Optional[str] = None
) -> None:
"""Delete a collection on the Hub.
Args:
collection_slug (`str`):
Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
missing_ok (`bool`, *optional*):
If `True`, do not raise an error if collection doesn't exists.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Example:
```py
>>> from huggingface_hub import delete_collection
>>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)
```
<Tip warning={true}>
This is a non-revertible action. A deleted collection cannot be restored.
</Tip>
"""
r = get_session().delete(
f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token)
)
try:
hf_raise_for_status(r)
except HTTPError as err:
if missing_ok and err.response.status_code == 404:
# Collection doesn't exists and `missing_ok=True`
return
else:
raise
def add_collection_item(
self,
collection_slug: str,
item_id: str,
item_type: CollectionItemType_T,
*,
note: Optional[str] = None,
exists_ok: bool = False,
token: Optional[str] = None,
) -> Collection:
"""Add an item to a collection on the Hub.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
item_id (`str`):
ID of the item to add to the collection. It can be the ID of a repo on the Hub (e.g. `"facebook/bart-large-mnli"`)
or a paper id (e.g. `"2307.09288"`).
item_type (`str`):
Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"` or `"paper"`.
note (`str`, *optional*):
A note to attach to the item in the collection. The maximum size for a note is 500 characters.
exists_ok (`bool`, *optional*):
If `True`, do not raise an error if item already exists.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Returns: [`Collection`]
Example:
```py
>>> from huggingface_hub import add_collection_item
>>> collection = add_collection_item(
... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
... item_id="pierre-loic/climate-news-articles",
... item_type="dataset"
... )
>>> collection.items[-1].item_id
"pierre-loic/climate-news-articles"
# ^item got added to the collection on last position
# Add item with a note
>>> add_collection_item(
... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
... item_id="datasets/climate_fever",
... item_type="dataset"
... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
... )
(...)
```
"""
payload: Dict[str, Any] = {"item": {"id": item_id, "type": item_type}}
if note is not None:
payload["note"] = note
r = get_session().post(
f"{self.endpoint}/api/collections/{collection_slug}/items",
headers=self._build_hf_headers(token=token),
json=payload,
)
try:
hf_raise_for_status(r)
except HTTPError as err:
if exists_ok and err.response.status_code == 409:
# Item already exists and `exists_ok=True`
return self.get_collection(collection_slug, token=token)
else:
raise
return Collection(**{**r.json(), "endpoint": self.endpoint})
def update_collection_item(
self,
collection_slug: str,
item_object_id: str,
*,
note: Optional[str] = None,
position: Optional[int] = None,
token: Optional[str] = None,
) -> None:
"""Update an item in a collection.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
item_object_id (`str`):
ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`.
note (`str`, *optional*):
A note to attach to the item in the collection. The maximum size for a note is 500 characters.
position (`int`, *optional*):
New position of the item in the collection.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Example:
```py
>>> from huggingface_hub import get_collection, update_collection_item
# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
# Update item based on its ID (add note + update position)
>>> update_collection_item(
... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
... item_object_id=collection.items[-1].item_object_id,
... note="Newly updated model!"
... position=0,
... )
```
"""
payload = {"position": position, "note": note}
r = get_session().patch(
f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
headers=self._build_hf_headers(token=token),
# Only send not-none values to the API
json={key: value for key, value in payload.items() if value is not None},
)
hf_raise_for_status(r)
def delete_collection_item(
self,
collection_slug: str,
item_object_id: str,
*,
missing_ok: bool = False,
token: Optional[str] = None,
) -> None:
"""Delete an item from a collection.
Args:
collection_slug (`str`):
Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`.
item_object_id (`str`):
ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id).
It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0]._id`.
missing_ok (`bool`, *optional*):
If `True`, do not raise an error if item doesn't exists.
token (`str`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Example:
```py
>>> from huggingface_hub import get_collection, delete_collection_item
# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
# Delete item based on its ID
>>> delete_collection_item(
... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
... item_object_id=collection.items[-1].item_object_id,
... )
```
"""
r = get_session().delete(
f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}",
headers=self._build_hf_headers(token=token),
)
try:
hf_raise_for_status(r)
except HTTPError as err:
if missing_ok and err.response.status_code == 404:
# Item already deleted and `missing_ok=True`
return
else:
raise
##########################
# Manage access requests #
##########################
@validate_hf_hub_args
def list_pending_access_requests(
self, repo_id: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> List[AccessRequest]:
"""
Get pending access requests for a given gated repo.
A pending request means the user has requested access to the repo but the request has not been processed yet.
If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected
using [`accept_access_request`] and [`reject_access_request`].
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to get access requests for.
repo_type (`str`, *optional*):
The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Returns:
`List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
be populated with user's answers.
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
Example:
```py
>>> from huggingface_hub import list_pending_access_requests, accept_access_request
# List pending requests
>>> requests = list_pending_access_requests("meta-llama/Llama-2-7b")
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='pending',
fields=None,
),
...
]
# Accept Clem's request
>>> accept_access_request("meta-llama/Llama-2-7b", "clem")
```
"""
return self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token)
@validate_hf_hub_args
def list_accepted_access_requests(
self, repo_id: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> List[AccessRequest]:
"""
Get accepted access requests for a given gated repo.
An accepted request means the user has requested access to the repo and the request has been accepted. The user
can download any file of the repo. If the approval mode is automatic, this list should contains by default all
requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and
[`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will
go to the rejected list. In both cases, the user will lose access to the repo.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to get access requests for.
repo_type (`str`, *optional*):
The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Returns:
`List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
be populated with user's answers.
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
Example:
```py
>>> from huggingface_hub import list_accepted_access_requests
>>> requests = list_accepted_access_requests("meta-llama/Llama-2-7b")
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='accepted',
fields=None,
),
...
]
```
"""
return self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token)
@validate_hf_hub_args
def list_rejected_access_requests(
self, repo_id: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> List[AccessRequest]:
"""
Get rejected access requests for a given gated repo.
A rejected request means the user has requested access to the repo and the request has been explicitly rejected
by a repo owner (either you or another user from your organization). The user cannot download any file of the
repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and
[`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will
go to the accepted list.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to get access requests for.
repo_type (`str`, *optional*):
The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Returns:
`List[AccessRequest]`: A list of [`AccessRequest`] objects. Each time contains a `username`, `email`,
`status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will
be populated with user's answers.
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
Example:
```py
>>> from huggingface_hub import list_rejected_access_requests
>>> requests = list_rejected_access_requests("meta-llama/Llama-2-7b")
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='rejected',
fields=None,
),
...
]
```
"""
return self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token)
def _list_access_requests(
self,
repo_id: str,
status: Literal["accepted", "rejected", "pending"],
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> List[AccessRequest]:
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
response = get_session().get(
f"{ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}",
headers=self._build_hf_headers(token=token),
)
hf_raise_for_status(response)
return [
AccessRequest(
username=request["user"]["user"],
fullname=request["user"]["fullname"],
email=request["user"]["email"],
status=request["status"],
timestamp=parse_datetime(request["timestamp"]),
fields=request.get("fields"), # only if custom fields in form
)
for request in response.json()
]
@validate_hf_hub_args
def cancel_access_request(
self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> None:
"""
Cancel an access request from a user for a given gated repo.
A cancelled request will go back to the pending list and the user will lose access to the repo.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to cancel access request for.
user (`str`):
The username of the user which access request should be cancelled.
repo_type (`str`, *optional*):
The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
`HTTPError`:
HTTP 404 if the user does not exist on the Hub.
`HTTPError`:
HTTP 404 if the user access request cannot be found.
`HTTPError`:
HTTP 404 if the user access request is already in the pending list.
"""
self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token)
@validate_hf_hub_args
def accept_access_request(
self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> None:
"""
Accept an access request from a user for a given gated repo.
Once the request is accepted, the user will be able to download any file of the repo and access the community
tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be
cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`].
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to accept access request for.
user (`str`):
The username of the user which access request should be accepted.
repo_type (`str`, *optional*):
The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
`HTTPError`:
HTTP 404 if the user does not exist on the Hub.
`HTTPError`:
HTTP 404 if the user access request cannot be found.
`HTTPError`:
HTTP 404 if the user access request is already in the accepted list.
"""
self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token)
@validate_hf_hub_args
def reject_access_request(
self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> None:
"""
Reject an access request from a user for a given gated repo.
A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected
requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`].
A cancelled request will go back to the pending list while an accepted request will go to the accepted list.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to reject access request for.
user (`str`):
The username of the user which access request should be rejected.
repo_type (`str`, *optional*):
The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
`HTTPError`:
HTTP 404 if the user does not exist on the Hub.
`HTTPError`:
HTTP 404 if the user access request cannot be found.
`HTTPError`:
HTTP 404 if the user access request is already in the rejected list.
"""
self._handle_access_request(repo_id, user, "rejected", repo_type=repo_type, token=token)
@validate_hf_hub_args
def _handle_access_request(
self,
repo_id: str,
user: str,
status: Literal["accepted", "rejected", "pending"],
repo_type: Optional[str] = None,
token: Optional[str] = None,
) -> None:
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
response = get_session().post(
f"{ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle",
headers=self._build_hf_headers(token=token),
json={"user": user, "status": status},
)
hf_raise_for_status(response)
@validate_hf_hub_args
def grant_access(
self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Optional[str] = None
) -> None:
"""
Grant access to a user for a given gated repo.
Granting access don't require for the user to send an access request by themselves. The user is automatically
added to the accepted list meaning they can download the files You can revoke the granted access at any time
using [`cancel_access_request`] or [`reject_access_request`].
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Args:
repo_id (`str`):
The id of the repo to grant access to.
user (`str`):
The username of the user to grant access.
repo_type (`str`, *optional*):
The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`.
Defaults to `model`.
token (`str`, *optional*):
A valid authentication token (see https://huggingface.co/settings/token).
Raises:
`HTTPError`:
HTTP 400 if the repo is not gated.
`HTTPError`:
HTTP 400 if the user already has access to the repo.
`HTTPError`:
HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write`
or `admin` role in the organization the repo belongs to or if you passed a `read` token.
`HTTPError`:
HTTP 404 if the user does not exist on the Hub.
"""
if repo_type not in REPO_TYPES:
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
if repo_type is None:
repo_type = REPO_TYPE_MODEL
response = get_session().post(
f"{ENDPOINT}/api/models/{repo_id}/user-access-request/grant",
headers=self._build_hf_headers(token=token),
json={"user": user},
)
hf_raise_for_status(response)
return response.json()
#############
# Internals #
#############
def _build_hf_headers(
self,
token: Optional[Union[bool, str]] = None,
is_write_action: bool = False,
library_name: Optional[str] = None,
library_version: Optional[str] = None,
user_agent: Union[Dict, str, None] = None,
) -> Dict[str, str]:
"""
Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client
when `token` is not provided.
"""
if token is None:
# Cannot do `token = token or self.token` as token can be `False`.
token = self.token
return build_hf_headers(
token=token,
is_write_action=is_write_action,
library_name=library_name or self.library_name,
library_version=library_version or self.library_version,
user_agent=user_agent or self.user_agent,
)
def _prepare_upload_folder_deletions(
self,
repo_id: str,
repo_type: Optional[str],
revision: Optional[str],
token: Optional[str],
path_in_repo: str,
delete_patterns: Optional[Union[List[str], str]],
) -> List[CommitOperationDelete]:
"""Generate the list of Delete operations for a commit to delete files from a repo.
List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`]
with the matching items.
Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be
kept even if it matches the `delete_patterns` constraints.
"""
if delete_patterns is None:
# If no delete patterns, no need to list and filter remote files
return []
# List remote files
filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token)
# Compute relative path in repo
if path_in_repo:
path_in_repo = path_in_repo.strip("/") + "/" # harmonize
relpath_to_abspath = {
file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo)
}
else:
relpath_to_abspath = {file: file for file in filenames}
# Apply filter on relative paths and return
return [
CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False)
for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns)
if relpath_to_abspath[relpath] != ".gitattributes"
]
def _prepare_upload_folder_additions(
folder_path: Union[str, Path],
path_in_repo: str,
allow_patterns: Optional[Union[List[str], str]] = None,
ignore_patterns: Optional[Union[List[str], str]] = None,
) -> List[CommitOperationAdd]:
"""Generate the list of Add operations for a commit to upload a folder.
Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist)
constraints are discarded.
"""
folder_path = Path(folder_path).expanduser().resolve()
if not folder_path.is_dir():
raise ValueError(f"Provided path: '{folder_path}' is not a directory")
# List files from folder
relpath_to_abspath = {
path.relative_to(folder_path).as_posix(): path
for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic
if path.is_file()
}
# Filter files and return
# Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering.
prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else ""
return [
CommitOperationAdd(
path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk
path_in_repo=prefix + relpath, # "absolute" path in repo
)
for relpath in filter_repo_objects(
relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns
)
]
def _parse_revision_from_pr_url(pr_url: str) -> str:
"""Safely parse revision number from a PR url.
Example:
```py
>>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2")
"refs/pr/2"
```
"""
re_match = re.match(_REGEX_DISCUSSION_URL, pr_url)
if re_match is None:
raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'")
return f"refs/pr/{re_match[1]}"
api = HfApi()
whoami = api.whoami
get_token_permission = api.get_token_permission
list_models = api.list_models
model_info = api.model_info
list_datasets = api.list_datasets
dataset_info = api.dataset_info
list_spaces = api.list_spaces
space_info = api.space_info
repo_exists = api.repo_exists
file_exists = api.file_exists
repo_info = api.repo_info
list_repo_files = api.list_repo_files
list_repo_refs = api.list_repo_refs
list_repo_commits = api.list_repo_commits
list_files_info = api.list_files_info
list_repo_tree = api.list_repo_tree
get_paths_info = api.get_paths_info
list_metrics = api.list_metrics
get_model_tags = api.get_model_tags
get_dataset_tags = api.get_dataset_tags
create_commit = api.create_commit
create_repo = api.create_repo
delete_repo = api.delete_repo
update_repo_visibility = api.update_repo_visibility
super_squash_history = api.super_squash_history
move_repo = api.move_repo
upload_file = api.upload_file
upload_folder = api.upload_folder
delete_file = api.delete_file
delete_folder = api.delete_folder
create_commits_on_pr = api.create_commits_on_pr
preupload_lfs_files = api.preupload_lfs_files
create_branch = api.create_branch
delete_branch = api.delete_branch
create_tag = api.create_tag
delete_tag = api.delete_tag
get_full_repo_name = api.get_full_repo_name
# Safetensors helpers
get_safetensors_metadata = api.get_safetensors_metadata
parse_safetensors_file_metadata = api.parse_safetensors_file_metadata
# Background jobs
run_as_future = api.run_as_future
# Activity API
list_liked_repos = api.list_liked_repos
list_repo_likers = api.list_repo_likers
like = api.like
unlike = api.unlike
# Community API
get_discussion_details = api.get_discussion_details
get_repo_discussions = api.get_repo_discussions
create_discussion = api.create_discussion
create_pull_request = api.create_pull_request
change_discussion_status = api.change_discussion_status
comment_discussion = api.comment_discussion
edit_discussion_comment = api.edit_discussion_comment
rename_discussion = api.rename_discussion
merge_pull_request = api.merge_pull_request
# Space API
add_space_secret = api.add_space_secret
delete_space_secret = api.delete_space_secret
get_space_variables = api.get_space_variables
add_space_variable = api.add_space_variable
delete_space_variable = api.delete_space_variable
get_space_runtime = api.get_space_runtime
request_space_hardware = api.request_space_hardware
set_space_sleep_time = api.set_space_sleep_time
pause_space = api.pause_space
restart_space = api.restart_space
duplicate_space = api.duplicate_space
request_space_storage = api.request_space_storage
delete_space_storage = api.delete_space_storage
# Inference Endpoint API
list_inference_endpoints = api.list_inference_endpoints
create_inference_endpoint = api.create_inference_endpoint
get_inference_endpoint = api.get_inference_endpoint
update_inference_endpoint = api.update_inference_endpoint
delete_inference_endpoint = api.delete_inference_endpoint
pause_inference_endpoint = api.pause_inference_endpoint
resume_inference_endpoint = api.resume_inference_endpoint
scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint
# Collections API
get_collection = api.get_collection
list_collections = api.list_collections
create_collection = api.create_collection
update_collection_metadata = api.update_collection_metadata
delete_collection = api.delete_collection
add_collection_item = api.add_collection_item
update_collection_item = api.update_collection_item
delete_collection_item = api.delete_collection_item
delete_collection_item = api.delete_collection_item
# Access requests API
list_pending_access_requests = api.list_pending_access_requests
list_accepted_access_requests = api.list_accepted_access_requests
list_rejected_access_requests = api.list_rejected_access_requests
cancel_access_request = api.cancel_access_request
accept_access_request = api.accept_access_request
reject_access_request = api.reject_access_request
grant_access = api.grant_access
|