Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/pip/http-v2/1/1/c/a/5/11ca53f6629b39be038f5f3f843243e294312a1cd0bda91c3e78a20bAdded
- .cache/pip/http-v2/1/1/c/a/5/11ca53f6629b39be038f5f3f843243e294312a1cd0bda91c3e78a20b.bodyAdded+1091
- .cache/pip/http-v2/1/7/9/c/1/179c1c4742bcaf5b6d7af8dc2f14a1b329b9b11f7f5b09e3faa897a1Added
- .cache/pip/http-v2/1/8/e/c/b/18ecb372789efe49bbe46617b1f5d32a2b0eac245d58cbf930116174Added
- .cache/pip/http-v2/1/e/b/f/d/1ebfddf16e338050f3c69ee3fb0551055792844fc428979435d11f85Added
- .cache/pip/http-v2/1/e/b/f/d/1ebfddf16e338050f3c69ee3fb0551055792844fc428979435d11f85.bodyAdded+3
- .cache/pip/http-v2/3/3/2/7/a/3327a46f678846be6cb46f3352e6fba668d9664c70a79484c770e358Added
- .cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560Added
- .cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560.bodyAdded+97
- .cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2dAdded
- .cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2d.bodyAdded
- .cache/pip/http-v2/3/9/b/0/3/39b032291f3825af700bccccb41d7507c739ba2f89c5bbbc5b7b490dAdded
- .cache/pip/http-v2/3/9/b/0/3/39b032291f3825af700bccccb41d7507c739ba2f89c5bbbc5b7b490d.bodyAdded
- .cache/pip/http-v2/6/4/2/d/4/642d4b6a48573d7d40bd54626ef2bb21e5059817d13c7487dcfea9fdAdded
- .cache/pip/http-v2/6/4/2/d/4/642d4b6a48573d7d40bd54626ef2bb21e5059817d13c7487dcfea9fd.bodyAdded+1600
- .cache/pip/http-v2/6/4/6/7/b/6467bdd236eabb4648139f514441e5510842fbc90755e4738c64fcf3Added
- .cache/pip/http-v2/6/4/6/7/b/6467bdd236eabb4648139f514441e5510842fbc90755e4738c64fcf3.bodyAdded+341
- .cache/pip/http-v2/6/4/c/f/c/64cfc03e83f9fad4049b1d2a1d785c9273270a4ab9788b538f5054e3Added
- .cache/pip/http-v2/6/5/1/e/5/651e58859e8db8c99b9e7068d03984cfd4577518ff0e021c717afbf4Added
- .cache/pip/http-v2/6/5/1/e/5/651e58859e8db8c99b9e7068d03984cfd4577518ff0e021c717afbf4.bodyAdded+78
- .cache/pip/http-v2/6/6/e/c/7/66ec76a7b6ed4081044f5c7821af293b63c17bc2ac523ff93d5ca7d5Added
- .cache/pip/http-v2/6/8/0/d/4/680d4dd80dc6a3d2df9b9478dfcc8e81e0e4f130e154a3268b98b877Added
- .cache/pip/http-v2/6/b/5/3/a/6b53a9dd0e4fce887cc28c1a921aa1befe8c1a82e6c213d2542d2acbAdded
- .cache/pip/http-v2/6/b/5/3/a/6b53a9dd0e4fce887cc28c1a921aa1befe8c1a82e6c213d2542d2acb.bodyAdded
- .cache/pip/http-v2/a/b/e/2/c/abe2c30c0d105321771461cb84423576f0ec11c835b815e82e629cf7.bodyAdded+3
- .cache/pip/http-v2/c/1/6/c/6/c16c6c635e568e65136b95a15ea17f91b43799aeb0a7e80b55d7a898Added
- .cache/pip/http-v2/c/1/6/c/6/c16c6c635e568e65136b95a15ea17f91b43799aeb0a7e80b55d7a898.bodyAdded+1366
- .cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3Added
- .cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3.bodyAdded+300
- .cache/pip/http-v2/c/d/5/d/e/cd5de44b899cbe1869765c21b55cffc53c0c0ffa9d3c6f1fd40a42a2Added
- .cache/pip/http-v2/e/5/0/3/0/e503010ce88b2bb388d7806c951cab4dd3e436342653b4835f430bcc.bodyAdded+3
- .cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8aAdded
- .cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832dAdded
- .cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d.bodyAdded+139
- .cache/uv/.gitignoreAdded+1
- .cache/uv/.lockAdded
- .cache/uv/CACHEDIR.TAGAdded+1
- .cache/uv/archive-v0/9vHEgYd05Zufvhj6EkjIX/typing_extensions.pyAdded
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/METADATAAdded+373
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/RECORDAdded+190
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/WHEELAdded+5
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/entry_points.txtAdded+7
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/licenses/LICENSEAdded+201
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/top_level.txtAdded+1
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/__init__.pyAdded+1804
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_buckets.pyAdded+1244
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_commit_api.pyAdded+1075
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_commit_scheduler.pyAdded+353
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_dataset_viewer.pyAdded+172
- .cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_eval_results.pyAdded+211
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091Metadata-Version: 2.1Name: scipyVersion: 1.18.0Summary: Fundamental algorithms for scientific computing in PythonMaintainer-Email: SciPy Developers <scipy-dev@python.org>License: Copyright (c) 2001-2002 Enthought, Inc. 2003, SciPy Developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---- ---- This binary distribution of SciPy can also bundle the following software (depending on the build): Name: OpenBLAS Files: scipy.libs/libscipy_openblas*.so Description: bundled as a dynamically linked library Availability: https://github.com/OpenMathLib/OpenBLAS/ License: BSD-3-Clause Copyright (c) 2011-2014, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Name: LAPACK Files: scipy.libs/libscipy_openblas*.so Description: bundled in OpenBLAS Availability: https://github.com/OpenMathLib/OpenBLAS/ License: BSD-3-Clause-Open-MPI Copyright (c) 1992-2013 The University of Tennessee and The University of Tennessee Research Foundation. All rights reserved. Copyright (c) 2000-2013 The University of California Berkeley. All rights reserved. Copyright (c) 2006-2013 The University of Colorado Denver. All rights reserved. $COPYRIGHT$ Additional copyrights may follow $HEADER$ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer listed in this license in the documentation and/or other materials provided with the distribution. - Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. The copyright holders provide no reassurances that the source code provided does not infringe any patent, copyright, or any other intellectual property rights of third parties. The copyright holders disclaim any liability to any recipient for claims brought against recipient by any third party for infringement of that parties intellectual property rights. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Name: GCC runtime library Files: scipy.libs/libgfortran*.so Description: dynamically linked to files compiled with gcc Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran License: GPL-3.0-or-later WITH GCC-exception-3.1 Copyright (C) 2002-2017 Free Software Foundation, Inc. Libgfortran is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. Libgfortran is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. ---- Full text of license texts referred to above follows (that they are listed below does not necessarily imply the conditions apply to the present binary release): ---- GCC RUNTIME LIBRARY EXCEPTION Version 3.1, 31 March 2009 Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This GCC Runtime Library Exception ("Exception") is an additional permission under section 7 of the GNU General Public License, version 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that bears a notice placed by the copyright holder of the file stating that the file is governed by GPLv3 along with this Exception. When you use GCC to compile a program, GCC may combine portions of certain GCC header files and runtime libraries with the compiled program. The purpose of this Exception is to allow compilation of non-GPL (including proprietary) programs to use, in this way, the header files and runtime libraries covered by this Exception. 0. Definitions. A file is an "Independent Module" if it either requires the Runtime Library for execution after a Compilation Process, or makes use of an interface provided by the Runtime Library, but is not otherwise based on the Runtime Library. "GCC" means a version of the GNU Compiler Collection, with or without modifications, governed by version 3 (or a specified later version) of the GNU General Public License (GPL) with the option of using any subsequent versions published by the FSF. "GPL-compatible Software" is software whose conditions of propagation, modification and use would permit combination with GCC in accord with the license of GCC. "Target Code" refers to output from any compiler for a real or virtual target processor architecture, in executable form or suitable for input to an assembler, loader, linker and/or execution phase. Notwithstanding that, Target Code does not include data in any format that is used as a compiler intermediate representation, or used for producing a compiler intermediate representation. The "Compilation Process" transforms code entirely represented in non-intermediate languages designed for human-written code, and/or in Java Virtual Machine byte code, into Target Code. Thus, for example, use of source code generators and preprocessors need not be considered part of the Compilation Process, since the Compilation Process can be understood as starting with the output of the generators or preprocessors. A Compilation Process is "Eligible" if it is done using GCC, alone or with other GPL-compatible software, or if it is done without using any work based on GCC. For example, using non-GPL-compatible Software to optimize any GCC intermediate representations would not qualify as an Eligible Compilation Process. 1. Grant of Additional Permission. You have permission to propagate a work of Target Code formed by combining the Runtime Library with Independent Modules, even if such propagation would otherwise violate the terms of GPLv3, provided that all Target Code was generated by Eligible Compilation Processes. You may then convey such a combination under terms of your choice, consistent with the licensing of the Independent Modules. 2. No Weakening of GCC Copyleft. The availability of this Exception does not imply any general presumption that third-party software is unaffected by the copyleft requirements of the license of GCC. ---- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. Name: libquadmath Files: scipy.libs/libquadmath*.so Description: dynamically linked to files compiled with gcc Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath License: LGPL-2.1-or-later GCC Quad-Precision Math Library Copyright (C) 2010-2019 Free Software Foundation, Inc. Written by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org> This file is part of the libquadmath library. Libquadmath is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Libquadmath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html Classifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: Science/ResearchClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: BSD LicenseClassifier: Programming Language :: CClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Scientific/EngineeringClassifier: Operating System :: Microsoft :: WindowsClassifier: Operating System :: POSIX :: LinuxClassifier: Operating System :: POSIXClassifier: Operating System :: UnixClassifier: Operating System :: MacOSProject-URL: homepage, https://scipy.org/Project-URL: documentation, https://docs.scipy.org/doc/scipy/Project-URL: source, https://github.com/scipy/scipyProject-URL: download, https://github.com/scipy/scipy/releasesProject-URL: tracker, https://github.com/scipy/scipy/issuesRequires-Python: >=3.12Requires-Dist: numpy<2.8,>=2.0.0Provides-Extra: testRequires-Dist: pytest>=8.0.0; extra == "test"Requires-Dist: pytest-cov; extra == "test"Requires-Dist: pytest-timeout; extra == "test"Requires-Dist: pytest-xdist; extra == "test"Requires-Dist: asv; extra == "test"Requires-Dist: mpmath; extra == "test"Requires-Dist: gmpy2; extra == "test"Requires-Dist: threadpoolctl; extra == "test"Requires-Dist: scikit-umfpack; extra == "test"Requires-Dist: pooch; extra == "test"Requires-Dist: hypothesis>=6.30; extra == "test"Requires-Dist: array-api-strict>=2.3.1; extra == "test"Requires-Dist: Cython; extra == "test"Requires-Dist: meson; extra == "test"Requires-Dist: ninja; sys_platform != "emscripten" and extra == "test"Requires-Dist: scipy-doctest>=2.0.0; extra == "test"Provides-Extra: docRequires-Dist: sphinx<8.2.0,>=5.0.0; extra == "doc"Requires-Dist: intersphinx_registry; extra == "doc"Requires-Dist: pydata-sphinx-theme>=0.15.2; extra == "doc"Requires-Dist: sphinx-copybutton; extra == "doc"Requires-Dist: sphinx-design>=0.4.0; extra == "doc"Requires-Dist: matplotlib>=3.5; extra == "doc"Requires-Dist: numpydoc; extra == "doc"Requires-Dist: jupytext; extra == "doc"Requires-Dist: myst-nb>=1.2.0; extra == "doc"Requires-Dist: pooch; extra == "doc"Requires-Dist: jupyterlite-sphinx>=0.19.1; extra == "doc"Requires-Dist: jupyterlite-pyodide-kernel; extra == "doc"Requires-Dist: linkify-it-py; extra == "doc"Requires-Dist: tabulate; extra == "doc"Provides-Extra: devRequires-Dist: click<8.3.0; extra == "dev"Requires-Dist: spin; extra == "dev"Requires-Dist: mypy==1.19.1; extra == "dev"Requires-Dist: pyrefly==0.63.0; extra == "dev"Requires-Dist: typing_extensions; extra == "dev"Requires-Dist: types-psutil; extra == "dev"Requires-Dist: pycodestyle; extra == "dev"Requires-Dist: ruff>=0.12.0; extra == "dev"Requires-Dist: cython-lint>=0.12.2; extra == "dev"Description-Content-Type: text/x-rst
.. image:: https://raw.githubusercontent.com/scipy/scipy/main/doc/source/_static/logo.svg :target: https://scipy.org :width: 110 :height: 110 :align: left
.. image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A :target: https://numfocus.org
.. image:: https://img.shields.io/pypi/dm/scipy.svg?label=Pypi%20downloads :target: https://pypi.org/project/scipy/
.. image:: https://img.shields.io/conda/dn/conda-forge/scipy.svg?label=Conda%20downloads :target: https://anaconda.org/conda-forge/scipy
.. image:: https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg :target: https://stackoverflow.com/questions/tagged/scipy
.. image:: https://img.shields.io/badge/DOI-10.1038%2Fs41592--019--0686--2-blue.svg :target: https://www.nature.com/articles/s41592-019-0686-2
.. image:: https://insights.linuxfoundation.org/api/badge/health-score?project=scipy :target: https://insights.linuxfoundation.org/project/scipy
SciPy (pronounced "Sigh Pie") is an open-source software for mathematics,science, and engineering. It includes modules for statistics, optimization,integration, linear algebra, Fourier transforms, signal and image processing,ODE solvers, and more.
- **Website:** https://scipy.org- **Documentation:** https://docs.scipy.org/doc/scipy/- **Development version of the documentation:** https://scipy.github.io/devdocs- **SciPy development forum:** https://discuss.scientific-python.org/c/contributor/scipy- **Stack Overflow:** https://stackoverflow.com/questions/tagged/scipy- **Source code:** https://github.com/scipy/scipy- **Contributing:** https://scipy.github.io/devdocs/dev/index.html- **Bug reports:** https://github.com/scipy/scipy/issues- **Code of Conduct:** https://docs.scipy.org/doc/scipy/dev/conduct/code_of_conduct.html- **Report a security vulnerability:** via Tidelift, as explained in `our docs on Security <https://scipy.github.io/devdocs/tutorial/security.html>`__- **Citing in your work:** https://www.scipy.org/citing-scipy/
SciPy is built to work withNumPy arrays, and provides many user-friendly and efficient numerical routines,such as routines for numerical integration and optimization. Together, theyrun on all popular operating systems, are quick to install, and are free ofcharge. NumPy and SciPy are easy to use, but powerful enough to be dependedupon by some of the world's leading scientists and engineers. If you need tomanipulate numbers on a computer and display or publish the results, giveSciPy a try!
For the installation instructions, see `our installguide <https://scipy.org/install/>`__.
Call for Contributions----------------------
We appreciate and welcome contributions. Small improvements or fixes are always appreciated; issues labeled as "goodfirst issue" may be a good starting point. Have a look at `our contributingguide <https://scipy.github.io/devdocs/dev/index.html>`__.
Writing code isn’t the only way to contribute to SciPy. You can also:
- review pull requests- triage issues- develop tutorials, presentations, and other educational materials- maintain and improve `our website <https://github.com/scipy/scipy.org>`__- develop graphic design for our brand assets and promotional materials- help with outreach and onboard new contributors- write grant proposals and help with other fundraising efforts
If you’re unsure where to start or how your skills fit in, reach out! You canask on the `forum <https://discuss.scientific-python.org/c/contributor/scipy>`__or here, on GitHub, by leaving a comment on a relevant issue that is alreadyopen.
If you are new to contributing to open source, `thisguide <https://opensource.guide/how-to-contribute/>`__ helps explain why, what,and how to get involved.123version https://git-lfs.github.com/spec/v1oid sha256:1f55797419e16e7f30cf88ffb3113ce0467f00cfe3f70d5c281730b21769bfc2size 3528711512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697Metadata-Version: 2.4Name: kiwisolverVersion: 1.5.0Summary: A fast implementation of the Cassowary constraint solverAuthor-email: The Nucleic Development Team <sccolbert@gmail.com>Maintainer-email: "Matthieu C. Dartiailh" <m.dartiailh@gmail.com>License: ========================= The Kiwi licensing terms ========================= Kiwi is licensed under the terms of the Modified BSD License (also known as New or Revised BSD), as follows: Copyright (c) 2013-2026, Nucleic Development Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Nucleic Development Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. About Kiwi ---------- Chris Colbert began the Kiwi project in December 2013 in an effort to create a blisteringly fast UI constraint solver. Chris is still the project lead. The Nucleic Development Team is the set of all contributors to the Nucleic project and its subprojects. The core team that coordinates development on GitHub can be found here: http://github.com/nucleic. The current team consists of: * Chris Colbert Our Copyright Policy -------------------- Nucleic uses a shared copyright model. Each contributor maintains copyright over their contributions to Nucleic. But, it is important to note that these contributions are typically only changes to the repositories. Thus, the Nucleic source code, in its entirety is not the copyright of any single person or institution. Instead, it is the collective copyright of the entire Nucleic Development Team. If individual contributors want to maintain a record of what changes/contributions they have specific copyright on, they should indicate their copyright in the commit message of the change, when they commit the change to one of the Nucleic repositories. With this in mind, the following banner should be used in any source code file to indicate the copyright and license terms: #------------------------------------------------------------------------------ # Copyright (c) 2013-2026, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------------------------------------ Project-URL: homepage, https://github.com/nucleic/kiwiProject-URL: documentation, https://kiwisolver.readthedocs.io/en/latest/Project-URL: repository, https://github.com/nucleic/kiwiProject-URL: changelog, https://github.com/nucleic/kiwi/blob/main/releasenotes.rstClassifier: License :: OSI Approved :: BSD LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: Implementation :: GraalPyRequires-Python: >=3.10Description-Content-Type: text/x-rstLicense-File: LICENSEDynamic: license-file1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600Metadata-Version: 2.4Name: tqdmVersion: 4.69.0Summary: Fast, Extensible Progress MeterMaintainer-email: tqdm developers <devs@tqdm.ml>License: MPL-2.0 AND MITProject-URL: homepage, https://tqdm.github.ioProject-URL: repository, https://github.com/tqdm/tqdmProject-URL: changelog, https://tqdm.github.io/releasesProject-URL: wiki, https://github.com/tqdm/tqdm/wikiKeywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,timeClassifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Environment :: MacOS XClassifier: Environment :: Other EnvironmentClassifier: Environment :: Win32 (MS Windows)Classifier: Environment :: X11 ApplicationsClassifier: Framework :: IPythonClassifier: Framework :: JupyterClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: End Users/DesktopClassifier: Intended Audience :: Other AudienceClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: MacOSClassifier: Operating System :: MacOS :: MacOS XClassifier: Operating System :: MicrosoftClassifier: Operating System :: Microsoft :: MS-DOSClassifier: Operating System :: Microsoft :: WindowsClassifier: Operating System :: POSIXClassifier: Operating System :: POSIX :: BSDClassifier: Operating System :: POSIX :: BSD :: FreeBSDClassifier: Operating System :: POSIX :: LinuxClassifier: Operating System :: POSIX :: SunOS/SolarisClassifier: Operating System :: UnixClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: ImplementationClassifier: Programming Language :: Python :: Implementation :: IronPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Unix ShellClassifier: Topic :: Desktop EnvironmentClassifier: Topic :: Education :: Computer Aided Instruction (CAI)Classifier: Topic :: Education :: TestingClassifier: Topic :: Office/BusinessClassifier: Topic :: Other/Nonlisted TopicClassifier: Topic :: Software Development :: Build ToolsClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Software Development :: Pre-processorsClassifier: Topic :: Software Development :: User InterfacesClassifier: Topic :: System :: Installation/SetupClassifier: Topic :: System :: LoggingClassifier: Topic :: System :: MonitoringClassifier: Topic :: System :: ShellsClassifier: Topic :: TerminalsClassifier: Topic :: UtilitiesRequires-Python: >=3.8Description-Content-Type: text/x-rstLicense-File: LICENCERequires-Dist: colorama; platform_system == "Windows"Provides-Extra: discordRequires-Dist: requests; extra == "discord"Requires-Dist: envwrap; extra == "discord"Provides-Extra: slackRequires-Dist: slack-sdk; extra == "slack"Requires-Dist: envwrap; extra == "slack"Provides-Extra: telegramRequires-Dist: requests; extra == "telegram"Requires-Dist: envwrap; extra == "telegram"Provides-Extra: notebookRequires-Dist: ipywidgets>=6; extra == "notebook"Dynamic: license-file
|Logo|
tqdm====
|Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
|Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
|LICENCE| |OpenHub-Status| |colab-demo| |binder-demo| |awesome-python|
``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
Instantly make your loops show a smart progress meter - just wrap anyiterable with ``tqdm(iterable)``, and you're done!
.. code:: python
from tqdm import tqdm for i in tqdm(range(10000)): ...
``76%|████████████████████████ | 7568/10000 [00:33<00:10, 229.00it/s]``
``trange(N)`` can be also used as a convenient shortcut for``tqdm(range(N))``.
|Screenshot| |Video| |Slides| |Merch|
It can also be executed as a module with pipes:
.. code:: sh
$ seq 9999999 | tqdm --bytes | wc -l 75.2MB [00:00, 217MB/s] 9999999
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \ > backup.tgz 32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and isunit tested against performance regression.By comparison, the well-established`ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ hasan 800ns/iter overhead.
In addition to its low overhead, ``tqdm`` uses smart algorithms to predictthe remaining time and to skip unnecessary iteration displays, which allowsfor a negligible overhead in most cases.
``tqdm`` works on any platform(Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
``tqdm`` does not require any dependencies (not even ``curses``!), justPython and an environment supporting ``carriage return \r`` and``line feed \n`` control characters.
**Featured Sponsors**
======== ================================================|OpenAI| Your Logo Here======== ================================================OpenAI `Sponsors <https://github.com/sponsors/tqdm>`__======== ================================================
.. |OpenAI| image:: https://avatars.githubusercontent.com/u/14957082?s=96 :target: https://openai.com
------------------------------------------
.. contents:: Table of contents :backlinks: top :local:
Installation------------
Latest PyPI stable release~~~~~~~~~~~~~~~~~~~~~~~~~~
|Versions| |PyPI-Downloads| |Libraries-Dependents|
.. code:: sh
pip install tqdm
Latest development release on GitHub~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
Pull and install pre-release ``devel`` branch:
.. code:: sh
pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
Latest Conda release~~~~~~~~~~~~~~~~~~~~
|Conda-Forge-Status|
.. code:: sh
conda install -c conda-forge tqdm
Latest Snapcraft release~~~~~~~~~~~~~~~~~~~~~~~~
|Snapcraft|
There are 3 channels to choose from:
.. code:: sh
snap install tqdm # implies --stable, i.e. latest tagged release snap install tqdm --candidate # master branch snap install tqdm --edge # devel branch
Note that ``snap`` binaries are purely for CLI use (not ``import``-able), andautomatically set up ``bash`` tab-completion.
Latest Docker release~~~~~~~~~~~~~~~~~~~~~
|Docker|
.. code:: sh
docker pull tqdm/tqdm docker run -i --rm tqdm/tqdm --help
Other~~~~~
There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
|Repology|
.. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg :target: https://repology.org/project/python:tqdm/versions
Changelog---------
The list of all changes is available either on GitHub's Releases:|GitHub-Status|, on the`wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the`website <https://tqdm.github.io/releases>`__.
Usage-----
``tqdm`` is very versatile and can be used in a number of ways.The three main ones are given below.
Iterable-based~~~~~~~~~~~~~~
Wrap ``tqdm()`` around any iterable:
.. code:: python
from tqdm import tqdm from time import sleep
text = "" for char in tqdm(["a", "b", "c", "d"]): sleep(0.25) text = text + char
``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
.. code:: python
from tqdm import trange
for i in trange(100): sleep(0.01)
Instantiation outside of the loop allows for manual control over ``tqdm()``:
.. code:: python
pbar = tqdm(["a", "b", "c", "d"]) for char in pbar: sleep(0.25) pbar.set_description("Processing %s" % char)
Manual~~~~~~
Manual control of ``tqdm()`` updates using a ``with`` statement:
.. code:: python
with tqdm(total=100) as pbar: for i in range(10): sleep(0.1) pbar.update(10)
If the optional variable ``total`` (or an iterable with ``len()``) isprovided, predictive stats are displayed.
``with`` is also optional (you can just assign ``tqdm()`` to a variable,but in this case don't forget to ``del`` or ``close()`` at the end:
.. code:: python
pbar = tqdm(total=100) for i in range(10): sleep(0.1) pbar.update(10) pbar.close()
Module~~~~~~
Perhaps the most wonderful use of ``tqdm`` is in a script or on the commandline. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will passthrough all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
The example below demonstrate counting the number of lines in all Python filesin the current directory, with timing information included.
.. code:: sh
$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l 857365
real 0m3.458s user 0m0.274s sys 0m3.325s
$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l 857366it [00:03, 246471.31it/s] 857365
real 0m3.585s user 0m0.862s sys 0m3.358s
Note that the usual arguments for ``tqdm`` can also be specified.
.. code:: sh
$ find . -name '*.py' -type f -exec cat \{} \; | tqdm --unit loc --unit_scale --total 857366 >> /dev/null 100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
Backing up a large directory?
.. code:: sh
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \ > backup.tgz 44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
This can be beautified further:
.. code:: sh
$ BYTES=$(du -sb docs/ | cut -f1) $ tar -cf - docs/ \ | tqdm --bytes --total "$BYTES" --desc Processing | gzip \ | tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \ > ~/backup.tgz Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s] Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
Or done on a file level using 7-zip:
.. code:: sh
$ 7z a -bd -r backup.7z docs/ | grep Compressing \ | tqdm --total $(find docs/ -type f | wc -l) --unit files \ | grep -v Compressing 100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
Pre-existing CLI programs already outputting basic progress information willbenefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
.. code:: sh
$ seq 3 0.1 5 | tqdm --total 5 --update_to --null 100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s] $ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations 55it [00:00, 90006.52it/s]
FAQ and Known Issues--------------------
|GitHub-Issues|
The most common issues relate to excessive output on multiple lines, insteadof a neat one-line progress bar.
- Consoles in general: require support for carriage return (``CR``, ``\r``).
* Some cloud logging consoles which don't support ``\r`` properly (`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__, `K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from ``export TQDM_POSITION=-1``.
- Nested progress bars:
* Consoles in general: require support for moving cursors up to the previous line. For example, `IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__, `ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and `PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also `here <https://github.com/tqdm/tqdm/issues/208>`__, `here <https://github.com/tqdm/tqdm/issues/307>`__, and `here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__) lack full support. * Windows: additionally may require the Python module ``colorama`` to ensure nested bars stay within their respective lines.
- Unicode:
* Environments which report that they support unicode will have solid smooth progress bars. The fallback is an ``ascii``-only bar. * Windows consoles often only partially support unicode and thus `often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__ (also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to either normal-width unicode characters being incorrectly displayed as "wide", or some unicode characters not rendering.
- Wrapping generators:
* Generator wrapper functions tend to hide the length of iterables. ``tqdm`` does not. * Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or ``tqdm(enumerate(x), total=len(x), ...)``. The same applies to ``numpy.ndenumerate``. * Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even ``zip(tqdm(a), tqdm(b))``. * The same applies to ``itertools``. * Some useful convenience functions can be found under ``tqdm.contrib``.
- `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__: use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
- Overriding defaults via environment variables: e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam. This override logic is handled by the ``tqdm.utils.envwrap`` decorator (useful independent of ``tqdm``).
If you come across any other difficulties, browse and file |GitHub-Issues|.
Documentation-------------
|Py-Versions| |README-Hits| (Since 19 May 2016)
.. code:: python
class tqdm(): """ Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progress bar every time a value is requested. """
@envwrap("tqdm") # override defaults via env vars def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0):
Parameters~~~~~~~~~~
* iterable : iterable, optional Iterable to decorate with a progress bar. Leave blank to manually manage the updates.* desc : str, optional Prefix for the progress bar.* total : int or float, optional The number of expected iterations. If unspecified, len(iterable) is used if possible. If float("inf") or as a last resort, only basic progress statistics are displayed (no ETA, no progress bar). If ``gui`` is True and this parameter needs subsequent updating, specify an initial arbitrary large positive number, e.g. 9e9.* leave : bool, optional If [default: True], keeps all traces of the progress bar upon termination of iteration. If ``None``, will leave only if ``position`` is ``0``.* file : ``io.TextIOWrapper`` or ``io.StringIO``, optional Specifies where to output the progress messages (default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()`` methods. For encoding, see ``write_bytes``.* ncols : int, optional The width of the entire output message. If specified, dynamically resizes the progress bar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).* mininterval : float, optional Minimum progress display update interval [default: 0.1] seconds.* maxinterval : float, optional Maximum progress display update interval [default: 10] seconds. Automatically adjusts ``miniters`` to correspond to ``mininterval`` after long display update lag. Only works if ``dynamic_miniters`` or monitor thread is enabled.* miniters : int or float, optional Minimum progress display update interval, in iterations. If 0 and ``dynamic_miniters``, will automatically adjust to equal ``mininterval`` (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and ``mininterval`` to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1.* ascii : bool or str, optional If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters " 123456789#".* disable : bool, optional Whether to disable the entire progress bar wrapper [default: False]. If set to None, disable on non-TTY.* unit : str, optional String that will be used to define the unit of each iteration [default: it].* unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale ``total`` and ``n``.* dynamic_ncols : bool, optional If set, constantly alters ``ncols`` and ``nrows`` to the environment (allowing for window resizes) [default: False].* smoothing : float, optional Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].* bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing ": " is automatically removed after {desc} if the latter is empty.* initial : int or float, optional The initial counter value. Useful when restarting a progress bar [default: 0]. If using float, consider specifying ``{n:.3f}`` or similar in ``bar_format``, or specifying ``unit_scale``.* position : int, optional Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).* postfix : dict or ``*``, optional Specify additional stats to display at the end of the bar. Calls ``set_postfix(**postfix)`` if possible (dict).* unit_divisor : float, optional [default: 1000], ignored unless ``unit_scale`` is True.* write_bytes : bool, optional Whether to write bytes. If (default: False) will write unicode.* lock_args : tuple, optional Passed to ``refresh`` for intermediate output (initialisation, iterating, and updating).* nrows : int, optional The screen height. If specified, hides nested bars outside this bound. If unspecified, attempts to use environment height. The fallback is 20.* colour : str, optional Bar colour (e.g. 'green', '#00ff00').* delay : float, optional Don't display until [default: 0] seconds have elapsed.
Extra CLI Options~~~~~~~~~~~~~~~~~
* delim : chr, optional Delimiting character [default: '\n']. Use '\0' for null. N.B.: on Windows systems, Python converts '\n' to '\r\n'.* buf_size : int, optional String buffer size in bytes [default: 256] used when ``delim`` is specified.* bytes : bool, optional If true, will count bytes, ignore ``delim``, and default ``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.* tee : bool, optional If true, passes ``stdin`` to both ``stderr`` and ``stdout``.* update : bool, optional If true, will treat input as newly elapsed iterations, i.e. numbers to pass to ``update()``. Note that this is slow (~2e5 it/s) since every input must be decoded as a number.* update_to : bool, optional If true, will treat input as total elapsed iterations, i.e. numbers to assign to ``self.n``. Note that this is slow (~2e5 it/s) since every input must be decoded as a number.* null : bool, optional If true, will discard input (no stdout).* manpath : str, optional Directory in which to install tqdm man pages.* comppath : str, optional Directory in which to place tqdm completion.* log : str, optional CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
Returns~~~~~~~
* out : decorated iterator.
.. code:: python
class tqdm(): def update(self, n=1): """ Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if `t.update()` will be called in such a way that `filesize` will be exactly reached and printed.
Parameters ---------- n : int or float, optional Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying `{n:.3f}` or similar in `bar_format`, or specifying `unit_scale`.
Returns ------- out : bool or None True if a `display()` was triggered. """
def close(self): """Cleanup and (if leave=False) close the progress bar."""
def clear(self, nomove=False): """Clear current bar display."""
def refresh(self): """ Force refresh the display of this bar.
Parameters ---------- nolock : bool, optional If `True`, does not lock. If [default: `False`]: calls `acquire()` on internal lock. lock_args : tuple, optional Passed to internal lock's `acquire()`. If specified, will only `display()` if `acquire()` returns `True`. """
def unpause(self): """Restart tqdm timer from last print time."""
def reset(self, total=None): """ Resets to 0 iterations for repeated use.
Consider combining with `leave=True`.
Parameters ---------- total : int or float, optional. Total to use for the new bar. """
def set_description(self, desc=None, refresh=True): """ Set/modify description of the progress bar.
Parameters ---------- desc : str, optional refresh : bool, optional Forces refresh [default: True]. """
def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs): """ Set/modify postfix (additional stats) with automatic formatting based on datatype.
Parameters ---------- ordered_dict : dict or OrderedDict, optional refresh : bool, optional Forces refresh [default: True]. kwargs : dict, optional """
@classmethod def write(cls, s, file=sys.stdout, end="\n"): """Print a message via tqdm (without overlap with bars)."""
@property def format_dict(self): """Public API for read-only member access."""
def display(self, msg=None, pos=None): """ Use `self.sp` to display `msg` in the specified `pos`.
Consider overloading this function when inheriting to use e.g.: `self.some_frontend(**self.format_dict)` instead of `self.sp`.
Parameters ---------- msg : str, optional. What to display (default: `repr(self)`). pos : int, optional. Position to `moveto` (default: `abs(self.pos)`). """
@classmethod @contextmanager def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs): """ stream : file-like object. method : str, "read" or "write". The result of `read()` and the first argument of `write()` should have a `len()`.
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj: ... while True: ... chunk = fobj.read(chunk_size) ... if not chunk: ... break """
@classmethod def pandas(cls, *targs, **tqdm_kwargs): """Registers the current `tqdm` class with `pandas`."""
def trange(*args, **tqdm_kwargs): """Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
Convenience Functions~~~~~~~~~~~~~~~~~~~~~
.. code:: python
def tqdm.contrib.tenumerate(iterable, start=0, total=None, tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs): """Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs): """Equivalent of builtin `zip`."""
def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs): """Equivalent of builtin `map`."""
Submodules~~~~~~~~~~
.. code:: python
class tqdm.notebook.tqdm(tqdm.tqdm): """IPython/Jupyter Notebook widget."""
class tqdm.auto.tqdm(tqdm.tqdm): """Automatically chooses between `tqdm.notebook` and `tqdm.tqdm`."""
class tqdm.asyncio.tqdm(tqdm.tqdm): """Asynchronous version.""" @classmethod def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs): """Wrapper for `asyncio.as_completed`."""
class tqdm.gui.tqdm(tqdm.tqdm): """Matplotlib GUI version."""
class tqdm.tk.tqdm(tqdm.tqdm): """Tkinter GUI version."""
class tqdm.rich.tqdm(tqdm.tqdm): """`rich.progress` version."""
class tqdm.keras.TqdmCallback(keras.callbacks.Callback): """Keras callback for epoch and batch progress."""
class tqdm.dask.TqdmCallback(dask.callbacks.Callback): """Dask callback for task progress."""
``contrib``+++++++++++
The ``tqdm.contrib`` package also contains experimental modules:
- `tqdm.contrib.itertools <https://tqdm.github.io/docs/contrib.itertools/>`_: Thin wrappers around ``itertools``- `tqdm.contrib.concurrent <https://tqdm.github.io/docs/contrib.concurrent/>`_: Thin wrappers around ``concurrent.futures``- `tqdm.contrib.slack <https://tqdm.github.io/docs/contrib.slack/>`_: Posts to `Slack <https://slack.com>`__ bots- `tqdm.contrib.discord <https://tqdm.github.io/docs/contrib.discord/>`_: Posts to `Discord <https://discord.com>`__ bots- `tqdm.contrib.telegram <https://tqdm.github.io/docs/contrib.telegram/>`_: Posts to `Telegram <https://telegram.org>`__ bots- `tqdm.contrib.bells <https://tqdm.github.io/docs/shortcuts/>`_: Automagically enables all optional features
* ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
.. image:: https://tqdm.github.io/img/screenshot-discord.png :alt: Screenshot of `tqdm.contrib.discord` in action
Examples and Advanced Usage---------------------------
- See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__ folder;- import the module and run ``help()``;- consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
* this has an `excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__ on how to make a **great** progress bar;
- check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or- run the |binder-demo|.
Description and additional stats~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Custom information can be displayed and updated dynamically on ``tqdm`` barswith the ``desc`` and ``postfix`` arguments:
.. code:: python
from tqdm import tqdm, trange from random import random, randint from time import sleep
with trange(10) as t: for i in t: # Description will be displayed on the left t.set_description('GEN %i' % i) # Postfix will be displayed on the right, # formatted automatically based on argument's datatype t.set_postfix(loss=random(), gen=randint(1,999), str='h', lst=[1, 2]) sleep(0.1)
with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}", postfix=["Batch", {"value": 0}]) as t: for i in range(10): sleep(0.1) t.postfix[1]["value"] = i / 2 t.update()
Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
- ``postfix`` also needs to be passed as an initial argument in a compatible format, and- ``postfix`` will be auto-converted to a string if it is a ``dict``-like object. To prevent this behaviour, insert an extra item into the dictionary where the key is not a string.
Additional ``bar_format`` parameters may also be defined by overriding``format_dict``, and the bar itself may be modified using ``ascii``:
.. code:: python
from tqdm import tqdm class TqdmExtraFormat(tqdm): """Provides a `total_time` format parameter""" @property def format_dict(self): d = super().format_dict total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1) d.update(total_time=self.format_interval(total_time) + " in total") return d
for i in TqdmExtraFormat( range(9), ascii=" .oO0", bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"): if i == 4: break
.. code::
00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
Note that ``{bar}`` also supports a format specifier ``[width][type]``.
- ``width``
* unspecified (default): automatic to fill ``ncols`` * ``int >= 0``: fixed width overriding ``ncols`` logic * ``int < 0``: subtract from the automatic default
- ``type``
* ``a``: ascii (``ascii=True`` override) * ``u``: unicode (``ascii=False`` override) * ``b``: blank (``ascii=" "`` override)
This means a fixed bar with right-justified text may be created by using:``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
Nested progress bars~~~~~~~~~~~~~~~~~~~~
``tqdm`` supports nested progress bars. Here's an example:
.. code:: python
from tqdm.auto import trange from time import sleep
for i in trange(4, desc='1st loop'): for j in trange(5, desc='2nd loop'): for k in trange(50, desc='3rd loop', leave=False): sleep(0.01)
For manual control over positioning (e.g. for multi-processing use),you may specify ``position=n`` where ``n=0`` for the outermost bar,``n=1`` for the next, and so on.However, it's best to check if ``tqdm`` can work without manual ``position``first.
.. code:: python
from time import sleep from tqdm import trange, tqdm from multiprocessing import Pool, RLock, freeze_support
L = list(range(9))
def progresser(n): interval = 0.001 / (n + 2) total = 5000 text = f"#{n}, est. {interval * total:<04.2}s" for _ in trange(total, desc=text, position=n): sleep(interval)
if __name__ == '__main__': freeze_support() # for Windows support tqdm.set_lock(RLock()) # for managing output contention p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),)) p.map(progresser, L)
Note that in Python 3, ``tqdm.write`` is thread-safe:
.. code:: python
from time import sleep from tqdm import tqdm, trange from concurrent.futures import ThreadPoolExecutor
L = list(range(9))
def progresser(n): interval = 0.001 / (n + 2) total = 5000 text = f"#{n}, est. {interval * total:<04.2}s" for _ in trange(total, desc=text): sleep(interval) if n == 6: tqdm.write("n == 6 completed.") tqdm.write("`tqdm.write()` is thread-safe in py3!")
if __name__ == '__main__': with ThreadPoolExecutor() as p: p.map(progresser, L)
Hooks and callbacks~~~~~~~~~~~~~~~~~~~
``tqdm`` can easily support callbacks/hooks and manual updates.Here's an example with ``urllib``:
**``urllib.urlretrieve`` documentation**
| [...] | If present, the hook function will be called once | on establishment of the network connection and once after each block read | thereafter. The hook will be passed three arguments; a count of blocks | transferred so far, a block size in bytes, and the total size of the file. | [...]
.. code:: python
import urllib, os from tqdm import tqdm urllib = getattr(urllib, 'request', urllib)
class TqdmUpTo(tqdm): """Provides `update_to(n)` which uses `tqdm.update(delta_n)`.""" def update_to(self, b=1, bsize=1, tsize=None): """ b : int, optional Number of blocks transferred so far [default: 1]. bsize : int, optional Size of each block (in tqdm units) [default: 1]. tsize : int, optional Total size (in tqdm units). If [default: None] remains unchanged. """ if tsize is not None: self.total = tsize return self.update(b * bsize - self.n) # also sets self.n = b * bsize
eg_link = "https://cgi.cdcl.ml/matryoshka.zip" with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1, desc=eg_link.split('/')[-1]) as t: # all optional kwargs urllib.urlretrieve(eg_link, filename=os.devnull, reporthook=t.update_to, data=None) t.total = t.n
Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.Functional alternative in`examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
It is recommend to use ``miniters=1`` whenever there is potentiallylarge differences in iteration speed (e.g. downloading a file overa patchy connection).
**Wrapping read/write methods**
To measure throughput through a file-like object's ``read`` or ``write``methods, use ``CallbackIOWrapper``:
.. code:: python
from tqdm.auto import tqdm from tqdm.utils import CallbackIOWrapper
with tqdm(total=file_obj.size, unit='B', unit_scale=True, unit_divisor=1024) as t: fobj = CallbackIOWrapper(t.update, file_obj, "read") while True: chunk = fobj.read(chunk_size) if not chunk: break t.reset() # ... continue to use `t` for something else
Alternatively, use the even simpler ``wrapattr`` convenience function,which would condense both the ``urllib`` and ``CallbackIOWrapper`` examplesdown to:
.. code:: python
import urllib, os from tqdm import tqdm
eg_link = "https://cgi.cdcl.ml/matryoshka.zip" response = getattr(urllib, 'request', urllib).urlopen(eg_link) with tqdm.wrapattr(open(os.devnull, "wb"), "write", miniters=1, desc=eg_link.split('/')[-1], total=getattr(response, 'length', None)) as fout: for chunk in response: fout.write(chunk)
The ``requests`` equivalent is nearly identical:
.. code:: python
import requests, os from tqdm import tqdm
eg_link = "https://cgi.cdcl.ml/matryoshka.zip" response = requests.get(eg_link, stream=True) with tqdm.wrapattr(open(os.devnull, "wb"), "write", miniters=1, desc=eg_link.split('/')[-1], total=int(response.headers.get('content-length', 0))) as fout: for chunk in response.iter_content(chunk_size=4096): fout.write(chunk)
**Custom callback**
``tqdm`` is known for intelligently skipping unnecessary displays. To make acustom callback take advantage of this, simply use the return value of``update()``. This is set to ``True`` if a ``display()`` was triggered.
.. code:: python
from tqdm.auto import tqdm as std_tqdm
def external_callback(*args, **kwargs): ...
class TqdmExt(std_tqdm): def update(self, n=1): displayed = super().update(n) if displayed: external_callback(**self.format_dict) return displayed
``asyncio``~~~~~~~~~~~
Note that ``break`` isn't currently caught by asynchronous iterators.This means that ``tqdm`` cannot clean up after itself in this case:
.. code:: python
from tqdm.asyncio import tqdm
async for i in tqdm(range(9)): if i == 2: break
Instead, either call ``pbar.close()`` manually or use the context manager syntax:
.. code:: python
from tqdm.asyncio import tqdm
with tqdm(range(9)) as pbar: async for i in pbar: if i == 2: break
Pandas Integration~~~~~~~~~~~~~~~~~~
Due to popular demand we've added support for ``pandas`` -- here's an examplefor ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
.. code:: python
import pandas as pd import numpy as np from tqdm import tqdm
df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm` # (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.) tqdm.pandas(desc="my bar!")
# Now you can use `progress_apply` instead of `apply` # and `progress_map` instead of `map` df.progress_apply(lambda x: x**2) # can also groupby: # df.groupby(0).progress_apply(lambda x: x**2)
In case you're interested in how this works (and how to modify it for yourown callbacks), see the`examples <https://github.com/tqdm/tqdm/tree/master/examples>`__folder or import the module and run ``help()``.
Keras Integration~~~~~~~~~~~~~~~~~
A ``keras`` callback is also available:
.. code:: python
from tqdm.keras import TqdmCallback
...
model.fit(..., verbose=0, callbacks=[TqdmCallback()])
Dask Integration~~~~~~~~~~~~~~~~
A ``dask`` callback is also available:
.. code:: python
from tqdm.dask import TqdmCallback
with TqdmCallback(desc="compute"): ... arr.compute()
# or use callback globally cb = TqdmCallback(desc="global") cb.register() arr.compute()
IPython/Jupyter Integration~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
.. code:: python
from tqdm.notebook import trange, tqdm from time import sleep
for i in trange(3, desc='1st loop'): for j in tqdm(range(100), desc='2nd loop'): sleep(0.01)
In addition to ``tqdm`` features, the submodule provides a native Jupyterwidget (compatible with IPython v1-v4 and Jupyter), fully working nested barsand colour hints (blue: normal, green: completed, red: error/interrupt,light blue: no ETA); as demonstrated below.
|Screenshot-Jupyter1||Screenshot-Jupyter2||Screenshot-Jupyter3|
The ``notebook`` version supports percentage or pixels for overall width(e.g.: ``ncols='100%'`` or ``ncols='480px'``).
It is also possible to let ``tqdm`` automatically choose betweenconsole or notebook versions by using the ``autonotebook`` submodule:
.. code:: python
from tqdm.autonotebook import tqdm tqdm.pandas()
Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebooksince it is not meant to be possible to distinguish between ``jupyter notebook``and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppressthis warning.
Note that notebooks will display the bar in the cell where it was created.This may be a different cell from the one where it is used.If this is not desired, either
- delay the creation of the bar to the cell where it must be displayed, or- create the bar with ``display=False``, and in a later cell call ``display(bar.container)``:
.. code:: python
from tqdm.notebook import tqdm pbar = tqdm(..., display=False)
.. code:: python
# different cell display(pbar.container)
The ``keras`` callback has a ``display()`` method which can be used likewise:
.. code:: python
from tqdm.keras import TqdmCallback cbk = TqdmCallback(display=False)
.. code:: python
# different cell cbk.display() model.fit(..., verbose=0, callbacks=[cbk])
Another possibility is to have a single bar (near the top of the notebook)which is constantly re-used (using ``reset()`` rather than ``close()``).For this reason, the notebook version (unlike the CLI version) does notautomatically call ``close()`` upon ``Exception``.
.. code:: python
from tqdm.notebook import tqdm pbar = tqdm()
.. code:: python
# different cell iterable = range(100) pbar.reset(total=len(iterable)) # initialise with new `total` for i in iterable: pbar.update() pbar.refresh() # force print final status but don't `close()`
Custom Integration~~~~~~~~~~~~~~~~~~
To change the default arguments (such as making ``dynamic_ncols=True``),simply use built-in Python magic:
.. code:: python
from functools import partial from tqdm import tqdm as std_tqdm tqdm = partial(std_tqdm, dynamic_ncols=True)
For further customisation,``tqdm`` may be inherited from to create custom callbacks (as with the``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends(e.g. GUIs such as notebook or plotting packages). In the latter case:
1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable terminal ``status_printer`` creation.2. Redefine: ``close()``, ``clear()``, ``display()``.
Consider overloading ``display()`` to use e.g.``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
Some submodule examples of inheritance:
- `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__- `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__- `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__- `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__- `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__- `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
Dynamic Monitor/Meter~~~~~~~~~~~~~~~~~~~~~
You can use a ``tqdm`` as a meter which is not monotonically increasing.This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``changes.
One example would be recursively searching for files. The ``total`` is thenumber of objects found so far, while ``n`` is the number of those objects whichare files (rather than folders):
.. code:: python
from tqdm import tqdm import os.path
def find_files_recursively(path, show_progress=True): files = [] # total=1 assumes `path` is a file t = tqdm(total=1, unit="file", disable=not show_progress) if not os.path.exists(path): raise IOError("Cannot find:" + path)
def append_found_file(f): files.append(f) t.update()
def list_found_dir(path): """returns os.listdir(path) assuming os.path.isdir(path)""" listing = os.listdir(path) # subtract 1 since a "file" we found was actually this directory t.total += len(listing) - 1 # fancy way to give info without forcing a refresh t.set_postfix(dir=path[-10:], refresh=False) t.update(0) # may trigger a refresh return listing
def recursively_search(path): if os.path.isdir(path): for f in list_found_dir(path): recursively_search(os.path.join(path, f)) else: append_found_file(path)
recursively_search(path) t.set_postfix(dir=path) t.close() return files
Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger adisplay refresh to avoid console spamming.
Writing messages~~~~~~~~~~~~~~~~
This is a work in progress (see`#737 <https://github.com/tqdm/tqdm/issues/737>`__).
Since ``tqdm`` uses a simple printing mechanism to display progress bars,you should not write any message in the terminal using ``print()`` whilea progress bar is open.
To write messages in the terminal without any collision with ``tqdm`` bardisplay, a ``.write()`` method is provided:
.. code:: python
from tqdm.auto import tqdm, trange from time import sleep
bar = trange(10) for i in bar: # Print using tqdm class method .write() sleep(0.1) if not (i % 3): tqdm.write("Done task %i" % i) # Can also use bar.write()
By default, this will print to standard output ``sys.stdout``. but you canspecify any file-like object using the ``file`` argument. For example, thiscan be used to redirect the messages writing to a log file or class.
Redirecting writing~~~~~~~~~~~~~~~~~~~
If using a library that can print messages to the console, editing the libraryby replacing ``print()`` with ``tqdm.write()`` may not be desirable.In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
To redirect ``sys.stdout``, create a file-like class that will writeany input string to ``tqdm.write()``, and supply the arguments``file=sys.stdout, dynamic_ncols=True``.
A reusable canonical example is given below:
.. code:: python
from time import sleep import contextlib import sys from tqdm import tqdm from tqdm.contrib import DummyTqdmFile
@contextlib.contextmanager def std_out_err_redirect_tqdm(): orig_out_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err) yield orig_out_err[0] # Relay exceptions except Exception as exc: raise exc # Always restore sys.stdout/err if necessary finally: sys.stdout, sys.stderr = orig_out_err
def some_fun(i): print("Fee, fi, fo,".split()[i])
# Redirect stdout to tqdm.write() (don't forget the `as save_stdout`) with std_out_err_redirect_tqdm() as orig_stdout: # tqdm needs the original stdout # and dynamic_ncols=True to autodetect console width for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True): sleep(.5) some_fun(i)
# After the `with`, printing is restored print("Done!")
Redirecting ``logging``~~~~~~~~~~~~~~~~~~~~~~~
Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``may also be redirected to ``tqdm.write()``.
Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure toredirect ``logging`` first if needed.
Helper methods are available in ``tqdm.contrib.logging``. For example:
.. code:: python
import logging from tqdm import trange from tqdm.contrib.logging import logging_redirect_tqdm
LOG = logging.getLogger(__name__)
if __name__ == '__main__': logging.basicConfig(level=logging.INFO) with logging_redirect_tqdm(): for i in trange(9): if i == 4: LOG.info("console logging redirected to `tqdm.write()`") # logging restored
Monitoring thread, intervals and miniters~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
- Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long to wait between each refresh. ``tqdm`` always gets updated in the background, but it will display only every ``mininterval``.- Reduce number of calls to check system clock/time.- ``mininterval`` is more intuitive to configure than ``miniters``. A clever adjustment system ``dynamic_miniters`` will automatically adjust ``miniters`` to the amount of iterations that fit into time ``mininterval``. Essentially, ``tqdm`` will check if it's time to print without actually checking time. This behaviour can be still be bypassed by manually setting ``miniters``.
However, consider a case with a combination of fast and slow iterations.After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to alarge number. When iteration rate subsequently slows, ``miniters`` willremain large and thus reduce display update frequency. To address this:
- ``maxinterval`` defines the maximum time between display refreshes. A concurrent monitoring thread checks for overdue updates and forces one where necessary.
The monitoring thread should not have a noticeable overhead, and guaranteesupdates at least every 10 seconds by default.This value can be directly changed by setting the ``monitor_interval`` ofany ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).The monitor thread may be disabled application-wide by setting``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
Merch-----
You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
Contributions-------------
|GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.Contributions are welcome.
See the`CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__file for more information.
Developers who have contributed more that 5 *loc* (surviving lines of code):
|git-fame|
Honourable mentions:
- Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ primary maintainer |Gift-Casper|- Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ maintainer- Hadrien Mary `hadim <https://github.com/hadim>`__ maintainer- Mikhail Korobov `kmike <https://github.com/kmike>`__ maintainer- Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ original author
Ports to Other Languages~~~~~~~~~~~~~~~~~~~~~~~~
A list is available on`this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
LICENCE-------
Open Source (OSI approved): |LICENCE|
Citation information: |DOI|
|README-Hits| (Since 19 May 2016)
.. |Logo| image:: https://tqdm.github.io/img/logo.gif.. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif.. |Video| image:: https://tqdm.github.io/img/video.jpg :target: https://tqdm.github.io/video.. |Slides| image:: https://tqdm.github.io/img/slides.jpg :target: https://tqdm.github.io/PyData2019/slides.html.. |Merch| image:: https://tqdm.github.io/img/merch.jpg :target: https://tqdm.github.io/merch.. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub :target: https://github.com/tqdm/tqdm/actions/workflows/test.yml.. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls :target: https://coveralls.io/github/tqdm/tqdm.. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg :target: https://codecov.io/gh/tqdm/tqdm.. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177 :target: https://app.codacy.com/gh/tqdm/tqdm/dashboard.. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge :target: https://bestpractices.coreinfrastructure.org/projects/3264.. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/releases.. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/network.. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/stargazers.. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white :target: https://github.com/tqdm/tqdm/graphs/commit-activity.. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/issues?q=.. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/pulls.. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white :target: https://github.com/tqdm/tqdm/graphs/contributors.. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed :target: https://github.com/tqdm/tqdm/pulse.. |git-fame| image:: https://git-fame.cdcl.ml/gh/tqdm/tqdm?min=5&w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1 :alt: git-fame.cdcl.ml/gh/tqdm/tqdm :target: https://git-fame.cdcl.ml/gh/tqdm/tqdm?w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1.. |Gift-Casper| image:: https://img.shields.io/badge/sponsor-casper-ff69b4.svg :target: https://cdcl.ml/sponsor.. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg :target: https://tqdm.github.io/releases.. |PyPI-Downloads| image:: https://img.shields.io/pypi/dm/tqdm.svg?label=pypi%20downloads&logo=PyPI&logoColor=white :target: https://pepy.tech/project/tqdm.. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white :target: https://pypi.org/project/tqdm.. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge :target: https://anaconda.org/conda-forge/tqdm.. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft :target: https://snapcraft.io/tqdm.. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white :target: https://hub.docker.com/r/tqdm/tqdm.. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white :target: https://libraries.io/pypi/tqdm.. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white :target: https://github.com/tqdm/tqdm/network/dependents.. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif :target: https://www.openhub.net/p/tqdm?ref=Thin+badge.. |awesome-python| image:: https://awesome.re/mentioned-badge.svg :target: https://github.com/vinta/awesome-python.. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg :target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE.. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg :target: https://doi.org/10.5281/zenodo.595120.. |colab-demo| image:: https://colab.research.google.com/assets/colab-badge.svg :target: https://colab.research.google.com/github/tqdm/tqdm/blob/master/DEMO.ipynb.. |binder-demo| image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb.. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif.. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif.. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif.. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif :target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341Metadata-Version: 2.4Name: colorlogVersion: 6.12.0Summary: Add colours to the output of Python's logging module.Home-page: https://github.com/borntyping/python-colorlogAuthor: Sam ClementsAuthor-email: sam@borntyping.co.ukLicense: MIT LicenseClassifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.6Classifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Topic :: TerminalsClassifier: Topic :: UtilitiesRequires-Python: >=3.6Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: colorama; sys_platform == "win32"Provides-Extra: developmentRequires-Dist: black; extra == "development"Requires-Dist: flake8; extra == "development"Requires-Dist: mypy; extra == "development"Requires-Dist: pytest; extra == "development"Requires-Dist: types-colorama; extra == "development"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-pythonDynamic: summary
# Log formatting with colors!
[](https://pypi.org/project/colorlog/)[](https://pypi.org/project/colorlog/)
Add colours to the output of Python's `logging` module.
- [Source on GitHub](https://github.com/borntyping/python-colorlog)- [Package on PyPI](https://pypi.org/pypi/colorlog/)
## Status
colorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x)support Python 2.6 and above.
- colorlog 6.x requires Python 3.6 or higher.- colorlog 5.x is an interim version that will warn Python 2 users to downgrade.- colorlog 4.x is the final version supporting Python 2.
[colorama] is included as a dependency on Windows, where it is automaticallyinitialised to support colored output.
This library is over a decade old and supported a wide set of Python versionsfor most of its life, which has made it a difficult library to add new featuresto. colorlog 6 may break backwards compatibility so that newer featurescan be added more easily, but may still not accept all changes or featurerequests. colorlog 4 might accept essential bugfixes but should not beconsidered actively maintained and will not accept any major changes or newfeatures.
## Installation
Install from PyPI with:
```bashpip install colorlog```
Several Linux distributions provide official packages ([Debian], [Arch],[Fedora], [Gentoo], [OpenSuse] and [Ubuntu]), and others have user providedpackages ([BSD ports], [Conda]).
## Usage
```pythonimport colorlog
handler = colorlog.StreamHandler()handler.setFormatter(colorlog.ColoredFormatter())
logger = colorlog.getLogger('example')logger.addHandler(handler)```
### Arguments
`ColoredFormatter` extends [`logging.Formatter`][formatter] and accepts thefollowing arguments:
- `fmt` *(default=`None`)*: A format string used to output the message. If `None`, a default format string is selected based on `style` (e.g. `%(log_color)s%(levelname)s:%(name)s:%(message)s` for `%` style).- `datefmt`, `style`, `validate`, `defaults`: see [`logging.Formatter`][formatter].- `reset` *(default=`True`)*: Implicitly adds a color reset code to the message output, unless the output already ends with one.- `log_colors` *(default=`None`)*: A mapping of record level names to color names. If `None`, `colorlog.default_log_colors` is used.- `secondary_log_colors` *(default=`None`)*: A mapping of names to `log_colors` style mappings, defining additional colors that can be used in format strings. If `None`, an empty mapping is used.- `stream` *(default=`None`)*: The stream being written to (e.g. `sys.stderr`). Used to detect whether the output is a TTY. Colors are disabled automatically on non-TTY streams unless `force_color` is set.- `no_color` *(default=`False`)*: Disable color output. Can also be set via the `NO_COLOR` environment variable.- `force_color` *(default=`False`)*: Force color output even on non-TTY streams. Takes precedence over `no_color`. Can also be set via the `FORCE_COLOR` environment variable.
### Color escape codes
Color escape codes can be selected based on the log records level, by addingparameters to the format string:
- `log_color`: Return the color associated with the records level.- `<name>_log_color`: Return another color based on the records level if the formatter has secondary colors configured (see `secondary_log_colors` below).
Multiple escape codes can be used at once by joining them with commas whenconfiguring the color for a log level (but can't be used directly in the formatstring). For example, `black,bg_white` would use the escape codes for blacktext on a white background.
The following escape codes are made available for use in the format string:
- `{color}`, `fg_{color}`, `bg_{color}`: Foreground and background colors.- `bold`, `bold_{color}`, `fg_bold_{color}`, `bg_bold_{color}`: Bold/bright colors.- `thin`, `thin_{color}`, `fg_thin_{color}`: Thin colors (terminal dependent).- `reset`: Clear all formatting (both foreground and background colors).
The available color names are:
- `black`- `red`- `green`- `yellow`- `blue`- `purple`- `cyan`- `white`
You can also use "bright" colors. These aren't standard ANSI codes, andsupport for these varies wildly across different terminals.
- `light_black`- `light_red`- `light_green`- `light_yellow`- `light_blue`- `light_purple`- `light_cyan`- `light_white`
In addition to pre-defined color names, you can use integers from 0 to 255 for256-color support (e.g. `fg_196`, `bg_42`).
## Examples

The following snippet creates a `ColoredFormatter` for use in a logging setup,with a custom format string and log colors:
```pythonfrom colorlog import ColoredFormatter
formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", log_colors={ "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "red,bg_white", })```
*See `docs/example.py` for full example script.*
### Using `secondary_log_colors`
Secondary log colors are a way to have more than one color that is selectedbased on the log level. Each key in `secondary_log_colors` adds an attributethat can be used in format strings (`message` becomes `message_log_color`), andhas a corresponding value that is identical in format to the `log_colors`argument.
The following example highlights the level name using the default log colors,and highlights the message in red for `error` and `critical` level log messages.
```pythonfrom colorlog import ColoredFormatter
formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s", secondary_log_colors={ 'message': { 'ERROR': 'red', 'CRITICAL': 'red' } })```
### With [`dictConfig`][dictconfig]
```pythonlogging.config.dictConfig({ 'formatters': { 'colored': { '()': 'colorlog.ColoredFormatter', 'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s" } }})```
A full example dictionary can be found in `tests/test_colorlog.py`.
### With [`fileConfig`][fileconfig]
```ini...
[formatters]keys=color
[formatter_color]class=colorlog.ColoredFormatterformat=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfigdatefmt=%m-%d %H:%M:%S```
An instance of ColoredFormatter created with those arguments will then be usedby any handlers that are configured to use the `color` formatter.
A full example configuration can be found in `tests/test_config.ini`.
### With custom log levels
ColoredFormatter will work with custom log levels added with[`logging.addLevelName`][addlevelname]:
```pythonimport logging, colorlogTRACE = 5logging.addLevelName(TRACE, 'TRACE')formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'})handler = logging.StreamHandler()handler.setFormatter(formatter)logger = logging.getLogger('example')logger.addHandler(handler)logger.setLevel('TRACE')logger.log(TRACE, 'a message using a custom level')```
## Tests
Tests similar to the above examples are found in `tests/test_colorlog.py`.
## Status
colorlog is in maintenance mode. I try and ensure bugfixes are published,but compatibility a wide set of Python versions makes this a difficultcodebase to add features to. Any changes that might break backwardscompatibility for existing users will not be considered.
## Alternatives
There are some more modern libraries for improving Python logging you mayfind useful.
- [structlog]- [jsonlog]
## Projects using colorlog
GitHub provides [a list of projects that depend on colorlog][dependents].
Some early adopters included [Errbot], [Pythran], and [zenlog].
## Licence
Copyright (c) 2012-2025 Sam Clements <sam@borntyping.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy ofthis software and associated documentation files (the "Software"), to deal inthe Software without restriction, including without limitation the rights touse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ofthe Software, and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESSFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[addlevelname]: https://docs.python.org/3/library/logging.html#logging.addLevelName[arch]: https://archlinux.org/packages/extra/any/python-colorlog/[bsd ports]: https://www.freshports.org/devel/py-colorlog/[colorama]: https://pypi.python.org/pypi/colorama[conda]: https://anaconda.org/conda-forge/colorlog[debian]: https://packages.debian.org/trixie/python3-colorlog[dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D[dictconfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig[errbot]: http://errbot.io/[fedora]: https://src.fedoraproject.org/rpms/python-colorlog[fileconfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig[formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter[gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog[jsonlog]: https://github.com/borntyping/jsonlog[opensuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3[pythran]: https://github.com/serge-sans-paille/pythran[structlog]: https://www.structlog.org/en/stable/[ubuntu]: https://launchpad.net/python-colorlog[zenlog]: https://github.com/ManufacturaInd/python-zenlog123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778Metadata-Version: 2.1Name: cyclerVersion: 0.12.1Summary: Composable style cyclesAuthor-email: Thomas A Caswell <matplotlib-users@python.org>License: Copyright (c) 2015, matplotlib project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the matplotlib project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Project-URL: homepage, https://matplotlib.org/cycler/Project-URL: repository, https://github.com/matplotlib/cyclerKeywords: cycle kwargsClassifier: License :: OSI Approved :: BSD LicenseClassifier: Development Status :: 4 - BetaClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3 :: OnlyRequires-Python: >=3.8Description-Content-Type: text/x-rstLicense-File: LICENSEProvides-Extra: docsRequires-Dist: ipython ; extra == 'docs'Requires-Dist: matplotlib ; extra == 'docs'Requires-Dist: numpydoc ; extra == 'docs'Requires-Dist: sphinx ; extra == 'docs'Provides-Extra: testsRequires-Dist: pytest ; extra == 'tests'Requires-Dist: pytest-cov ; extra == 'tests'Requires-Dist: pytest-xdist ; extra == 'tests'
|PyPi|_ |Conda|_ |Supported Python versions|_ |GitHub Actions|_ |Codecov|_
.. |PyPi| image:: https://img.shields.io/pypi/v/cycler.svg?style=flat.. _PyPi: https://pypi.python.org/pypi/cycler
.. |Conda| image:: https://img.shields.io/conda/v/conda-forge/cycler.. _Conda: https://anaconda.org/conda-forge/cycler
.. |Supported Python versions| image:: https://img.shields.io/pypi/pyversions/cycler.svg.. _Supported Python versions: https://pypi.python.org/pypi/cycler
.. |GitHub Actions| image:: https://github.com/matplotlib/cycler/actions/workflows/tests.yml/badge.svg.. _GitHub Actions: https://github.com/matplotlib/cycler/actions
.. |Codecov| image:: https://codecov.io/github/matplotlib/cycler/badge.svg?branch=main&service=github.. _Codecov: https://codecov.io/github/matplotlib/cycler?branch=main
cycler: composable cycles=========================
Docs: https://matplotlib.org/cycler/123version https://git-lfs.github.com/spec/v1oid sha256:ba8f811b8ddfac493734d6af0b2dff96919d0c28ca0d641858dab4262777c6easize 100356151234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366Metadata-Version: 2.1Name: matplotlibVersion: 3.11.1Summary: Python plotting packageAuthor: John D. Hunter, Michael DroettboomAuthor-Email: Unknown <matplotlib-users@python.org>License: License agreement for matplotlib versions 1.3.0 and later ========================================================= 1. This LICENSE AGREEMENT is between the Matplotlib Development Team ("MDT"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, MDT hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib alone or in any derivative version, provided, however, that MDT's License Agreement and MDT's notice of copyright, i.e., "Copyright (c) 2012- Matplotlib Development Team; All Rights Reserved" are retained in matplotlib alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib . 4. MDT is making matplotlib available to Licensee on an "AS IS" basis. MDT MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between MDT and Licensee. This License Agreement does not grant permission to use MDT trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib , Licensee agrees to be bound by the terms and conditions of this License Agreement. License agreement for matplotlib versions prior to 1.3.0 ======================================================== 1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib alone or in any derivative version, provided, however, that JDH's License Agreement and JDH's notice of copyright, i.e., "Copyright (c) 2002-2011 John D. Hunter; All Rights Reserved" are retained in matplotlib alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib. 4. JDH is making matplotlib available to Licensee on an "AS IS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib, Licensee agrees to be bound by the terms and conditions of this License Agreement. ---- This binary distrubution of Matplotlib can also bundle the following software (depending on the build): Name: AMS Fonts Files: matplotlib/tests/cmr10.pfb Description: Type-1 version of one of Knuth's Computer Modern fonts License: OFL-1.1 The cmr10.pfb file is a Type-1 version of one of Knuth's Computer Modern fonts. It is included here as test data only, but the following license applies. Copyright (c) 1997, 2009, American Mathematical Society (http://www.ams.org). All Rights Reserved. "cmb10" is a Reserved Font Name for this Font Software. "cmbsy10" is a Reserved Font Name for this Font Software. "cmbsy5" is a Reserved Font Name for this Font Software. "cmbsy6" is a Reserved Font Name for this Font Software. "cmbsy7" is a Reserved Font Name for this Font Software. "cmbsy8" is a Reserved Font Name for this Font Software. "cmbsy9" is a Reserved Font Name for this Font Software. "cmbx10" is a Reserved Font Name for this Font Software. "cmbx12" is a Reserved Font Name for this Font Software. "cmbx5" is a Reserved Font Name for this Font Software. "cmbx6" is a Reserved Font Name for this Font Software. "cmbx7" is a Reserved Font Name for this Font Software. "cmbx8" is a Reserved Font Name for this Font Software. "cmbx9" is a Reserved Font Name for this Font Software. "cmbxsl10" is a Reserved Font Name for this Font Software. "cmbxti10" is a Reserved Font Name for this Font Software. "cmcsc10" is a Reserved Font Name for this Font Software. "cmcsc8" is a Reserved Font Name for this Font Software. "cmcsc9" is a Reserved Font Name for this Font Software. "cmdunh10" is a Reserved Font Name for this Font Software. "cmex10" is a Reserved Font Name for this Font Software. "cmex7" is a Reserved Font Name for this Font Software. "cmex8" is a Reserved Font Name for this Font Software. "cmex9" is a Reserved Font Name for this Font Software. "cmff10" is a Reserved Font Name for this Font Software. "cmfi10" is a Reserved Font Name for this Font Software. "cmfib8" is a Reserved Font Name for this Font Software. "cminch" is a Reserved Font Name for this Font Software. "cmitt10" is a Reserved Font Name for this Font Software. "cmmi10" is a Reserved Font Name for this Font Software. "cmmi12" is a Reserved Font Name for this Font Software. "cmmi5" is a Reserved Font Name for this Font Software. "cmmi6" is a Reserved Font Name for this Font Software. "cmmi7" is a Reserved Font Name for this Font Software. "cmmi8" is a Reserved Font Name for this Font Software. "cmmi9" is a Reserved Font Name for this Font Software. "cmmib10" is a Reserved Font Name for this Font Software. "cmmib5" is a Reserved Font Name for this Font Software. "cmmib6" is a Reserved Font Name for this Font Software. "cmmib7" is a Reserved Font Name for this Font Software. "cmmib8" is a Reserved Font Name for this Font Software. "cmmib9" is a Reserved Font Name for this Font Software. "cmr10" is a Reserved Font Name for this Font Software. "cmr12" is a Reserved Font Name for this Font Software. "cmr17" is a Reserved Font Name for this Font Software. "cmr5" is a Reserved Font Name for this Font Software. "cmr6" is a Reserved Font Name for this Font Software. "cmr7" is a Reserved Font Name for this Font Software. "cmr8" is a Reserved Font Name for this Font Software. "cmr9" is a Reserved Font Name for this Font Software. "cmsl10" is a Reserved Font Name for this Font Software. "cmsl12" is a Reserved Font Name for this Font Software. "cmsl8" is a Reserved Font Name for this Font Software. "cmsl9" is a Reserved Font Name for this Font Software. "cmsltt10" is a Reserved Font Name for this Font Software. "cmss10" is a Reserved Font Name for this Font Software. "cmss12" is a Reserved Font Name for this Font Software. "cmss17" is a Reserved Font Name for this Font Software. "cmss8" is a Reserved Font Name for this Font Software. "cmss9" is a Reserved Font Name for this Font Software. "cmssbx10" is a Reserved Font Name for this Font Software. "cmssdc10" is a Reserved Font Name for this Font Software. "cmssi10" is a Reserved Font Name for this Font Software. "cmssi12" is a Reserved Font Name for this Font Software. "cmssi17" is a Reserved Font Name for this Font Software. "cmssi8" is a Reserved Font Name for this Font Software. "cmssi9" is a Reserved Font Name for this Font Software. "cmssq8" is a Reserved Font Name for this Font Software. "cmssqi8" is a Reserved Font Name for this Font Software. "cmsy10" is a Reserved Font Name for this Font Software. "cmsy5" is a Reserved Font Name for this Font Software. "cmsy6" is a Reserved Font Name for this Font Software. "cmsy7" is a Reserved Font Name for this Font Software. "cmsy8" is a Reserved Font Name for this Font Software. "cmsy9" is a Reserved Font Name for this Font Software. "cmtcsc10" is a Reserved Font Name for this Font Software. "cmtex10" is a Reserved Font Name for this Font Software. "cmtex8" is a Reserved Font Name for this Font Software. "cmtex9" is a Reserved Font Name for this Font Software. "cmti10" is a Reserved Font Name for this Font Software. "cmti12" is a Reserved Font Name for this Font Software. "cmti7" is a Reserved Font Name for this Font Software. "cmti8" is a Reserved Font Name for this Font Software. "cmti9" is a Reserved Font Name for this Font Software. "cmtt10" is a Reserved Font Name for this Font Software. "cmtt12" is a Reserved Font Name for this Font Software. "cmtt8" is a Reserved Font Name for this Font Software. "cmtt9" is a Reserved Font Name for this Font Software. "cmu10" is a Reserved Font Name for this Font Software. "cmvtt10" is a Reserved Font Name for this Font Software. "euex10" is a Reserved Font Name for this Font Software. "euex7" is a Reserved Font Name for this Font Software. "euex8" is a Reserved Font Name for this Font Software. "euex9" is a Reserved Font Name for this Font Software. "eufb10" is a Reserved Font Name for this Font Software. "eufb5" is a Reserved Font Name for this Font Software. "eufb7" is a Reserved Font Name for this Font Software. "eufm10" is a Reserved Font Name for this Font Software. "eufm5" is a Reserved Font Name for this Font Software. "eufm7" is a Reserved Font Name for this Font Software. "eurb10" is a Reserved Font Name for this Font Software. "eurb5" is a Reserved Font Name for this Font Software. "eurb7" is a Reserved Font Name for this Font Software. "eurm10" is a Reserved Font Name for this Font Software. "eurm5" is a Reserved Font Name for this Font Software. "eurm7" is a Reserved Font Name for this Font Software. "eusb10" is a Reserved Font Name for this Font Software. "eusb5" is a Reserved Font Name for this Font Software. "eusb7" is a Reserved Font Name for this Font Software. "eusm10" is a Reserved Font Name for this Font Software. "eusm5" is a Reserved Font Name for this Font Software. "eusm7" is a Reserved Font Name for this Font Software. "lasy10" is a Reserved Font Name for this Font Software. "lasy5" is a Reserved Font Name for this Font Software. "lasy6" is a Reserved Font Name for this Font Software. "lasy7" is a Reserved Font Name for this Font Software. "lasy8" is a Reserved Font Name for this Font Software. "lasy9" is a Reserved Font Name for this Font Software. "lasyb10" is a Reserved Font Name for this Font Software. "lcircle1" is a Reserved Font Name for this Font Software. "lcirclew" is a Reserved Font Name for this Font Software. "lcmss8" is a Reserved Font Name for this Font Software. "lcmssb8" is a Reserved Font Name for this Font Software. "lcmssi8" is a Reserved Font Name for this Font Software. "line10" is a Reserved Font Name for this Font Software. "linew10" is a Reserved Font Name for this Font Software. "msam10" is a Reserved Font Name for this Font Software. "msam5" is a Reserved Font Name for this Font Software. "msam6" is a Reserved Font Name for this Font Software. "msam7" is a Reserved Font Name for this Font Software. "msam8" is a Reserved Font Name for this Font Software. "msam9" is a Reserved Font Name for this Font Software. "msbm10" is a Reserved Font Name for this Font Software. "msbm5" is a Reserved Font Name for this Font Software. "msbm6" is a Reserved Font Name for this Font Software. "msbm7" is a Reserved Font Name for this Font Software. "msbm8" is a Reserved Font Name for this Font Software. "msbm9" is a Reserved Font Name for this Font Software. "wncyb10" is a Reserved Font Name for this Font Software. "wncyi10" is a Reserved Font Name for this Font Software. "wncyr10" is a Reserved Font Name for this Font Software. "wncysc10" is a Reserved Font Name for this Font Software. "wncyss10" is a Reserved Font Name for this Font Software. This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. Name: BaKoMa Fonts Files: matplotlib/mpl-data/fonts/ttf/cm*.ttf matplotlib/mpl-data/fonts/afm/cm*.afm Description: Computer Modern Fonts in PostScript Type 1 and TrueType font formats. License: BaKoMa Fonts Licence BaKoMa Fonts Licence -------------------- This licence covers two font packs (known as BaKoMa Fonts Collection, which is available at `CTAN:fonts/cm/ps-type1/bakoma/'): 1) BaKoMa-CM (1.1/12-Nov-94) Computer Modern Fonts in PostScript Type 1 and TrueType font formats. 2) BaKoMa-AMS (1.2/19-Jan-95) AMS TeX fonts in PostScript Type 1 and TrueType font formats. Copyright (C) 1994, 1995, Basil K. Malyshev. All Rights Reserved. Permission to copy and distribute these fonts for any purpose is hereby granted without fee, provided that the above copyright notice, author statement and this permission notice appear in all copies of these fonts and related documentation. Permission to modify and distribute modified fonts for any purpose is hereby granted without fee, provided that the copyright notice, author statement, this permission notice and location of original fonts (http://www.ctan.org/tex-archive/fonts/cm/ps-type1/bakoma) appear in all copies of modified fonts and related documentation. Permission to use these fonts (embedding into PostScript, PDF, SVG and printing by using any software) is hereby granted without fee. It is not required to provide any notices about using these fonts. Basil K. Malyshev INSTITUTE FOR HIGH ENERGY PHYSICS IHEP, OMVT Moscow Region 142281 PROTVINO RUSSIA E-Mail: bakoma@mail.ru or malyshev@mail.ihep.ru Name: ColorBrewer Color Schemes Files: lib/matplotlib/_cm.py Description: Color schemes from ColorBrewer License: Apache-2.0 Apache-Style Software License for ColorBrewer software and ColorBrewer Color Schemes Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University. 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. Name: Courier 10 Files: matplotlib/tests/Courier10PitchBT-Bold.pfb Description: Courier 10 font, used in tests. License: Bitstream-Charter The Courier10PitchBT-Bold.pfb file is a Type-1 version of Courier 10 Pitch BT Bold by Bitstream, obtained from <https://ctan.org/tex-archive/fonts/courierten>. It is included here as test data only, but the following license applies. (c) Copyright 1989-1992, Bitstream Inc., Cambridge, MA. You are hereby granted permission under all Bitstream propriety rights to use, copy, modify, sublicense, sell, and redistribute the 4 Bitstream Charter (r) Type 1 outline fonts and the 4 Courier Type 1 outline fonts for any purpose and without restriction; provided, that this notice is left intact on all copies of such fonts and that Bitstream's trademark is acknowledged as shown below on all unmodified copies of the 4 Charter Type 1 fonts. BITSTREAM CHARTER is a registered trademark of Bitstream Inc. Name: FreeType Files: matplotlib/ft2font.*.so Description: Font rendering library License: FTL OR GPL-2.0-or-later The FreeType 2 font engine is copyrighted work and cannot be used legally without a software license. In order to make this project usable to a vast majority of developers, we distribute it under two mutually exclusive open-source licenses. This means that *you* must choose *one* of the two licenses described below, then obey all its terms and conditions when using FreeType 2 in any of your projects or products. - The FreeType License, found in the file `docs/FTL.TXT`, which is similar to the original BSD license *with* an advertising clause that forces you to explicitly cite the FreeType project in your product's documentation. All details are in the license file. This license is suited to products which don't use the GNU General Public License. Note that this license is compatible to the GNU General Public License version 3, but not version 2. - The GNU General Public License version 2, found in `docs/GPLv2.TXT` (any later version can be used also), for programs which already use the GPL. Note that the FTL is incompatible with GPLv2 due to its advertisement clause. The contributed BDF and PCF drivers come with a license similar to that of the X Window System. It is compatible to the above two licenses (see files `src/bdf/README` and `src/pcf/README`). The same holds for the source code files `src/base/fthash.c` and `include/freetype/internal/fthash.h`; they were part of the BDF driver in earlier FreeType versions. The gzip module uses the zlib license (see `src/gzip/zlib.h`) which too is compatible to the above two licenses. The files `src/autofit/ft-hb.c` and `src/autofit/ft-hb.h` contain code taken almost verbatim from the HarfBuzz file `hb-ft.cc`, which uses the 'Old MIT' license, compatible to the above two licenses. The MD5 checksum support (only used for debugging in development builds) is in the public domain. Name: HarfBuzz Files: matplotlib/ft2font.*.so Description: Text shaping library License: MIT-Modern-Variant HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. For parts of HarfBuzz that are licensed under different licenses see individual files names COPYING in subdirectories where applicable. Copyright © 2010-2022 Google, Inc. Copyright © 2015-2020 Ebrahim Byagowi Copyright © 2019,2020 Facebook, Inc. Copyright © 2012,2015 Mozilla Foundation Copyright © 2011 Codethink Limited Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) Copyright © 2009 Keith Stribley Copyright © 2011 Martin Hosken and SIL International Copyright © 2007 Chris Wilson Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. Copyright © 1998-2005 David Turner and Werner Lemberg Copyright © 2016 Igalia S.L. Copyright © 2022 Matthias Clasen Copyright © 2018,2021 Khaled Hosny Copyright © 2018,2019,2020 Adobe, Inc Copyright © 2013-2015 Alexei Podtelezhnikov For full copyright notices consult the individual files in the package. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. Name: JSXTools resize observer Files: lib/matplotlib/backends/web_backend/js/mpl.js Description: Minimal polyfill for the ResizeObserver API License: CC0-1.0 # CC0 1.0 Universal ## Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an “owner”) of an original work of authorship and/or a database (each, a “Work”). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works (“Commons”) that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the “Affirmer”), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights (“Copyright and Related Rights”). Copyright and Related Rights include, but are not limited to, the following: 1. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; 2. moral rights retained by the original author(s) and/or performer(s); 3. publicity and privacy rights pertaining to a person’s image or likeness depicted in a Work; 4. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(i), below; 5. rights protecting the extraction, dissemination, use and reuse of data in a Work; 6. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and 7. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer’s Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the “Waiver”). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer’s heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer’s express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer’s express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer’s Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the “License”). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer’s express Statement of Purpose. 4. Limitations and Disclaimers. 1. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. 2. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. 3. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person’s Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. 4. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. For more information, please see http://creativecommons.org/publicdomain/zero/1.0/. Name: Last Resort fonts Files: matplotlib/mpl-data/fonts/ttf/LastResortHE-Regular.ttf Description: Last Resort High-Efficiency Font License: OFL-1.1 This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. SPDX-License-Identifier: OFL-1.1 Name: libraqm Files: matplotlib/ft2font.*.so Description: Complex text layout library License: MIT The MIT License (MIT) Copyright © 2015 Information Technology Authority (ITA) <foss@ita.gov.om> Copyright © 2016-2023 Khaled Hosny <khaled@aliftype.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Name: QHull Files: matplotlib/_qhull.*.so Description: Convex hull, Delaunay triangulation, Voronoi diagrams, Halfspace intersection License: Qhull Qhull, Copyright (c) 1993-2020 C.B. Barber Arlington, MA and The National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center) University of Minnesota email: qhull@qhull.org This software includes Qhull from C.B. Barber and The Geometry Center. Files derived from Qhull 1.0 are copyrighted by the Geometry Center. The remaining files are copyrighted by C.B. Barber. Qhull is free software and may be obtained via http from www.qhull.org. It may be freely copied, modified, and redistributed under the following conditions: 1. All copyright notices must remain intact in all files. 2. A copy of this text file must be distributed along with any copies of Qhull that you redistribute; this includes copies that you have modified, or copies of programs or other software products that include Qhull. 3. If you modify Qhull, you must include a notice giving the name of the person performing the modification, the date of modification, and the reason for such modification. 4. When distributing modified versions of Qhull, or other software products that include Qhull, you must provide notice that the original source code may be obtained as noted above. 5. There is no warranty or other guarantee of fitness for Qhull, it is provided solely "as is". Bug reports or fixes may be sent to qhull_bug@qhull.org; the authors may or may not act on them as they desire. Name: Qt4 Editor Files: matplotlib/backends/qt_editor Description: Module creating PyQt4 form dialogs/layouts to edit various type of parameters License: MIT Module creating PyQt4 form dialogs/layouts to edit various type of parameters formlayout License Agreement (MIT License) ------------------------------------------ Copyright (c) 2009 Pierre Raybaut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Name: SheenBidi Files: matplotlib/ft2font.*.so Description: Unicode Bidirectional Algorithm implementation License: Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. Name: Solarized Files: matplotlib/mpl-data/stylelib/Solarize_Light2.mplstyle Description: Solarized color scheme/style License: MIT https://github.com/altercation/solarized/blob/master/LICENSE Copyright (c) 2011 Ethan Schoonover Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Name: Stix fonts Files: matplotlib/mpl-data/fonts/ttf/STIX*.ttf Description: STIX fonts License: OFL-1.1 STIX Font License 24 May 2010 Copyright (c) 2001-2010 by the STI Pub Companies, consisting of the American Institute of Physics, the American Chemical Society, the American Mathematical Society, the American Physical Society, Elsevier, Inc., and The Institute of Electrical and Electronic Engineers, Inc. (www.stixfonts.org), with Reserved Font Name STIX Fonts, STIX Fonts (TM) is a trademark of The Institute of Electrical and Electronics Engineers, Inc. Portions copyright (c) 1998-2003 by MicroPress, Inc. (www.micropress-inc.com), with Reserved Font Name TM Math. To obtain additional mathematical fonts, please contact MicroPress, Inc., 68-30 Harrow Street, Forest Hills, NY 11375, USA, Phone: (718) 575-1816. Portions copyright (c) 1990 by Elsevier, Inc. This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. Name: Yorick Colormaps Files: lib/matplotlib/_cm.py Description: Gist/Yorick colormaps License: BSD-style license for gist/yorick colormaps. Copyright: Copyright (c) 1996. The Regents of the University of California. All rights reserved. Permission to use, copy, modify, and distribute this software for any purpose without fee is hereby granted, provided that this entire notice is included in all copies of any software which is or includes a copy or modification of this software and in all copies of the supporting documentation for such software. This work was produced at the University of California, Lawrence Livermore National Laboratory under contract no. W-7405-ENG-48 between the U.S. Department of Energy and The Regents of the University of California for the operation of UC LLNL. DISCLAIMER This software was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the University of California nor any of their employees, makes any warranty, express or implied, or assumes any liability or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or represents that its use would not infringe privately-owned rights. Reference herein to any specific commercial products, process, or service by trade name, trademark, manufacturer, or otherwise, does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government or the University of California. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or the University of California, and shall not be used for advertising or product endorsement purposes. AUTHOR David H. Munro wrote Yorick and Gist. Berkeley Yacc (byacc) generated the Yorick parser. The routines in Math are from LAPACK and FFTPACK; MathC contains C translations by David H. Munro. The algorithms for Yorick's random number generator and several special functions in Yorick/include were taken from Numerical Recipes by Press, et. al., although the Yorick implementations are unrelated to those in Numerical Recipes. A small amount of code in Gist was adapted from the X11R4 release, copyright M.I.T. -- the complete copyright notice may be found in the (unused) file Gist/host.c. Classifier: Development Status :: 5 - Production/StableClassifier: Framework :: MatplotlibClassifier: Intended Audience :: Science/ResearchClassifier: Intended Audience :: EducationClassifier: License :: OSI Approved :: Python Software Foundation LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/Engineering :: VisualizationProject-URL: Homepage, https://matplotlib.orgProject-URL: Download, https://matplotlib.org/stable/install/index.htmlProject-URL: Documentation, https://matplotlib.orgProject-URL: Source Code, https://github.com/matplotlib/matplotlibProject-URL: Bug Tracker, https://github.com/matplotlib/matplotlib/issuesProject-URL: Forum, https://discourse.matplotlib.org/Project-URL: Donate, https://numfocus.org/donate-to-matplotlibRequires-Python: >=3.11Requires-Dist: contourpy>=1.0.1Requires-Dist: cycler>=0.10Requires-Dist: fonttools>=4.28.2Requires-Dist: kiwisolver>=1.3.1Requires-Dist: numpy>=1.25Requires-Dist: packaging>=20.0Requires-Dist: pillow>=9Requires-Dist: pyparsing>=3Requires-Dist: python-dateutil>=2.7Description-Content-Type: text/markdown
[](https://pypi.org/project/matplotlib/)[](https://anaconda.org/conda-forge/matplotlib)[](https://pypi.org/project/matplotlib)[](https://numfocus.org)[](https://insights.linuxfoundation.org/project/matplotlib)
[](https://discourse.matplotlib.org)[](https://discourse.matplotlib.org/chat/c/matplotlib/2)[](https://github.com/matplotlib/matplotlib/issues)[](https://matplotlib.org/stable/devel/index.html)
[](https://github.com/matplotlib/matplotlib/actions?query=workflow%3ATests)[](https://dev.azure.com/matplotlib/matplotlib/_build/latest?definitionId=1&branchName=main)[](https://ci.appveyor.com/project/matplotlib/matplotlib)[](https://app.codecov.io/gh/matplotlib/matplotlib)[](https://jacobtomlinson.dev/effver)

Matplotlib is a comprehensive library for creating static, animated, andinteractive visualizations in Python.
Check out our [home page](https://matplotlib.org/) for more information.

Matplotlib produces publication-quality figures in a variety of hardcopyformats and interactive environments across platforms. Matplotlib can beused in Python scripts, Python/IPython shells, web application servers,and various graphical user interface toolkits.
## Install
See the [installdocumentation](https://matplotlib.org/stable/users/installing/index.html),which is generated from `/doc/install/index.rst`
## Contribute
You've discovered a bug or something else you want to change — excellent!
You've worked out a way to fix it — even better!
You want to tell us about it — best of all!
Start at the [contributingguide](https://matplotlib.org/devdocs/devel/contribute.html)!
## Contact
[Discourse](https://discourse.matplotlib.org/) is the discussion forumfor general questions and discussions and our recommended startingpoint.
Our active mailing lists (which are mirrored on Discourse) are:
- [Users](https://mail.python.org/mailman/listinfo/matplotlib-users) mailing list: <matplotlib-users@python.org>- [Announcement](https://mail.python.org/mailman/listinfo/matplotlib-announce) mailing list: <matplotlib-announce@python.org>- [Development](https://mail.python.org/mailman/listinfo/matplotlib-devel) mailing list: <matplotlib-devel@python.org>
[Discourse Chat](https://discourse.matplotlib.org/chat/c/matplotlib/2) is forcoordinating development and asking questions directly related to contributingto matplotlib.
## Citing Matplotlib
If Matplotlib contributes to a project that leads to publication, pleaseacknowledge this by citing Matplotlib.
[A ready-made citationentry](https://matplotlib.org/stable/users/project/citing.html) isavailable.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300Metadata-Version: 2.4Name: segmentation_models_pytorchVersion: 0.5.0Summary: Image segmentation models with pre-trained backbones. PyTorch.Author-email: Pavel Iakubovskii <qubvel@gmail.com>License: The MIT License Copyright (c) 2019, Pavel Iakubovskii Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Project-URL: Homepage, https://github.com/qubvel-org/segmentation_models.pytorchClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyRequires-Python: >=3.9Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: huggingface-hub>=0.24Requires-Dist: numpy>=1.19.3Requires-Dist: pillow>=8Requires-Dist: safetensors>=0.3.1Requires-Dist: timm>=0.9Requires-Dist: torch>=1.8Requires-Dist: torchvision>=0.9Requires-Dist: tqdm>=4.42.1Provides-Extra: docsRequires-Dist: autodocsumm; extra == "docs"Requires-Dist: huggingface-hub; extra == "docs"Requires-Dist: six; extra == "docs"Requires-Dist: sphinx; extra == "docs"Requires-Dist: sphinx-book-theme; extra == "docs"Provides-Extra: testRequires-Dist: gitpython; extra == "test"Requires-Dist: packaging; extra == "test"Requires-Dist: pytest; extra == "test"Requires-Dist: pytest-cov; extra == "test"Requires-Dist: pytest-xdist; extra == "test"Requires-Dist: ruff>=0.9; extra == "test"Requires-Dist: setuptools; extra == "test"Dynamic: license-file
<div align="center">  **Python library with Neural Networks for Image Semantic Segmentation based on [PyTorch](https://pytorch.org/).**
[](https://github.com/qubvel/segmentation_models.pytorch/actions/workflows/tests.yml) [](https://smp.readthedocs.io/en/latest/) <br>[](https://pypi.org/project/segmentation-models-pytorch/) [](https://pepy.tech/project/segmentation-models-pytorch) [](https://pepy.tech/project/segmentation-models-pytorch) <br>[](https://github.com/qubvel/segmentation_models.pytorch/blob/main/LICENSE)[](https://pepy.tech/project/segmentation-models-pytorch)
</div>
The main features of the library are:
- Super simple high-level API (just two lines to create a neural network) - 12 encoder-decoder model architectures (Unet, Unet++, Segformer, DPT, ...) - 800+ **pretrained** convolution- and transform-based encoders, including [timm](https://github.com/huggingface/pytorch-image-models) support - Popular metrics and losses for training routines (Dice, Jaccard, Tversky, ...) - ONNX export and torch script/trace/compile friendly
### Community-Driven Project, Supported By<table> <tr> <td align="center" vertical-align="center"> <a href="https://withoutbg.com/?utm_source=smp&utm_medium=github_readme&utm_campaign=sponsorship" > <img src="https://withoutbg.com/images/logo-social.png" width="70px;" alt="withoutBG API Logo" /> </a> </td> <td align="center" vertical-align="center"> <b>withoutBG API</b> <br /> <a href="https://withoutbg.com/?utm_source=smp&utm_medium=github_readme&utm_campaign=sponsorship">https://withoutbg.com</a> <br /> <p width="200px"> High-quality background removal API <br/> </p> </td> </tr></table> ### [📚 Project Documentation 📚](http://smp.readthedocs.io/)
Visit [Read The Docs Project Page](https://smp.readthedocs.io/) or read the following README to know more about Segmentation Models Pytorch (SMP for short) library
### 📋 Table of content 1. [Quick start](#start) 2. [Examples](#examples) 3. [Models and encoders](#models-and-encoders) 4. [Models API](#api) 1. [Input channels](#input-channels) 2. [Auxiliary classification output](#auxiliary-classification-output) 3. [Depth](#depth) 5. [Installation](#installation) 6. [Competitions won with the library](#competitions) 7. [Contributing](#contributing) 8. [Citing](#citing) 9. [License](#license)
## ⏳ Quick start <a name="start"></a>
#### 1. Create your first Segmentation model with SMP
The segmentation model is just a PyTorch `torch.nn.Module`, which can be created as easy as:
```pythonimport segmentation_models_pytorch as smp
model = smp.Unet( encoder_name="resnet34", # choose encoder, e.g. mobilenet_v2 or efficientnet-b7 encoder_weights="imagenet", # use `imagenet` pre-trained weights for encoder initialization in_channels=1, # model input channels (1 for gray-scale images, 3 for RGB, etc.) classes=3, # model output channels (number of classes in your dataset))``` - see [table](#architectures) with available model architectures - see [table](#encoders) with available encoders and their corresponding weights
#### 2. Configure data preprocessing
All encoders have pretrained weights. Preparing your data the same way as during weights pre-training may give you better results (higher metric score and faster convergence). It is **not necessary** in case you train the whole model, not only the decoder.
```pythonfrom segmentation_models_pytorch.encoders import get_preprocessing_fn
preprocess_input = get_preprocessing_fn('resnet18', pretrained='imagenet')```
Congratulations! You are done! Now you can train your model with your favorite framework!
## 💡 Examples <a name="examples"></a>
| Name | Link | Colab ||-------------------------------------------|-----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|| **Train** pets binary segmentation on OxfordPets | [Notebook](https://github.com/qubvel/segmentation_models.pytorch/blob/main/examples/binary_segmentation_intro.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/binary_segmentation_intro.ipynb) || **Train** cars binary segmentation on CamVid | [Notebook](https://github.com/qubvel/segmentation_models.pytorch/blob/main/examples/cars%20segmentation%20(camvid).ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/cars%20segmentation%20(camvid).ipynb) || **Train** multiclass segmentation on CamVid | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/camvid_segmentation_multiclass.ipynb) | [](https://colab.research.google.com/github/qubvel-org/segmentation_models.pytorch/blob/main/examples/camvid_segmentation_multiclass.ipynb) || **Train** clothes binary segmentation by @ternaus | [Repo](https://github.com/ternaus/cloths_segmentation) | || **Load and inference** pretrained Segformer | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/segformer_inference_pretrained.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/segformer_inference_pretrained.ipynb) || **Load and inference** pretrained DPT | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/dpt_inference_pretrained.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/dpt_inference_pretrained.ipynb) || **Load and inference** pretrained DPT | [Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/upernet_inference_pretrained.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/upernet_inference_pretrained.ipynb) || **Save and load** models locally / to HuggingFace Hub |[Notebook](https://github.com/qubvel-org/segmentation_models.pytorch/blob/main/examples/save_load_model_and_share_with_hf_hub.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/save_load_model_and_share_with_hf_hub.ipynb)| **Export** trained model to ONNX | [Notebook](https://github.com/qubvel/segmentation_models.pytorch/blob/main/examples/convert_to_onnx.ipynb) | [](https://colab.research.google.com/github/qubvel/segmentation_models.pytorch/blob/main/examples/convert_to_onnx.ipynb) |
## 📦 Models and encoders <a name="models-and-encoders"></a>
### Architectures <a name="architectures"></a>| Architecture | Paper | Documentation | Checkpoints ||--------------|-------|---------------|------------|| Unet | [paper](https://arxiv.org/abs/1505.04597) | [docs](https://smp.readthedocs.io/en/latest/models.html#unet) | || Unet++ | [paper](https://arxiv.org/pdf/1807.10165.pdf) | [docs](https://smp.readthedocs.io/en/latest/models.html#unetplusplus) | || MAnet | [paper](https://ieeexplore.ieee.org/abstract/document/9201310) | [docs](https://smp.readthedocs.io/en/latest/models.html#manet) | || Linknet | [paper](https://arxiv.org/abs/1707.03718) | [docs](https://smp.readthedocs.io/en/latest/models.html#linknet) | || FPN | [paper](http://presentations.cocodataset.org/COCO17-Stuff-FAIR.pdf) | [docs](https://smp.readthedocs.io/en/latest/models.html#fpn) | || PSPNet | [paper](https://arxiv.org/abs/1612.01105) | [docs](https://smp.readthedocs.io/en/latest/models.html#pspnet) | || PAN | [paper](https://arxiv.org/abs/1805.10180) | [docs](https://smp.readthedocs.io/en/latest/models.html#pan) | || DeepLabV3 | [paper](https://arxiv.org/abs/1706.05587) | [docs](https://smp.readthedocs.io/en/latest/models.html#deeplabv3) | || DeepLabV3+ | [paper](https://arxiv.org/abs/1802.02611) | [docs](https://smp.readthedocs.io/en/latest/models.html#deeplabv3plus) | || UPerNet | [paper](https://arxiv.org/abs/1807.10221) | [docs](https://smp.readthedocs.io/en/latest/models.html#upernet) | [checkpoints](https://huggingface.co/collections/smp-hub/upernet-67fadcdbe08418c6ea94f768) || Segformer | [paper](https://arxiv.org/abs/2105.15203) | [docs](https://smp.readthedocs.io/en/latest/models.html#segformer) | [checkpoints](https://huggingface.co/collections/smp-hub/segformer-6749eb4923dea2c355f29a1f) || DPT | [paper](https://arxiv.org/abs/2103.13413) | [docs](https://smp.readthedocs.io/en/latest/models.html#dpt) | [checkpoints](https://huggingface.co/collections/smp-hub/dpt-67f30487327c0599a0c62d68) |
### Encoders <a name="encoders"></a>
The library provides a wide range of **pretrained** encoders (also known as backbones) for segmentation models. Instead of using features from the final layer of a classification model, we extract **intermediate features** and feed them into the decoder for segmentation tasks.
All encoders come with **pretrained weights**, which help achieve **faster and more stable convergence** when training segmentation models.
Given the extensive selection of supported encoders, you can choose the best one for your specific use case, for example: - **Lightweight encoders** for low-latency applications or real-time inference on edge devices (mobilenet/mobileone). - **High-capacity architectures** for complex tasks involving a large number of segmented classes, providing superior accuracy (convnext/swin/mit).
By selecting the right encoder, you can balance **efficiency, performance, and model complexity** to suit your project needs.
All encoders and corresponding pretrained weight are listed in the documentation: - [table](https://smp.readthedocs.io/en/latest/encoders.html) with natively ported encoders - [table](https://smp.readthedocs.io/en/latest/encoders_timm.html) with [timm](https://github.com/huggingface/pytorch-image-models) encoders supported
## 🔁 Models API <a name="api"></a>
### Input channels
The input channels parameter allows you to create a model that can process a tensor with an arbitrary number of channels. If you use pretrained weights from ImageNet, the weights of the first convolution will be reused: - For the 1-channel case, it would be a sum of the weights of the first convolution layer. - Otherwise, channels would be populated with weights like `new_weight[:, i] = pretrained_weight[:, i % 3]`, and then scaled with `new_weight * 3 / new_in_channels`.
```pythonmodel = smp.FPN('resnet34', in_channels=1)mask = model(torch.ones([1, 1, 64, 64]))```
### Auxiliary classification output
All models support `aux_params` parameters, which is default set to `None`. If `aux_params = None` then classification auxiliary output is not created, elsemodel produce not only `mask`, but also `label` output with shape `NC`.Classification head consists of GlobalPooling->Dropout(optional)->Linear->Activation(optional) layers, which can be configured by `aux_params` as follows:```pythonaux_params=dict( pooling='avg', # one of 'avg', 'max' dropout=0.5, # dropout ratio, default is None activation='sigmoid', # activation function, default is None classes=4, # define number of output labels)model = smp.Unet('resnet34', classes=4, aux_params=aux_params)mask, label = model(x)```
### Depth
Depth parameter specify a number of downsampling operations in encoder, so you can makeyour model lighter if specify smaller `depth`.```pythonmodel = smp.Unet('resnet34', encoder_depth=4)```
## 🛠 Installation <a name="installation"></a>PyPI version:
```bash$ pip install segmentation-models-pytorch````
The latest version from GitHub:
```bash$ pip install git+https://github.com/qubvel/segmentation_models.pytorch````
## 🏆 Competitions won with the library <a name="competitions"></a>
`Segmentation Models` package is widely used in image segmentation competitions.[Here](https://github.com/qubvel/segmentation_models.pytorch/blob/main/HALLOFFAME.md) you can find competitions, names of the winners and links to their solutions.
## 🤝 Contributing <a name="contributing"></a>
1. Install SMP in dev mode
```bashmake install_dev # Create .venv, install SMP in dev mode```
2. Run tests and code checks
```bashmake test # Run tests suite with pytestmake fixup # Ruff for formatting and lint checks```
3. Update a table (in case you added an encoder)
```bashmake table # Generates a table with encoders and print to stdout```
## 📝 Citing <a name="citing"></a>```@misc{Iakubovskii:2019, Author = {Pavel Iakubovskii}, Title = {Segmentation Models Pytorch}, Year = {2019}, Publisher = {GitHub}, Journal = {GitHub repository}, Howpublished = {\url{https://github.com/qubvel/segmentation_models.pytorch}}}```
## 🛡️ License <a name="license"></a>The project is primarily distributed under [MIT License](https://github.com/qubvel/segmentation_models.pytorch/blob/main/LICENSE), while some files are subject to other licenses. Please refer to [LICENSES](licenses/LICENSES.md) and license statements in each file for careful check, especially for commercial use.123version https://git-lfs.github.com/spec/v1oid sha256:382ff9f685ee3bc25864f820aa50505825f10f5458ffff07e30a6d96e5715cabsize 1813144123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139Metadata-Version: 2.4Name: alembicVersion: 1.18.5Summary: A database migration tool for SQLAlchemy.Author-email: Mike Bayer <mike_mp@zzzcomputing.com>License-Expression: MITProject-URL: Homepage, https://alembic.sqlalchemy.orgProject-URL: Documentation, https://alembic.sqlalchemy.org/en/latest/Project-URL: Changelog, https://alembic.sqlalchemy.org/en/latest/changelog.htmlProject-URL: Source, https://github.com/sqlalchemy/alembic/Project-URL: Issue Tracker, https://github.com/sqlalchemy/alembic/issues/Classifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Environment :: ConsoleClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Topic :: Database :: Front-EndsRequires-Python: >=3.10Description-Content-Type: text/x-rstLicense-File: LICENSERequires-Dist: SQLAlchemy>=1.4.23Requires-Dist: MakoRequires-Dist: typing-extensions>=4.12Requires-Dist: tomli; python_version < "3.11"Provides-Extra: tzRequires-Dist: tzdata; extra == "tz"Dynamic: license-file
Alembic is a database migrations tool written by the authorof `SQLAlchemy <http://www.sqlalchemy.org>`_. A migrations tooloffers the following functionality:
* Can emit ALTER statements to a database in order to change the structure of tables and other constructs* Provides a system whereby "migration scripts" may be constructed; each script indicates a particular series of steps that can "upgrade" a target database to a new version, and optionally a series of steps that can "downgrade" similarly, doing the same steps in reverse.* Allows the scripts to execute in some sequential manner.
The goals of Alembic are:
* Very open ended and transparent configuration and operation. A new Alembic environment is generated from a set of templates which is selected among a set of options when setup first occurs. The templates then deposit a series of scripts that define fully how database connectivity is established and how migration scripts are invoked; the migration scripts themselves are generated from a template within that series of scripts. The scripts can then be further customized to define exactly how databases will be interacted with and what structure new migration files should take.* Full support for transactional DDL. The default scripts ensure that all migrations occur within a transaction - for those databases which support this (Postgresql, Microsoft SQL Server), migrations can be tested with no need to manually undo changes upon failure.* Minimalist script construction. Basic operations like renaming tables/columns, adding/removing columns, changing column attributes can be performed through one line commands like alter_column(), rename_table(), add_constraint(). There is no need to recreate full SQLAlchemy Table structures for simple operations like these - the functions themselves generate minimalist schema structures behind the scenes to achieve the given DDL sequence.* "auto generation" of migrations. While real world migrations are far more complex than what can be automatically determined, Alembic can still eliminate the initial grunt work in generating new migration directives from an altered schema. The ``--autogenerate`` feature will inspect the current status of a database using SQLAlchemy's schema inspection capabilities, compare it to the current state of the database model as specified in Python, and generate a series of "candidate" migrations, rendering them into a new migration script as Python directives. The developer then edits the new file, adding additional directives and data migrations as needed, to produce a finished migration. Table and column level changes can be detected, with constraints and indexes to follow as well.* Full support for migrations generated as SQL scripts. Those of us who work in corporate environments know that direct access to DDL commands on a production database is a rare privilege, and DBAs want textual SQL scripts. Alembic's usage model and commands are oriented towards being able to run a series of migrations into a textual output file as easily as it runs them directly to a database. Care must be taken in this mode to not invoke other operations that rely upon in-memory SELECTs of rows - Alembic tries to provide helper constructs like bulk_insert() to help with data-oriented operations that are compatible with script-based DDL.* Non-linear, dependency-graph versioning. Scripts are given UUID identifiers similarly to a DVCS, and the linkage of one script to the next is achieved via human-editable markers within the scripts themselves. The structure of a set of migration files is considered as a directed-acyclic graph, meaning any migration file can be dependent on any other arbitrary set of migration files, or none at all. Through this open-ended system, migration files can be organized into branches, multiple roots, and mergepoints, without restriction. Commands are provided to produce new branches, roots, and merges of branches automatically.* Provide a library of ALTER constructs that can be used by any SQLAlchemy application. The DDL constructs build upon SQLAlchemy's own DDLElement base and can be used standalone by any application or script.* At long last, bring SQLite and its inability to ALTER things into the fold, but in such a way that SQLite's very special workflow needs are accommodated in an explicit way that makes the most of a bad situation, through the concept of a "batch" migration, where multiple changes to a table can be batched together to form a series of instructions for a single, subsequent "move-and-copy" workflow. You can even use "move-and-copy" workflow for other databases, if you want to recreate a table in the background on a busy system.
Documentation and status of Alembic is at https://alembic.sqlalchemy.org/
The SQLAlchemy Project======================
Alembic is part of the `SQLAlchemy Project <https://www.sqlalchemy.org>`_ andadheres to the same standards and conventions as the core project.
Development / Bug reporting / Pull requests___________________________________________
Please refer to the`SQLAlchemy Community Guide <https://www.sqlalchemy.org/develop.html>`_ forguidelines on coding and participating in this project.
Code of Conduct_______________
Above all, SQLAlchemy places great emphasis on polite, thoughtful, andconstructive communication between users and developers.Please see our current Code of Conduct at`Code of Conduct <https://www.sqlalchemy.org/codeofconduct.html>`_.
License=======
Alembic is distributed under the `MIT license<https://opensource.org/licenses/MIT>`_.1*1Signature: 8a477f597d28d172789f06886806bc55123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373Metadata-Version: 2.4Name: huggingface_hubVersion: 1.24.0Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hubHome-page: https://github.com/huggingface/huggingface_hubAuthor: Hugging Face, Inc.Author-email: julien@huggingface.coLicense: Apache-2.0Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-modelsClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: EducationClassifier: Intended Audience :: Science/ResearchClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Topic :: Scientific/Engineering :: Artificial IntelligenceRequires-Python: >=3.10.0Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: click<9.0.0,>=8.4.2Requires-Dist: filelock>=3.10.0Requires-Dist: fsspec>=2023.5.0Requires-Dist: hf-xet<2.0.0,>=1.5.1; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64"Requires-Dist: httpx<1,>=0.23.0Requires-Dist: packaging>=20.9Requires-Dist: pyyaml>=5.1Requires-Dist: tqdm>=4.42.1Requires-Dist: typing-extensions>=4.1.0Provides-Extra: oauthRequires-Dist: authlib>=1.3.2; extra == "oauth"Requires-Dist: fastapi; extra == "oauth"Requires-Dist: httpx; extra == "oauth"Requires-Dist: itsdangerous; extra == "oauth"Provides-Extra: torchRequires-Dist: torch; extra == "torch"Requires-Dist: safetensors[torch]; extra == "torch"Provides-Extra: fastaiRequires-Dist: toml; extra == "fastai"Requires-Dist: fastai>=2.4; extra == "fastai"Requires-Dist: fastcore>=1.3.27; extra == "fastai"Provides-Extra: hf-xetRequires-Dist: hf-xet<2.0.0,>=1.5.1; extra == "hf-xet"Provides-Extra: mcpRequires-Dist: mcp>=1.8.0; extra == "mcp"Provides-Extra: testingRequires-Dist: authlib>=1.3.2; extra == "testing"Requires-Dist: fastapi; extra == "testing"Requires-Dist: httpx; extra == "testing"Requires-Dist: itsdangerous; extra == "testing"Requires-Dist: jedi; extra == "testing"Requires-Dist: Jinja2; extra == "testing"Requires-Dist: pytest>=8.4.2; extra == "testing"Requires-Dist: pytest-cov; extra == "testing"Requires-Dist: pytest-env; extra == "testing"Requires-Dist: pytest-xdist; extra == "testing"Requires-Dist: pytest-vcr; extra == "testing"Requires-Dist: pytest-asyncio; extra == "testing"Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"Requires-Dist: pytest-mock; extra == "testing"Requires-Dist: urllib3<2.0; extra == "testing"Requires-Dist: soundfile; extra == "testing"Requires-Dist: Pillow; extra == "testing"Requires-Dist: numpy; extra == "testing"Requires-Dist: duckdb; extra == "testing"Requires-Dist: fastapi; extra == "testing"Provides-Extra: gradioRequires-Dist: gradio>=5.0.0; extra == "gradio"Requires-Dist: requests; extra == "gradio"Provides-Extra: typingRequires-Dist: typing-extensions>=4.8.0; extra == "typing"Requires-Dist: types-PyYAML; extra == "typing"Requires-Dist: types-simplejson; extra == "typing"Requires-Dist: types-toml; extra == "typing"Requires-Dist: types-tqdm; extra == "typing"Requires-Dist: types-urllib3; extra == "typing"Provides-Extra: qualityRequires-Dist: ruff>=0.9.0; extra == "quality"Requires-Dist: mypy==1.15.0; extra == "quality"Requires-Dist: libcst>=1.4.0; extra == "quality"Requires-Dist: ty; extra == "quality"Provides-Extra: allRequires-Dist: authlib>=1.3.2; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: httpx; extra == "all"Requires-Dist: itsdangerous; extra == "all"Requires-Dist: jedi; extra == "all"Requires-Dist: Jinja2; extra == "all"Requires-Dist: pytest>=8.4.2; extra == "all"Requires-Dist: pytest-cov; extra == "all"Requires-Dist: pytest-env; extra == "all"Requires-Dist: pytest-xdist; extra == "all"Requires-Dist: pytest-vcr; extra == "all"Requires-Dist: pytest-asyncio; extra == "all"Requires-Dist: pytest-rerunfailures<16.0; extra == "all"Requires-Dist: pytest-mock; extra == "all"Requires-Dist: urllib3<2.0; extra == "all"Requires-Dist: soundfile; extra == "all"Requires-Dist: Pillow; extra == "all"Requires-Dist: numpy; extra == "all"Requires-Dist: duckdb; extra == "all"Requires-Dist: fastapi; extra == "all"Requires-Dist: ruff>=0.9.0; extra == "all"Requires-Dist: mypy==1.15.0; extra == "all"Requires-Dist: libcst>=1.4.0; extra == "all"Requires-Dist: ty; extra == "all"Requires-Dist: typing-extensions>=4.8.0; extra == "all"Requires-Dist: types-PyYAML; extra == "all"Requires-Dist: types-simplejson; extra == "all"Requires-Dist: types-toml; extra == "all"Requires-Dist: types-tqdm; extra == "all"Requires-Dist: types-urllib3; extra == "all"Provides-Extra: devRequires-Dist: authlib>=1.3.2; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: httpx; extra == "dev"Requires-Dist: itsdangerous; extra == "dev"Requires-Dist: jedi; extra == "dev"Requires-Dist: Jinja2; extra == "dev"Requires-Dist: pytest>=8.4.2; extra == "dev"Requires-Dist: pytest-cov; extra == "dev"Requires-Dist: pytest-env; extra == "dev"Requires-Dist: pytest-xdist; extra == "dev"Requires-Dist: pytest-vcr; extra == "dev"Requires-Dist: pytest-asyncio; extra == "dev"Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"Requires-Dist: pytest-mock; extra == "dev"Requires-Dist: urllib3<2.0; extra == "dev"Requires-Dist: soundfile; extra == "dev"Requires-Dist: Pillow; extra == "dev"Requires-Dist: numpy; extra == "dev"Requires-Dist: duckdb; extra == "dev"Requires-Dist: fastapi; extra == "dev"Requires-Dist: ruff>=0.9.0; extra == "dev"Requires-Dist: mypy==1.15.0; extra == "dev"Requires-Dist: libcst>=1.4.0; extra == "dev"Requires-Dist: ty; extra == "dev"Requires-Dist: typing-extensions>=4.8.0; extra == "dev"Requires-Dist: types-PyYAML; extra == "dev"Requires-Dist: types-simplejson; extra == "dev"Requires-Dist: types-toml; extra == "dev"Requires-Dist: types-tqdm; extra == "dev"Requires-Dist: types-urllib3; extra == "dev"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: keywordsDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-distDynamic: requires-pythonDynamic: summary
<p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg"> <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg"> <img alt="huggingface_hub library logo" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg" width="352" height="59" style="max-width: 100%"> </picture> <br/> <br/></p>
<p align="center"> <i>The official CLI and Python client for the Hugging Face Hub.</i> <br/> <a href="#what-is-huggingface_hub">About</a> · <a href="https://huggingface.co/docs/huggingface_hub">Documentation</a> · <a href="https://huggingface.co/docs/huggingface_hub/en/installation">Install</a> · <a href="https://huggingface.co/docs/huggingface_hub/en/guides/cli">CLI Guide</a> · <a href="https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md">Contributing</a></p>
<p align="center"> <a href="https://huggingface.co/docs/huggingface_hub/en/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/huggingface_hub/index.svg?down_color=red&down_message=offline&up_message=online&label=doc"></a> <a href="https://github.com/huggingface/huggingface_hub/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/huggingface_hub.svg"></a> <a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a> <a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a> <a href="https://codecov.io/gh/huggingface/huggingface_hub"><img alt="Code coverage" src="https://codecov.io/gh/huggingface/huggingface_hub/branch/main/graph/badge.svg?token=RXP95LE2XL"></a></p>
<h4 align="center"> <p> <b>English</b> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a> | <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_kn.md">ಕನ್ನಡ</a> </p></h4>
## Quick start
Install the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) with the standalone installer:
```bash# On macOS and Linux.curl -LsSf https://hf.co/cli/install.sh | bash```
```powershell# On Windows.powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"```
Log in, then start working with the Hub:
```bash# Log in (use --token $HF_TOKEN in non-interactive environments)hf auth login
# Find models served by Inference Providershf models ls --warm
# Download a modelhf download Qwen/Qwen3-0.6B
# Upload files to your own repohf upload username/my-cool-model ./model.safetensors
# Sync a local folder to a storage buckethf buckets sync ./checkpoints hf://buckets/username/my-bucket
# Run a job on Hugging Face infrastructurehf jobs run python:3.12 python -c "print('Hello from the cloud!')"
# Discover everything elsehf --help```
The Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). Check out the [CLI guide](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for a tour of the main features.
## What is `huggingface_hub`?
The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects, play with the thousands of machine learning apps hosted on the Hub, or create and share your own models, datasets and demos with the community. Everything ships in one package with two interfaces: the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for your terminal and the `huggingface_hub` library for Python — both designed to work well for humans and AI agents. Use them to:
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.- [Run Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) on Hugging Face infrastructure.- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.- Do all of the above from the terminal with the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli).
## Built for humans and AI agents
The `hf` CLI is designed for people and coding agents alike: the same commands adapt their output when run by an agent. If you use Claude Code, Codex, Cursor, or another coding agent, install the `hf` CLI Skill — a command reference generated from your installed CLI:
```bash# for Codex, Cursor, OpenCode, Pi and other agents that load skills from `.agents/skills`hf skills add# includes the above + Claude Codehf skills add --claude```
Learn more in the [Hugging Face CLI for AI agents guide](https://huggingface.co/docs/hub/agents-cli) and the [announcement blog post](https://huggingface.co/blog/hf-cli-for-agents).
## Use the Python library
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/) (this also installs the `hf` CLI):
```bashpip install huggingface_hub```
We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install:
```bashuv pip install huggingface_hub```
In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run:
```bashpip install "huggingface_hub[mcp]"```
To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
### Download files
Download a single file
```pyfrom huggingface_hub import hf_hub_download
hf_hub_download(repo_id="zai-org/GLM-5.2", filename="config.json")```
Or an entire repository
```pyfrom huggingface_hub import snapshot_download
snapshot_download("sentence-transformers/all-MiniLM-L6-v2")```
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
### Create a repository
```pyfrom huggingface_hub import create_repo
create_repo(repo_id="super-cool-model")```
### Upload files
Upload a single file
```pyfrom huggingface_hub import upload_file
upload_file( path_or_fileobj="/home/lysandre/dummy-test/README.md", path_in_repo="README.md", repo_id="lysandre/test-model",)```
Or an entire folder
```pyfrom huggingface_hub import upload_folder
upload_folder( folder_path="/path/to/local/space", repo_id="username/my-cool-space", repo_type="space",)```
More details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
## Integrating with the Hub.
We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries).
The advantages are:
- Free model or dataset hosting for libraries and their users.- Built-in file versioning, even with very large files, made possible by [Xet](https://huggingface.co/docs/hub/xet/index), the Hub's chunk-deduplicated storage backend.- In-browser widgets to play with the uploaded models.- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.- Usage stats and more features to come.
If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration.
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarizehow to get started to contribute to this repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190huggingface_hub/__init__.py,sha256=-S0NPE6Z4nJekQs_IfXDYzv314lNMbbaDDEhCTl8C3c,60255huggingface_hub/_buckets.py,sha256=XyLbsLzS2fpQz0aAIjKzV-1YbQ4XYZ4-HXQTVq0TXoU,45311huggingface_hub/_commit_api.py,sha256=yW99ZJbIuiRt604bQ2TpDzsfxTO-IxdFW8nf-NY2MyE,45389huggingface_hub/_commit_scheduler.py,sha256=VG3zjb7xb66NrFMq_pB9dWIsoqSPoF6CntovV7vUiWg,14684huggingface_hub/_dataset_viewer.py,sha256=LE9k4s0WJ0JNdriJ8L6qV_-xfbUVC1VEh7CBd0jOjLI,5675huggingface_hub/_eval_results.py,sha256=Og7p7bCl2HQG6ZWlSDyir-CRTXjNWPu3S3q65cTGffs,8126huggingface_hub/_inference_endpoints.py,sha256=TNCEvHfu5M790bQPl4BccRzcii8WS5FlDYGrGqQzdW4,17724huggingface_hub/_jobs_api.py,sha256=tZMrw8idM6nbIz_EJsOt7Gx7_2v7CzRtaUqrQfXAsi0,21164huggingface_hub/_local_folder.py,sha256=Fc_hikyMaZRHtXIDZj38hL7MNkq5nZZVxQF-dd-EkMo,18279huggingface_hub/_login.py,sha256=wAMdhqMSSh3GBJDozodmk4IIsAvb9J6LaLY9KnXFoyY,21818huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628huggingface_hub/_oidc.py,sha256=3kcCLavWQ5FQOwizUPzLaBb1ft2FIJo0bSXL24S3r4U,7098huggingface_hub/_sandbox.py,sha256=F6ZMchoqH8cnzdmGECqszL8JR4hcWIgGDq4QgV8W-TQ,80138huggingface_hub/_sandbox_cache.py,sha256=UYpvHOWZj7CRhacYs5Ot-5N1wFcAapiAyniYdoX-jX8,5742huggingface_hub/_snapshot_download.py,sha256=jdXyEI_e00GLeTIs6r783MbO5-AdS2nCow2aqlgzy1Q,30431huggingface_hub/_space_api.py,sha256=MF3ezhgl0Vpt3RP1wuwZ7VI9_rSyIlIJ5SmDzIwQlcQ,13424huggingface_hub/_tensorboard_logger.py,sha256=GA-LhoG4Z-0Zq7w5B9vTIDJbWUkAhiG2d8a-ktlwGDY,8377huggingface_hub/_tree_cache.py,sha256=9JU2uOX5oQT3wK2BSUj5Yb33UUNpmybGav5d5FduzGk,5336huggingface_hub/_upload_large_folder.py,sha256=BWA1zyOK9W_3YUerX9YWQa3wAYtHRe_ypgsO79JEkqo,31235huggingface_hub/_upload_pipeline.py,sha256=19UxsZ10NB05kOXEvTN663TDE--9EBJjvxR4uI-Lg9c,28946huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544huggingface_hub/_webhooks_server.py,sha256=VXOk3FHkbIc28phxknJfaFy5B_EoKOKihoCKyOaWZQk,15767huggingface_hub/community.py,sha256=N5OE5Rbc2BMwpNXCFOPQAwn0otqQunsXdEnSE_0J2Xo,12325huggingface_hub/constants.py,sha256=eI3-JDy6jkG1EuXAjUdVdG67kbj6gxGNlr9In2-5AMc,13182huggingface_hub/dataclasses.py,sha256=47qPdMJMuzFFjPwqa_bRvzh7nxwXx_lXE8h3eblkxp8,25940huggingface_hub/errors.py,sha256=eso8GCrCcDv1Yb6NDBqyFt_Vr9PLCOsueNylNlDXMD4,18391huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583huggingface_hub/file_download.py,sha256=jSwr6Ze9CT0hScAgEZhRx3LF3BRgZSZLoptYwotQxis,87253huggingface_hub/hf_api.py,sha256=VBGUpyUhZ__USFBMlNv20CZxzTKnkJ_CdRXez-LX7Wk,659053huggingface_hub/hf_file_system.py,sha256=1Y6BqYHafnwulGNufJtzWfMU3Q3sbaW7oOqUcrNlvc4,60581huggingface_hub/hub_mixin.py,sha256=ljKAtm3qQsY-ARtxY-PCFx0koFXLI37JytMrzpqfnQo,36912huggingface_hub/lfs.py,sha256=8ymYNHRXgvgUUM9w0EAnC-vkSOOq_1EFJEJNoevoeE8,16588huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0huggingface_hub/repocard.py,sha256=ytBgqomIuM3zOeTPfzQNk_stlswh8DttLDvTbX_woPI,35582huggingface_hub/repocard_data.py,sha256=CRW3puz-efDcoGjKIgZv6p3LKKKYVgcy-FGr96zAFOg,34251huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606huggingface_hub/_hot_reload/client.py,sha256=Ax7qT4CUi5wrg3mDzqkAG8ZzDsCwdcIIS1FIXK0SqD8,4269huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948huggingface_hub/_hot_reload/types.py,sha256=d3AOJCLUxT41Fhz4jUrFevm9bfpooe_3PQhpBdgNYSs,2725huggingface_hub/cli/__init__.py,sha256=tWu3Is-m2tlJwXhM_vT2mPRgpnt9KhU9qvw5aRsnjU0,664huggingface_hub/cli/_city_game.py,sha256=2qkC9dCtPwf4-aqrnbN-vApf0YqIcGGjn2v-etrTfqg,20585huggingface_hub/cli/_cli_utils.py,sha256=Q5795puu89Kf4fEvQYPjyJmDnyqFEyEr5SW1xQXQk8I,41313huggingface_hub/cli/_completion.py,sha256=BDP6Vob9TLFp6K3lr0XOY98FyD-rm22KrjwsO_YGNbE,3759huggingface_hub/cli/_cp.py,sha256=Z-2Z_tBs1e4XBqRO5R9QnabU4qTi9HDlbA52jTBaCkY,10436huggingface_hub/cli/_errors.py,sha256=X0rUTO-3eCK5v_MLGEza1BxcuXGccPY-h7ShzmuQc34,5907huggingface_hub/cli/_file_listing.py,sha256=QRGm9oZS_g0Cv_jLQcUR6iNwBzMrsmbhs1kxwuY6rwk,7910huggingface_hub/cli/_framework.py,sha256=HqfAEYGWRSjKABAZi2zVNgryyU9QKW8u-tRXfR_4nQ8,27364huggingface_hub/cli/_help_formatter.py,sha256=-vsa3HfHQFkKWms77EGyp9i22t44ETmVt2L-e8qP-KM,1288huggingface_hub/cli/_output.py,sha256=A_yLkT0lzIovZV-fS7NZx7hCGiwiqJNtvUr-IbYPgpQ,13908huggingface_hub/cli/_skills.py,sha256=b1dlasxALM5KsDG5R1azcETksQ6ssYYZN-kaz-RdHwg,12134huggingface_hub/cli/auth.py,sha256=Ew79M60pTMCnS1ewKVK3fd8ZyfHrNjREOmNWuFXy37M,6056huggingface_hub/cli/buckets.py,sha256=J8xMP88fQ6ri3f65Z8XEImI2GNA4KKWloLJJQCBezZw,21062huggingface_hub/cli/cache.py,sha256=Oa3g53dUYlNIKy6crlXXGxG7lOZFa6iob0-8mMalCDc,28059huggingface_hub/cli/collections.py,sha256=ECTb__1zduL3F02ezGkQIaaSmUOVaeBbsGMs_8MTPcI,10078huggingface_hub/cli/datasets.py,sha256=X1xMJTFhHH5NJtmjTS6NN1g4ffai6Abh_obDEJM5mvo,10497huggingface_hub/cli/deprecated_cli.py,sha256=vAK_CR4NE9uzNJ0I59SyBnIln5nlypG4CPoohMoPMVg,1090huggingface_hub/cli/discussions.py,sha256=obvvN4mtsFnfMs67YTZaMvHkVaM6A-FYr5n-wGkF_jE,14029huggingface_hub/cli/download.py,sha256=o6fMKJoNQMxCm1RQUnX3blihJ17mantxkf0F68rZIxs,9669huggingface_hub/cli/extensions.py,sha256=qNM1DmzcQXt8kPWQfISc8Pvyku8BxAs-BOVP6sKRBOM,25572huggingface_hub/cli/hf.py,sha256=G2R-Mgo2AX09aRiAb-13eZbO441m9yDTwMCtSUf1iac,5208huggingface_hub/cli/inference_endpoints.py,sha256=4pfvPm5PVQizStyXGRBnrev62KvhzSNEL65UEVtRcKw,17418huggingface_hub/cli/jobs.py,sha256=-eMUXzpU3Dzxp9RAjff-6eCxYwxH9M3s6KK_MOn6Rgo,49640huggingface_hub/cli/lfs.py,sha256=MAccazVPX0n-ySRaPocaQUHP7oBnVrvWZt0RhmNIavs,5936huggingface_hub/cli/models.py,sha256=eG7H5yDjCVrdL7W_-wpcl70qXlv8bC-roSEu8AroPws,10148huggingface_hub/cli/papers.py,sha256=HvT-8zj2fi14ua6awWpHphlbJ362FEJIwSCBJRQZ_cM,4982huggingface_hub/cli/repo_files.py,sha256=sGbD5wND3miF71ThfOBJm4xzPRUpJBeLFdvyj229NAM,2443huggingface_hub/cli/repos.py,sha256=QS3xYKvspLhCfO5VvpORrSiF6XhSVFclmBxsacVDP2c,20192huggingface_hub/cli/sandbox.py,sha256=rTCZf6WhoDa7UiNhsTU_4Lh5uKqKYOs73xXGAAqJGdA,18379huggingface_hub/cli/skills.py,sha256=JQkqD43bfr8IapIVp8rvQpd8NKA0dXSbGJD8g-u51w8,19473huggingface_hub/cli/spaces.py,sha256=AU655GGrQmF1s1yO8yO6ml2Z8veE7zsh4UMuR5b13RI,40800huggingface_hub/cli/system.py,sha256=NtICLnQ49BHFpm2Cl37IV_h21L6mufxVDfse8Lp38HA,1760huggingface_hub/cli/upload.py,sha256=P6sq8Dj81a2wazUgZEqbliRleVAAmJrf8ajFDDzHrBE,11318huggingface_hub/cli/upload_large_folder.py,sha256=A-2qxAdLrYd8IogfZS2nDhSR1cpA_aaxhXst638WkAk,4081huggingface_hub/cli/webhooks.py,sha256=HdpPp01c6Ece_EuNNJr46rnRki3vF4j4o9-SqYRUHnM,8550huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0huggingface_hub/inference/_client.py,sha256=bN5cj4tBHPD6v603uq4CJjMB_mmmpdVcfXtl9XIOVqc,157679huggingface_hub/inference/_common.py,sha256=X-fBP8s6xuNTAuQsGVIethE8dNQaa-mK7Ds54qVVDz8,14999huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0huggingface_hub/inference/_generated/_async_client.py,sha256=imtfJD9m3qxeo_59gox3nnV8Tr8dfQF3dQF0Joy5K4g,160890huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=kIA8FfRfOWS3SrZrMTbuVOjE6yxfKfMK75Co5egTWHA,3284huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250huggingface_hub/inference/_mcp/cli.py,sha256=RKdVQ_VdEgf1AL_QBCvwrsUQ0Ux4R1yerrE46DrV5C0,9642huggingface_hub/inference/_mcp/constants.py,sha256=0Ih6ivEvG-pfF8NwErFngzP4Rof4lQoz6ms_eKSAkUI,2463huggingface_hub/inference/_mcp/mcp_client.py,sha256=dGp8PhN6aVw4bDnuSySFSiguHUiz-nzhgv89CVdO7pI,17243huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318huggingface_hub/inference/_providers/__init__.py,sha256=TNWnSNPk0RmToBysTc5D1COm0vHEJoGom0Yh7oG2wC4,9838huggingface_hub/inference/_providers/_common.py,sha256=9CjlMAtb7W0-GdB1Z-VkV0GKZ0Zm68rIuicdGE-765M,13716huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226huggingface_hub/inference/_providers/deepinfra.py,sha256=4Behgf5V7FTv7CbN6vPEIYwv1z4gztdRRU-KVoOgxVE,4703huggingface_hub/inference/_providers/fal_ai.py,sha256=Y2vo5Dl3e8EoehplwNshu8LbDT1e7V4ZyhAMqs0wXws,11705huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315huggingface_hub/inference/_providers/hf_inference.py,sha256=d2vdCKSi5CtyQqYndHHvH7SY131-7YHUK3yE7653eIc,9467huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174huggingface_hub/inference/_providers/together.py,sha256=lrymDZ86n5yoR_Zz7o3AzzSePyo0s7BOBU5digLxb5o,12220huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963huggingface_hub/serialization/_base.py,sha256=8vYeDIsqgyOO3I_uii44Bkb50LsMz3kkD4gwAPzhfWU,8436huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385huggingface_hub/serialization/_torch.py,sha256=BtaCP-G3oYRP6Pj9MhI-ygBsk3JbBPnVDW9huSOgtkk,46897huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870huggingface_hub/utils/__init__.py,sha256=SHfYVviFx_oyeA0EFOz4kXFeRg-SAbDlgyb8tk4TpeU,4026huggingface_hub/utils/_auth.py,sha256=Ykuq3yi67jxHmFdyLSc43xvGuCAIR7-h-dajX8IxpGQ,19958huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691huggingface_hub/utils/_cache_manager.py,sha256=2StxP-nHZ5W9_hi8N9wBFqRNLw5HwO0h9HC7NTAGaFE,34955huggingface_hub/utils/_chunk_utils.py,sha256=pTjy8Z-KLU4W_6D3OUh3E8lCodWDCd6aJwjNDU0C5U8,2121huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865huggingface_hub/utils/_detect_agent.py,sha256=Iw2KW9BUZWfIypn9CtiTmEibHwKK9xx5Ar48z1cMU-Q,7337huggingface_hub/utils/_dotenv.py,sha256=NdlEM8OXtzwlwmJCmdc6oGubFObrpgr408y8gnSs7ls,2604huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548huggingface_hub/utils/_headers.py,sha256=Q9bu9mvOpm-9rfv-YRlr_Ywy_aMZkmRcN3MbVEcJAJA,8234huggingface_hub/utils/_hf_uris.py,sha256=RTHrVKLT5vVU-ca8roXHrKwbN3njowanvxHjx5B4sUg,27558huggingface_hub/utils/_http.py,sha256=C_mC63TsaxpmzyYBPHCneXKFLACEytAkBwxRwMNxcB4,46014huggingface_hub/utils/_lfs.py,sha256=xMU-ROgNAUpDkzbH6yRZsE-eVYUYTNMGrgVb_QdTv-k,3942huggingface_hub/utils/_oauth_device.py,sha256=o7ICmI01yDt1oAFNMUJvN1ThSfaCDpC8AHYSQgcnFGw,7983huggingface_hub/utils/_pagination.py,sha256=h-TJjFbX3FqkA1T0tGZ0EhxMvuRSCg-UfL_a-BMs54I,1943huggingface_hub/utils/_parsing.py,sha256=DVWuO6s_XMiGfXyc0jyX5hi_yGgBHpF9KLoeQM-VVK0,3586huggingface_hub/utils/_paths.py,sha256=kWpUMIK9rmKb2LHgHCkk2DnroDzucrwbj-urCJCgfGw,5962huggingface_hub/utils/_runtime.py,sha256=GVJ_Dt6y_48TZWl0ui9yPdW8M7rqGblRGyUqKaXxkCo,13493huggingface_hub/utils/_safetensors.py,sha256=qFE7OA-vjU8X0zBBtOeNRzLu147KF-PdFoaxkYfWB4M,4426huggingface_hub/utils/_subprocess.py,sha256=tFVBBNot_HLVqQ79y873TGb12C4PUTMwub-GhzDTemE,4542huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824huggingface_hub/utils/_terminal.py,sha256=whHgs0Co-1LatoCmJE_ojqE_cWP6b5dWPWpU-uSFWUU,8969huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542huggingface_hub/utils/_validators.py,sha256=tuC1U4yxB-4XKIajZMnKZUSKvZ6qPpydY8LItfa0g40,8419huggingface_hub/utils/_verification.py,sha256=ZSilnolSkYmHB3vmBlWuuVr53xz59P5uGnxC3H-Hjc0,5434huggingface_hub/utils/_xet.py,sha256=YtEzhvXi21VB4DtrnqGiSh2_Ox77XhVzLlDIwcnYxj0,6305huggingface_hub/utils/_xet_progress_reporting.py,sha256=MnNCxB9ieflArNNyz3R4kpkjOdt6mQxi8qp8xqzXQTM,14162huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008huggingface_hub/utils/logging.py,sha256=WaXk5gRa8Ml_LUIH34QCr8suYj8i_8Wot4IDnYJyWyM,4870huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121huggingface_hub/utils/tqdm.py,sha256=KbHhkB5g76JgGOGCcjAQOaR-oc-wzd4Sr3wqd41ny7k,13350huggingface_hub-1.24.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357huggingface_hub-1.24.0.dist-info/METADATA,sha256=v9Nc5D4ZrL3kN81cNvd66iJ1JPd9uOkE7TeLj61cjMQ,16311huggingface_hub-1.24.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91huggingface_hub-1.24.0.dist-info/entry_points.txt,sha256=zP7F_bBSdircPQFysHQZ9F3Lcn5_dCSOEZxVlGCsG0w,212huggingface_hub-1.24.0.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16huggingface_hub-1.24.0.dist-info/RECORD,,12345Wheel-Version: 1.0Generator: setuptools (83.0.0)Root-Is-Purelib: trueTag: py3-none-any
1234567[console_scripts]hf = huggingface_hub.cli.hf:mainhuggingface-cli = huggingface_hub.cli.deprecated_cli:maintiny-agents = huggingface_hub.inference._mcp.cli:app
[fsspec.specs]hf = huggingface_hub.HfFileSystem123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.1huggingface_hub1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804# Copyright 2020 The HuggingFace Team. All rights reserved.## 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.
# ***********# `huggingface_hub` init has 2 modes:# - Normal usage:# If imported to use it, all modules and functions are lazy-loaded. This means# they exist at top level in module but are imported only the first time they are# used. This way, `from huggingface_hub import something` will import `something`# quickly without the hassle of importing all the features from `huggingface_hub`.# - Static check:# If statically analyzed, all modules and functions are loaded normally. This way# static typing check works properly as well as autocomplete in text editors and# IDEs.## The static model imports are done inside the `if TYPE_CHECKING:` statement at# the bottom of this file. Since module/functions imports are duplicated, it is# mandatory to make sure to add them twice when adding one. This is checked in the# `make quality` command.## To update the static imports, please run the following command and commit the changes.# ```# # Use script# python utils/check_static_imports.py --update-file## # Or run style on codebase# make style# ```## ***********# Lazy loader vendored from https://github.com/scientific-python/lazy_loaderimport importlibimport osimport sysfrom typing import TYPE_CHECKING
__version__ = "1.24.0"
# Alphabetical order of definitions is ensured in tests# WARNING: any comment added in this dictionary definition will be lost when# re-generating the file !_SUBMOD_ATTRS = { "_buckets": [ "BucketFile", "BucketFileMetadata", "BucketFolder", "BucketInfo", "BucketUrl", "SyncOperation", "SyncPlan", ], "_commit_scheduler": [ "CommitScheduler", ], "_eval_results": [ "EvalResultEntry", "eval_result_entries_to_yaml", "parse_eval_result_entries", ], "_inference_endpoints": [ "InferenceEndpoint", "InferenceEndpointError", "InferenceEndpointStatus", "InferenceEndpointTimeoutError", "InferenceEndpointType", ], "_jobs_api": [ "JobAccelerator", "JobDurations", "JobHardware", "JobHardwareInfo", "JobInfo", "JobInitiator", "JobOwner", "JobStage", "JobStatus", ], "_login": [ "auth_list", "auth_switch", "interpreter_login", "login", "logout", "notebook_login", ], "_oauth": [ "OAuthInfo", "OAuthOrgInfo", "OAuthUserInfo", "attach_huggingface_oauth", "parse_huggingface_oauth", ], "_sandbox": [ "Sandbox", "SandboxCommandResult", "SandboxPool", "SandboxProcess", ], "_snapshot_download": [ "get_cached_repo_tree", "snapshot_download", ], "_space_api": [ "SpaceHardware", "SpaceRuntime", "SpaceSecret", "SpaceStage", "SpaceStorage", "SpaceVariable", "Volume", ], "_tensorboard_logger": [ "HFSummaryWriter", ], "_webhooks_payload": [ "WebhookPayload", "WebhookPayloadComment", "WebhookPayloadDiscussion", "WebhookPayloadDiscussionChanges", "WebhookPayloadEvent", "WebhookPayloadMovedTo", "WebhookPayloadRepo", "WebhookPayloadUrl", "WebhookPayloadWebhook", ], "_webhooks_server": [ "WebhooksServer", "webhook_endpoint", ], "cli._cli_utils": [ "check_cli_update", "typer_factory", ], "community": [ "Discussion", "DiscussionComment", "DiscussionCommit", "DiscussionEvent", "DiscussionStatusChange", "DiscussionTitleChange", "DiscussionWithDetails", ], "constants": [ "CONFIG_NAME", "FLAX_WEIGHTS_NAME", "HUGGINGFACE_CO_URL_HOME", "HUGGINGFACE_CO_URL_TEMPLATE", "PYTORCH_WEIGHTS_NAME", "REPO_TYPE_DATASET", "REPO_TYPE_MODEL", "REPO_TYPE_SPACE", "TF2_WEIGHTS_NAME", "TF_WEIGHTS_NAME", "is_offline_mode", ], "fastai_utils": [ "_save_pretrained_fastai", "from_pretrained_fastai", "push_to_hub_fastai", ], "file_download": [ "DryRunFileInfo", "HfFileMetadata", "_CACHED_NO_EXIST", "get_hf_file_metadata", "hf_hub_download", "hf_hub_url", "try_to_load_from_cache", ], "hf_api": [ "Collection", "CollectionItem", "CommitInfo", "CommitOperation", "CommitOperationAdd", "CommitOperationCopy", "CommitOperationDelete", "DatasetInfo", "DatasetLeaderboardEntry", "GitCommitInfo", "GitRefInfo", "GitRefs", "HfApi", "KernelInfo", "ModelInfo", "Organization", "RepoFile", "RepoFolder", "RepoStorageInfo", "RepoUrl", "SpaceInfo", "SpaceSearchResult", "SpaceTemplate", "User", "UserLikes", "WebhookInfo", "WebhookWatchedItem", "accept_access_request", "add_collection_item", "add_space_secret", "add_space_variable", "auth_check", "batch_bucket_files", "bucket_info", "cancel_access_request", "cancel_job", "change_discussion_status", "comment_discussion", "copy_files", "create_branch", "create_bucket", "create_collection", "create_commit", "create_discussion", "create_inference_endpoint", "create_inference_endpoint_from_catalog", "create_pull_request", "create_repo", "create_scheduled_job", "create_scheduled_uv_job", "create_tag", "create_webhook", "dataset_info", "delete_branch", "delete_bucket", "delete_collection", "delete_collection_item", "delete_file", "delete_folder", "delete_inference_endpoint", "delete_repo", "delete_scheduled_job", "delete_space_secret", "delete_space_storage", "delete_space_variable", "delete_space_volumes", "delete_tag", "delete_webhook", "disable_space_dev_mode", "disable_webhook", "download_bucket_files", "duplicate_repo", "duplicate_space", "edit_discussion_comment", "enable_space_dev_mode", "enable_webhook", "fetch_job_logs", "fetch_job_metrics", "fetch_space_logs", "file_exists", "get_bucket_file_metadata", "get_bucket_paths_info", "get_collection", "get_dataset_leaderboard", "get_dataset_tags", "get_discussion_details", "get_full_repo_name", "get_inference_endpoint", "get_local_safetensors_metadata", "get_model_tags", "get_organization_overview", "get_paths_info", "get_repo_discussions", "get_safetensors_metadata", "get_space_runtime", "get_space_secrets", "get_space_variables", "get_user_overview", "get_webhook", "grant_access", "inspect_job", "inspect_scheduled_job", "kernel_info", "list_accepted_access_requests", "list_bucket_tree", "list_buckets", "list_collections", "list_daily_papers", "list_dataset_parquet_files", "list_datasets", "list_inference_catalog", "list_inference_endpoints", "list_jobs", "list_jobs_hardware", "list_lfs_files", "list_liked_repos", "list_models", "list_organization_followers", "list_organization_members", "list_papers", "list_pending_access_requests", "list_rejected_access_requests", "list_repo_commits", "list_repo_files", "list_repo_likers", "list_repo_refs", "list_repo_tree", "list_space_templates", "list_spaces", "list_spaces_hardware", "list_user_followers", "list_user_following", "list_user_repos", "list_webhooks", "merge_pull_request", "model_info", "move_bucket", "move_repo", "paper_info", "parse_local_safetensors_file_metadata", "parse_safetensors_file_metadata", "pause_inference_endpoint", "pause_space", "permanently_delete_lfs_files", "preupload_lfs_files", "read_paper", "reject_access_request", "rename_discussion", "repo_exists", "repo_info", "repo_type_and_id_from_hf_id", "request_space_hardware", "request_space_storage", "restart_space", "resume_inference_endpoint", "resume_scheduled_job", "revision_exists", "run_as_future", "run_job", "run_uv_job", "scale_to_zero_inference_endpoint", "search_spaces", "set_space_sleep_time", "set_space_volumes", "space_info", "super_squash_history", "suspend_scheduled_job", "sync_bucket", "sync_job_volume", "trigger_scheduled_job", "unlike", "update_collection_item", "update_collection_metadata", "update_inference_endpoint", "update_job_labels", "update_repo_settings", "update_scheduled_job_labels", "update_webhook", "upload_file", "upload_folder", "upload_large_folder", "verify_repo_checksums", "wait_for_job", "wait_for_space", "whoami", ], "hf_file_system": [ "HfFileSystem", "HfFileSystemFile", "HfFileSystemResolvedPath", "HfFileSystemStreamFile", "hffs", ], "hub_mixin": [ "ModelHubMixin", "PyTorchModelHubMixin", ], "inference._client": [ "InferenceClient", "InferenceTimeoutError", ], "inference._generated._async_client": [ "AsyncInferenceClient", ], "inference._generated.types": [ "AudioClassificationInput", "AudioClassificationOutputElement", "AudioClassificationOutputTransform", "AudioClassificationParameters", "AudioToAudioInput", "AudioToAudioOutputElement", "AutomaticSpeechRecognitionEarlyStoppingEnum", "AutomaticSpeechRecognitionGenerationParameters", "AutomaticSpeechRecognitionInput", "AutomaticSpeechRecognitionOutput", "AutomaticSpeechRecognitionOutputChunk", "AutomaticSpeechRecognitionParameters", "ChatCompletionInput", "ChatCompletionInputFunctionDefinition", "ChatCompletionInputFunctionName", "ChatCompletionInputGrammarType", "ChatCompletionInputJSONSchema", "ChatCompletionInputMessage", "ChatCompletionInputMessageChunk", "ChatCompletionInputMessageChunkType", "ChatCompletionInputResponseFormatJSONObject", "ChatCompletionInputResponseFormatJSONSchema", "ChatCompletionInputResponseFormatText", "ChatCompletionInputStreamOptions", "ChatCompletionInputTool", "ChatCompletionInputToolCall", "ChatCompletionInputToolChoiceClass", "ChatCompletionInputToolChoiceEnum", "ChatCompletionInputURL", "ChatCompletionOutput", "ChatCompletionOutputComplete", "ChatCompletionOutputFunctionDefinition", "ChatCompletionOutputLogprob", "ChatCompletionOutputLogprobs", "ChatCompletionOutputMessage", "ChatCompletionOutputToolCall", "ChatCompletionOutputTopLogprob", "ChatCompletionOutputUsage", "ChatCompletionStreamOutput", "ChatCompletionStreamOutputChoice", "ChatCompletionStreamOutputDelta", "ChatCompletionStreamOutputDeltaToolCall", "ChatCompletionStreamOutputFunction", "ChatCompletionStreamOutputLogprob", "ChatCompletionStreamOutputLogprobs", "ChatCompletionStreamOutputTopLogprob", "ChatCompletionStreamOutputUsage", "DepthEstimationInput", "DepthEstimationOutput", "DocumentQuestionAnsweringInput", "DocumentQuestionAnsweringInputData", "DocumentQuestionAnsweringOutputElement", "DocumentQuestionAnsweringParameters", "FeatureExtractionInput", "FeatureExtractionInputTruncationDirection", "FillMaskInput", "FillMaskOutputElement", "FillMaskParameters", "ImageClassificationInput", "ImageClassificationOutputElement", "ImageClassificationOutputTransform", "ImageClassificationParameters", "ImageSegmentationInput", "ImageSegmentationOutputElement", "ImageSegmentationParameters", "ImageSegmentationSubtask", "ImageTextToImageInput", "ImageTextToImageOutput", "ImageTextToImageParameters", "ImageTextToImageTargetSize", "ImageTextToVideoInput", "ImageTextToVideoOutput", "ImageTextToVideoParameters", "ImageTextToVideoTargetSize", "ImageToImageInput", "ImageToImageOutput", "ImageToImageParameters", "ImageToImageTargetSize", "ImageToTextEarlyStoppingEnum", "ImageToTextGenerationParameters", "ImageToTextInput", "ImageToTextOutput", "ImageToTextParameters", "ImageToVideoInput", "ImageToVideoOutput", "ImageToVideoParameters", "ImageToVideoTargetSize", "ObjectDetectionBoundingBox", "ObjectDetectionInput", "ObjectDetectionOutputElement", "ObjectDetectionParameters", "Padding", "QuestionAnsweringInput", "QuestionAnsweringInputData", "QuestionAnsweringOutputElement", "QuestionAnsweringParameters", "SentenceSimilarityInput", "SentenceSimilarityInputData", "SummarizationInput", "SummarizationOutput", "SummarizationParameters", "SummarizationTruncationStrategy", "TableQuestionAnsweringInput", "TableQuestionAnsweringInputData", "TableQuestionAnsweringOutputElement", "TableQuestionAnsweringParameters", "Text2TextGenerationInput", "Text2TextGenerationOutput", "Text2TextGenerationParameters", "Text2TextGenerationTruncationStrategy", "TextClassificationInput", "TextClassificationOutputElement", "TextClassificationOutputTransform", "TextClassificationParameters", "TextGenerationInput", "TextGenerationInputGenerateParameters", "TextGenerationInputGrammarType", "TextGenerationOutput", "TextGenerationOutputBestOfSequence", "TextGenerationOutputDetails", "TextGenerationOutputFinishReason", "TextGenerationOutputPrefillToken", "TextGenerationOutputToken", "TextGenerationStreamOutput", "TextGenerationStreamOutputStreamDetails", "TextGenerationStreamOutputToken", "TextToAudioEarlyStoppingEnum", "TextToAudioGenerationParameters", "TextToAudioInput", "TextToAudioOutput", "TextToAudioParameters", "TextToImageInput", "TextToImageOutput", "TextToImageParameters", "TextToSpeechEarlyStoppingEnum", "TextToSpeechGenerationParameters", "TextToSpeechInput", "TextToSpeechOutput", "TextToSpeechParameters", "TextToVideoInput", "TextToVideoOutput", "TextToVideoParameters", "TokenClassificationAggregationStrategy", "TokenClassificationInput", "TokenClassificationOutputElement", "TokenClassificationParameters", "TranslationInput", "TranslationOutput", "TranslationParameters", "TranslationTruncationStrategy", "TypeEnum", "VideoClassificationInput", "VideoClassificationOutputElement", "VideoClassificationOutputTransform", "VideoClassificationParameters", "VisualQuestionAnsweringInput", "VisualQuestionAnsweringInputData", "VisualQuestionAnsweringOutputElement", "VisualQuestionAnsweringParameters", "ZeroShotClassificationInput", "ZeroShotClassificationOutputElement", "ZeroShotClassificationParameters", "ZeroShotImageClassificationInput", "ZeroShotImageClassificationOutputElement", "ZeroShotImageClassificationParameters", "ZeroShotObjectDetectionBoundingBox", "ZeroShotObjectDetectionInput", "ZeroShotObjectDetectionOutputElement", "ZeroShotObjectDetectionParameters", ], "inference._mcp.agent": [ "Agent", ], "inference._mcp.mcp_client": [ "MCPClient", ], "repocard": [ "DatasetCard", "ModelCard", "RepoCard", "SpaceCard", "metadata_eval_result", "metadata_load", "metadata_save", "metadata_update", ], "repocard_data": [ "CardData", "DatasetCardData", "EvalResult", "ModelCardData", "SpaceCardData", ], "serialization": [ "StateDictSplit", "get_torch_storage_id", "get_torch_storage_size", "load_state_dict_from_file", "load_torch_model", "save_torch_model", "save_torch_state_dict", "split_state_dict_into_shards_factory", "split_torch_state_dict_into_shards", ], "serialization._dduf": [ "DDUFEntry", "export_entries_as_dduf", "export_folder_as_dduf", "read_dduf_file", ], "utils": [ "ASYNC_CLIENT_FACTORY_T", "CLIENT_FACTORY_T", "CacheNotFound", "CachedFileInfo", "CachedIncompleteFileInfo", "CachedRepoInfo", "CachedRevisionInfo", "CorruptedCacheException", "DeleteCacheStrategy", "HFCacheInfo", "HfUri", "cached_assets_path", "close_session", "dump_environment_info", "get_async_session", "get_session", "get_token", "hf_raise_for_status", "logging", "parse_hf_uri", "scan_cache_dir", "set_async_client_factory", "set_client_factory", ],}
# WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file !## To update the static imports, please run the following command and commit the changes.# ```# # Use script# python utils/check_all_variable.py --update## # Or run style on codebase# make style# ```
__all__ = [ "ASYNC_CLIENT_FACTORY_T", "Agent", "AsyncInferenceClient", "AudioClassificationInput", "AudioClassificationOutputElement", "AudioClassificationOutputTransform", "AudioClassificationParameters", "AudioToAudioInput", "AudioToAudioOutputElement", "AutomaticSpeechRecognitionEarlyStoppingEnum", "AutomaticSpeechRecognitionGenerationParameters", "AutomaticSpeechRecognitionInput", "AutomaticSpeechRecognitionOutput", "AutomaticSpeechRecognitionOutputChunk", "AutomaticSpeechRecognitionParameters", "BucketFile", "BucketFileMetadata", "BucketFolder", "BucketInfo", "BucketUrl", "CLIENT_FACTORY_T", "CONFIG_NAME", "CacheNotFound", "CachedFileInfo", "CachedIncompleteFileInfo", "CachedRepoInfo", "CachedRevisionInfo", "CardData", "ChatCompletionInput", "ChatCompletionInputFunctionDefinition", "ChatCompletionInputFunctionName", "ChatCompletionInputGrammarType", "ChatCompletionInputJSONSchema", "ChatCompletionInputMessage", "ChatCompletionInputMessageChunk", "ChatCompletionInputMessageChunkType", "ChatCompletionInputResponseFormatJSONObject", "ChatCompletionInputResponseFormatJSONSchema", "ChatCompletionInputResponseFormatText", "ChatCompletionInputStreamOptions", "ChatCompletionInputTool", "ChatCompletionInputToolCall", "ChatCompletionInputToolChoiceClass", "ChatCompletionInputToolChoiceEnum", "ChatCompletionInputURL", "ChatCompletionOutput", "ChatCompletionOutputComplete", "ChatCompletionOutputFunctionDefinition", "ChatCompletionOutputLogprob", "ChatCompletionOutputLogprobs", "ChatCompletionOutputMessage", "ChatCompletionOutputToolCall", "ChatCompletionOutputTopLogprob", "ChatCompletionOutputUsage", "ChatCompletionStreamOutput", "ChatCompletionStreamOutputChoice", "ChatCompletionStreamOutputDelta", "ChatCompletionStreamOutputDeltaToolCall", "ChatCompletionStreamOutputFunction", "ChatCompletionStreamOutputLogprob", "ChatCompletionStreamOutputLogprobs", "ChatCompletionStreamOutputTopLogprob", "ChatCompletionStreamOutputUsage", "Collection", "CollectionItem", "CommitInfo", "CommitOperation", "CommitOperationAdd", "CommitOperationCopy", "CommitOperationDelete", "CommitScheduler", "CorruptedCacheException", "DDUFEntry", "DatasetCard", "DatasetCardData", "DatasetInfo", "DatasetLeaderboardEntry", "DeleteCacheStrategy", "DepthEstimationInput", "DepthEstimationOutput", "Discussion", "DiscussionComment", "DiscussionCommit", "DiscussionEvent", "DiscussionStatusChange", "DiscussionTitleChange", "DiscussionWithDetails", "DocumentQuestionAnsweringInput", "DocumentQuestionAnsweringInputData", "DocumentQuestionAnsweringOutputElement", "DocumentQuestionAnsweringParameters", "DryRunFileInfo", "EvalResult", "EvalResultEntry", "FLAX_WEIGHTS_NAME", "FeatureExtractionInput", "FeatureExtractionInputTruncationDirection", "FillMaskInput", "FillMaskOutputElement", "FillMaskParameters", "GitCommitInfo", "GitRefInfo", "GitRefs", "HFCacheInfo", "HFSummaryWriter", "HUGGINGFACE_CO_URL_HOME", "HUGGINGFACE_CO_URL_TEMPLATE", "HfApi", "HfFileMetadata", "HfFileSystem", "HfFileSystemFile", "HfFileSystemResolvedPath", "HfFileSystemStreamFile", "HfUri", "ImageClassificationInput", "ImageClassificationOutputElement", "ImageClassificationOutputTransform", "ImageClassificationParameters", "ImageSegmentationInput", "ImageSegmentationOutputElement", "ImageSegmentationParameters", "ImageSegmentationSubtask", "ImageTextToImageInput", "ImageTextToImageOutput", "ImageTextToImageParameters", "ImageTextToImageTargetSize", "ImageTextToVideoInput", "ImageTextToVideoOutput", "ImageTextToVideoParameters", "ImageTextToVideoTargetSize", "ImageToImageInput", "ImageToImageOutput", "ImageToImageParameters", "ImageToImageTargetSize", "ImageToTextEarlyStoppingEnum", "ImageToTextGenerationParameters", "ImageToTextInput", "ImageToTextOutput", "ImageToTextParameters", "ImageToVideoInput", "ImageToVideoOutput", "ImageToVideoParameters", "ImageToVideoTargetSize", "InferenceClient", "InferenceEndpoint", "InferenceEndpointError", "InferenceEndpointStatus", "InferenceEndpointTimeoutError", "InferenceEndpointType", "InferenceTimeoutError", "JobAccelerator", "JobDurations", "JobHardware", "JobHardwareInfo", "JobInfo", "JobInitiator", "JobOwner", "JobStage", "JobStatus", "KernelInfo", "MCPClient", "ModelCard", "ModelCardData", "ModelHubMixin", "ModelInfo", "OAuthInfo", "OAuthOrgInfo", "OAuthUserInfo", "ObjectDetectionBoundingBox", "ObjectDetectionInput", "ObjectDetectionOutputElement", "ObjectDetectionParameters", "Organization", "PYTORCH_WEIGHTS_NAME", "Padding", "PyTorchModelHubMixin", "QuestionAnsweringInput", "QuestionAnsweringInputData", "QuestionAnsweringOutputElement", "QuestionAnsweringParameters", "REPO_TYPE_DATASET", "REPO_TYPE_MODEL", "REPO_TYPE_SPACE", "RepoCard", "RepoFile", "RepoFolder", "RepoStorageInfo", "RepoUrl", "Sandbox", "SandboxCommandResult", "SandboxPool", "SandboxProcess", "SentenceSimilarityInput", "SentenceSimilarityInputData", "SpaceCard", "SpaceCardData", "SpaceHardware", "SpaceInfo", "SpaceRuntime", "SpaceSearchResult", "SpaceSecret", "SpaceStage", "SpaceStorage", "SpaceTemplate", "SpaceVariable", "StateDictSplit", "SummarizationInput", "SummarizationOutput", "SummarizationParameters", "SummarizationTruncationStrategy", "SyncOperation", "SyncPlan", "TF2_WEIGHTS_NAME", "TF_WEIGHTS_NAME", "TableQuestionAnsweringInput", "TableQuestionAnsweringInputData", "TableQuestionAnsweringOutputElement", "TableQuestionAnsweringParameters", "Text2TextGenerationInput", "Text2TextGenerationOutput", "Text2TextGenerationParameters", "Text2TextGenerationTruncationStrategy", "TextClassificationInput", "TextClassificationOutputElement", "TextClassificationOutputTransform", "TextClassificationParameters", "TextGenerationInput", "TextGenerationInputGenerateParameters", "TextGenerationInputGrammarType", "TextGenerationOutput", "TextGenerationOutputBestOfSequence", "TextGenerationOutputDetails", "TextGenerationOutputFinishReason", "TextGenerationOutputPrefillToken", "TextGenerationOutputToken", "TextGenerationStreamOutput", "TextGenerationStreamOutputStreamDetails", "TextGenerationStreamOutputToken", "TextToAudioEarlyStoppingEnum", "TextToAudioGenerationParameters", "TextToAudioInput", "TextToAudioOutput", "TextToAudioParameters", "TextToImageInput", "TextToImageOutput", "TextToImageParameters", "TextToSpeechEarlyStoppingEnum", "TextToSpeechGenerationParameters", "TextToSpeechInput", "TextToSpeechOutput", "TextToSpeechParameters", "TextToVideoInput", "TextToVideoOutput", "TextToVideoParameters", "TokenClassificationAggregationStrategy", "TokenClassificationInput", "TokenClassificationOutputElement", "TokenClassificationParameters", "TranslationInput", "TranslationOutput", "TranslationParameters", "TranslationTruncationStrategy", "TypeEnum", "User", "UserLikes", "VideoClassificationInput", "VideoClassificationOutputElement", "VideoClassificationOutputTransform", "VideoClassificationParameters", "VisualQuestionAnsweringInput", "VisualQuestionAnsweringInputData", "VisualQuestionAnsweringOutputElement", "VisualQuestionAnsweringParameters", "Volume", "WebhookInfo", "WebhookPayload", "WebhookPayloadComment", "WebhookPayloadDiscussion", "WebhookPayloadDiscussionChanges", "WebhookPayloadEvent", "WebhookPayloadMovedTo", "WebhookPayloadRepo", "WebhookPayloadUrl", "WebhookPayloadWebhook", "WebhookWatchedItem", "WebhooksServer", "ZeroShotClassificationInput", "ZeroShotClassificationOutputElement", "ZeroShotClassificationParameters", "ZeroShotImageClassificationInput", "ZeroShotImageClassificationOutputElement", "ZeroShotImageClassificationParameters", "ZeroShotObjectDetectionBoundingBox", "ZeroShotObjectDetectionInput", "ZeroShotObjectDetectionOutputElement", "ZeroShotObjectDetectionParameters", "_CACHED_NO_EXIST", "_save_pretrained_fastai", "accept_access_request", "add_collection_item", "add_space_secret", "add_space_variable", "attach_huggingface_oauth", "auth_check", "auth_list", "auth_switch", "batch_bucket_files", "bucket_info", "cached_assets_path", "cancel_access_request", "cancel_job", "change_discussion_status", "check_cli_update", "close_session", "comment_discussion", "copy_files", "create_branch", "create_bucket", "create_collection", "create_commit", "create_discussion", "create_inference_endpoint", "create_inference_endpoint_from_catalog", "create_pull_request", "create_repo", "create_scheduled_job", "create_scheduled_uv_job", "create_tag", "create_webhook", "dataset_info", "delete_branch", "delete_bucket", "delete_collection", "delete_collection_item", "delete_file", "delete_folder", "delete_inference_endpoint", "delete_repo", "delete_scheduled_job", "delete_space_secret", "delete_space_storage", "delete_space_variable", "delete_space_volumes", "delete_tag", "delete_webhook", "disable_space_dev_mode", "disable_webhook", "download_bucket_files", "dump_environment_info", "duplicate_repo", "duplicate_space", "edit_discussion_comment", "enable_space_dev_mode", "enable_webhook", "eval_result_entries_to_yaml", "export_entries_as_dduf", "export_folder_as_dduf", "fetch_job_logs", "fetch_job_metrics", "fetch_space_logs", "file_exists", "from_pretrained_fastai", "get_async_session", "get_bucket_file_metadata", "get_bucket_paths_info", "get_cached_repo_tree", "get_collection", "get_dataset_leaderboard", "get_dataset_tags", "get_discussion_details", "get_full_repo_name", "get_hf_file_metadata", "get_inference_endpoint", "get_local_safetensors_metadata", "get_model_tags", "get_organization_overview", "get_paths_info", "get_repo_discussions", "get_safetensors_metadata", "get_session", "get_space_runtime", "get_space_secrets", "get_space_variables", "get_token", "get_torch_storage_id", "get_torch_storage_size", "get_user_overview", "get_webhook", "grant_access", "hf_hub_download", "hf_hub_url", "hf_raise_for_status", "hffs", "inspect_job", "inspect_scheduled_job", "interpreter_login", "is_offline_mode", "kernel_info", "list_accepted_access_requests", "list_bucket_tree", "list_buckets", "list_collections", "list_daily_papers", "list_dataset_parquet_files", "list_datasets", "list_inference_catalog", "list_inference_endpoints", "list_jobs", "list_jobs_hardware", "list_lfs_files", "list_liked_repos", "list_models", "list_organization_followers", "list_organization_members", "list_papers", "list_pending_access_requests", "list_rejected_access_requests", "list_repo_commits", "list_repo_files", "list_repo_likers", "list_repo_refs", "list_repo_tree", "list_space_templates", "list_spaces", "list_spaces_hardware", "list_user_followers", "list_user_following", "list_user_repos", "list_webhooks", "load_state_dict_from_file", "load_torch_model", "logging", "login", "logout", "merge_pull_request", "metadata_eval_result", "metadata_load", "metadata_save", "metadata_update", "model_info", "move_bucket", "move_repo", "notebook_login", "paper_info", "parse_eval_result_entries", "parse_hf_uri", "parse_huggingface_oauth", "parse_local_safetensors_file_metadata", "parse_safetensors_file_metadata", "pause_inference_endpoint", "pause_space", "permanently_delete_lfs_files", "preupload_lfs_files", "push_to_hub_fastai", "read_dduf_file", "read_paper", "reject_access_request", "rename_discussion", "repo_exists", "repo_info", "repo_type_and_id_from_hf_id", "request_space_hardware", "request_space_storage", "restart_space", "resume_inference_endpoint", "resume_scheduled_job", "revision_exists", "run_as_future", "run_job", "run_uv_job", "save_torch_model", "save_torch_state_dict", "scale_to_zero_inference_endpoint", "scan_cache_dir", "search_spaces", "set_async_client_factory", "set_client_factory", "set_space_sleep_time", "set_space_volumes", "snapshot_download", "space_info", "split_state_dict_into_shards_factory", "split_torch_state_dict_into_shards", "super_squash_history", "suspend_scheduled_job", "sync_bucket", "sync_job_volume", "trigger_scheduled_job", "try_to_load_from_cache", "typer_factory", "unlike", "update_collection_item", "update_collection_metadata", "update_inference_endpoint", "update_job_labels", "update_repo_settings", "update_scheduled_job_labels", "update_webhook", "upload_file", "upload_folder", "upload_large_folder", "verify_repo_checksums", "wait_for_job", "wait_for_space", "webhook_endpoint", "whoami",]
def _attach(package_name, submodules=None, submod_attrs=None): """Attach lazily loaded submodules, functions, or other attributes.
Typically, modules import submodules and attributes as follows:
```py import mysubmodule import anothersubmodule
from .foo import someattr ```
The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports work exactly the way they would with normal imports, except that the import occurs upon first use.
The typical way to call this function, replacing the above imports, is:
```python __getattr__, __dir__ = lazy.attach( __name__, ['mysubmodule', 'anothersubmodule'], {'foo': ['someattr']} ) ``` This functionality requires Python 3.7 or higher.
Args: package_name (`str`): Typically use `__name__`. submodules (`set`): List of submodules to attach. submod_attrs (`dict`): Dictionary of submodule -> list of attributes / functions. These attributes are imported as they are used.
Returns: __getattr__, __dir__, __all__
""" if submod_attrs is None: submod_attrs = {}
if submodules is None: submodules = set() else: submodules = set(submodules)
attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
def __getattr__(name): if name in submodules: try: return importlib.import_module(f"{package_name}.{name}") except Exception as e: print(f"Error importing {package_name}.{name}: {e}") raise elif name in attr_to_modules: submod_path = f"{package_name}.{attr_to_modules[name]}" try: submod = importlib.import_module(submod_path) except Exception as e: print(f"Error importing {submod_path}: {e}") raise attr = getattr(submod, name)
# If the attribute lives in a file (module) with the same # name as the attribute, ensure that the attribute and *not* # the module is accessible on the package. if name == attr_to_modules[name]: pkg = sys.modules[package_name] pkg.__dict__[name] = attr
return attr else: raise AttributeError(f"No {package_name} attribute {name}")
def __dir__(): return __all__
return __getattr__, __dir__
__getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
if os.environ.get("EAGER_IMPORT", ""): for attr in __all__: __getattr__(attr)
# WARNING: any content below this statement is generated automatically. Any manual edit# will be lost when re-generating this file !## To update the static imports, please run the following command and commit the changes.# ```# # Use script# python utils/check_static_imports.py --update## # Or run style on codebase# make style# ```if TYPE_CHECKING: # pragma: no cover from ._buckets import ( BucketFile, # noqa: F401 BucketFileMetadata, # noqa: F401 BucketFolder, # noqa: F401 BucketInfo, # noqa: F401 BucketUrl, # noqa: F401 SyncOperation, # noqa: F401 SyncPlan, # noqa: F401 ) from ._commit_scheduler import CommitScheduler # noqa: F401 from ._eval_results import ( EvalResultEntry, # noqa: F401 eval_result_entries_to_yaml, # noqa: F401 parse_eval_result_entries, # noqa: F401 ) from ._inference_endpoints import ( InferenceEndpoint, # noqa: F401 InferenceEndpointError, # noqa: F401 InferenceEndpointStatus, # noqa: F401 InferenceEndpointTimeoutError, # noqa: F401 InferenceEndpointType, # noqa: F401 ) from ._jobs_api import ( JobAccelerator, # noqa: F401 JobDurations, # noqa: F401 JobHardware, # noqa: F401 JobHardwareInfo, # noqa: F401 JobInfo, # noqa: F401 JobInitiator, # noqa: F401 JobOwner, # noqa: F401 JobStage, # noqa: F401 JobStatus, # noqa: F401 ) from ._login import ( auth_list, # noqa: F401 auth_switch, # noqa: F401 interpreter_login, # noqa: F401 login, # noqa: F401 logout, # noqa: F401 notebook_login, # noqa: F401 ) from ._oauth import ( OAuthInfo, # noqa: F401 OAuthOrgInfo, # noqa: F401 OAuthUserInfo, # noqa: F401 attach_huggingface_oauth, # noqa: F401 parse_huggingface_oauth, # noqa: F401 ) from ._sandbox import ( Sandbox, # noqa: F401 SandboxCommandResult, # noqa: F401 SandboxPool, # noqa: F401 SandboxProcess, # noqa: F401 ) from ._snapshot_download import ( get_cached_repo_tree, # noqa: F401 snapshot_download, # noqa: F401 ) from ._space_api import ( SpaceHardware, # noqa: F401 SpaceRuntime, # noqa: F401 SpaceSecret, # noqa: F401 SpaceStage, # noqa: F401 SpaceStorage, # noqa: F401 SpaceVariable, # noqa: F401 Volume, # noqa: F401 ) from ._tensorboard_logger import HFSummaryWriter # noqa: F401 from ._webhooks_payload import ( WebhookPayload, # noqa: F401 WebhookPayloadComment, # noqa: F401 WebhookPayloadDiscussion, # noqa: F401 WebhookPayloadDiscussionChanges, # noqa: F401 WebhookPayloadEvent, # noqa: F401 WebhookPayloadMovedTo, # noqa: F401 WebhookPayloadRepo, # noqa: F401 WebhookPayloadUrl, # noqa: F401 WebhookPayloadWebhook, # noqa: F401 ) from ._webhooks_server import ( WebhooksServer, # noqa: F401 webhook_endpoint, # noqa: F401 ) from .cli._cli_utils import ( check_cli_update, # noqa: F401 typer_factory, # noqa: F401 ) from .community import ( Discussion, # noqa: F401 DiscussionComment, # noqa: F401 DiscussionCommit, # noqa: F401 DiscussionEvent, # noqa: F401 DiscussionStatusChange, # noqa: F401 DiscussionTitleChange, # noqa: F401 DiscussionWithDetails, # noqa: F401 ) from .constants import ( CONFIG_NAME, # noqa: F401 FLAX_WEIGHTS_NAME, # noqa: F401 HUGGINGFACE_CO_URL_HOME, # noqa: F401 HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401 PYTORCH_WEIGHTS_NAME, # noqa: F401 REPO_TYPE_DATASET, # noqa: F401 REPO_TYPE_MODEL, # noqa: F401 REPO_TYPE_SPACE, # noqa: F401 TF2_WEIGHTS_NAME, # noqa: F401 TF_WEIGHTS_NAME, # noqa: F401 is_offline_mode, # noqa: F401 ) from .fastai_utils import ( _save_pretrained_fastai, # noqa: F401 from_pretrained_fastai, # noqa: F401 push_to_hub_fastai, # noqa: F401 ) from .file_download import ( _CACHED_NO_EXIST, # noqa: F401 DryRunFileInfo, # noqa: F401 HfFileMetadata, # noqa: F401 get_hf_file_metadata, # noqa: F401 hf_hub_download, # noqa: F401 hf_hub_url, # noqa: F401 try_to_load_from_cache, # noqa: F401 ) from .hf_api import ( Collection, # noqa: F401 CollectionItem, # noqa: F401 CommitInfo, # noqa: F401 CommitOperation, # noqa: F401 CommitOperationAdd, # noqa: F401 CommitOperationCopy, # noqa: F401 CommitOperationDelete, # noqa: F401 DatasetInfo, # noqa: F401 DatasetLeaderboardEntry, # noqa: F401 GitCommitInfo, # noqa: F401 GitRefInfo, # noqa: F401 GitRefs, # noqa: F401 HfApi, # noqa: F401 KernelInfo, # noqa: F401 ModelInfo, # noqa: F401 Organization, # noqa: F401 RepoFile, # noqa: F401 RepoFolder, # noqa: F401 RepoStorageInfo, # noqa: F401 RepoUrl, # noqa: F401 SpaceInfo, # noqa: F401 SpaceSearchResult, # noqa: F401 SpaceTemplate, # noqa: F401 User, # noqa: F401 UserLikes, # noqa: F401 WebhookInfo, # noqa: F401 WebhookWatchedItem, # noqa: F401 accept_access_request, # noqa: F401 add_collection_item, # noqa: F401 add_space_secret, # noqa: F401 add_space_variable, # noqa: F401 auth_check, # noqa: F401 batch_bucket_files, # noqa: F401 bucket_info, # noqa: F401 cancel_access_request, # noqa: F401 cancel_job, # noqa: F401 change_discussion_status, # noqa: F401 comment_discussion, # noqa: F401 copy_files, # noqa: F401 create_branch, # noqa: F401 create_bucket, # noqa: F401 create_collection, # noqa: F401 create_commit, # noqa: F401 create_discussion, # noqa: F401 create_inference_endpoint, # noqa: F401 create_inference_endpoint_from_catalog, # noqa: F401 create_pull_request, # noqa: F401 create_repo, # noqa: F401 create_scheduled_job, # noqa: F401 create_scheduled_uv_job, # noqa: F401 create_tag, # noqa: F401 create_webhook, # noqa: F401 dataset_info, # noqa: F401 delete_branch, # noqa: F401 delete_bucket, # noqa: F401 delete_collection, # noqa: F401 delete_collection_item, # noqa: F401 delete_file, # noqa: F401 delete_folder, # noqa: F401 delete_inference_endpoint, # noqa: F401 delete_repo, # noqa: F401 delete_scheduled_job, # noqa: F401 delete_space_secret, # noqa: F401 delete_space_storage, # noqa: F401 delete_space_variable, # noqa: F401 delete_space_volumes, # noqa: F401 delete_tag, # noqa: F401 delete_webhook, # noqa: F401 disable_space_dev_mode, # noqa: F401 disable_webhook, # noqa: F401 download_bucket_files, # noqa: F401 duplicate_repo, # noqa: F401 duplicate_space, # noqa: F401 edit_discussion_comment, # noqa: F401 enable_space_dev_mode, # noqa: F401 enable_webhook, # noqa: F401 fetch_job_logs, # noqa: F401 fetch_job_metrics, # noqa: F401 fetch_space_logs, # noqa: F401 file_exists, # noqa: F401 get_bucket_file_metadata, # noqa: F401 get_bucket_paths_info, # noqa: F401 get_collection, # noqa: F401 get_dataset_leaderboard, # noqa: F401 get_dataset_tags, # noqa: F401 get_discussion_details, # noqa: F401 get_full_repo_name, # noqa: F401 get_inference_endpoint, # noqa: F401 get_local_safetensors_metadata, # noqa: F401 get_model_tags, # noqa: F401 get_organization_overview, # noqa: F401 get_paths_info, # noqa: F401 get_repo_discussions, # noqa: F401 get_safetensors_metadata, # noqa: F401 get_space_runtime, # noqa: F401 get_space_secrets, # noqa: F401 get_space_variables, # noqa: F401 get_user_overview, # noqa: F401 get_webhook, # noqa: F401 grant_access, # noqa: F401 inspect_job, # noqa: F401 inspect_scheduled_job, # noqa: F401 kernel_info, # noqa: F401 list_accepted_access_requests, # noqa: F401 list_bucket_tree, # noqa: F401 list_buckets, # noqa: F401 list_collections, # noqa: F401 list_daily_papers, # noqa: F401 list_dataset_parquet_files, # noqa: F401 list_datasets, # noqa: F401 list_inference_catalog, # noqa: F401 list_inference_endpoints, # noqa: F401 list_jobs, # noqa: F401 list_jobs_hardware, # noqa: F401 list_lfs_files, # noqa: F401 list_liked_repos, # noqa: F401 list_models, # noqa: F401 list_organization_followers, # noqa: F401 list_organization_members, # noqa: F401 list_papers, # noqa: F401 list_pending_access_requests, # noqa: F401 list_rejected_access_requests, # noqa: F401 list_repo_commits, # noqa: F401 list_repo_files, # noqa: F401 list_repo_likers, # noqa: F401 list_repo_refs, # noqa: F401 list_repo_tree, # noqa: F401 list_space_templates, # noqa: F401 list_spaces, # noqa: F401 list_spaces_hardware, # noqa: F401 list_user_followers, # noqa: F401 list_user_following, # noqa: F401 list_user_repos, # noqa: F401 list_webhooks, # noqa: F401 merge_pull_request, # noqa: F401 model_info, # noqa: F401 move_bucket, # noqa: F401 move_repo, # noqa: F401 paper_info, # noqa: F401 parse_local_safetensors_file_metadata, # noqa: F401 parse_safetensors_file_metadata, # noqa: F401 pause_inference_endpoint, # noqa: F401 pause_space, # noqa: F401 permanently_delete_lfs_files, # noqa: F401 preupload_lfs_files, # noqa: F401 read_paper, # noqa: F401 reject_access_request, # noqa: F401 rename_discussion, # noqa: F401 repo_exists, # noqa: F401 repo_info, # noqa: F401 repo_type_and_id_from_hf_id, # noqa: F401 request_space_hardware, # noqa: F401 request_space_storage, # noqa: F401 restart_space, # noqa: F401 resume_inference_endpoint, # noqa: F401 resume_scheduled_job, # noqa: F401 revision_exists, # noqa: F401 run_as_future, # noqa: F401 run_job, # noqa: F401 run_uv_job, # noqa: F401 scale_to_zero_inference_endpoint, # noqa: F401 search_spaces, # noqa: F401 set_space_sleep_time, # noqa: F401 set_space_volumes, # noqa: F401 space_info, # noqa: F401 super_squash_history, # noqa: F401 suspend_scheduled_job, # noqa: F401 sync_bucket, # noqa: F401 sync_job_volume, # noqa: F401 trigger_scheduled_job, # noqa: F401 unlike, # noqa: F401 update_collection_item, # noqa: F401 update_collection_metadata, # noqa: F401 update_inference_endpoint, # noqa: F401 update_job_labels, # noqa: F401 update_repo_settings, # noqa: F401 update_scheduled_job_labels, # noqa: F401 update_webhook, # noqa: F401 upload_file, # noqa: F401 upload_folder, # noqa: F401 upload_large_folder, # noqa: F401 verify_repo_checksums, # noqa: F401 wait_for_job, # noqa: F401 wait_for_space, # noqa: F401 whoami, # noqa: F401 ) from .hf_file_system import ( HfFileSystem, # noqa: F401 HfFileSystemFile, # noqa: F401 HfFileSystemResolvedPath, # noqa: F401 HfFileSystemStreamFile, # noqa: F401 hffs, # noqa: F401 ) from .hub_mixin import ( ModelHubMixin, # noqa: F401 PyTorchModelHubMixin, # noqa: F401 ) from .inference._client import ( InferenceClient, # noqa: F401 InferenceTimeoutError, # noqa: F401 ) from .inference._generated._async_client import AsyncInferenceClient # noqa: F401 from .inference._generated.types import ( AudioClassificationInput, # noqa: F401 AudioClassificationOutputElement, # noqa: F401 AudioClassificationOutputTransform, # noqa: F401 AudioClassificationParameters, # noqa: F401 AudioToAudioInput, # noqa: F401 AudioToAudioOutputElement, # noqa: F401 AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401 AutomaticSpeechRecognitionGenerationParameters, # noqa: F401 AutomaticSpeechRecognitionInput, # noqa: F401 AutomaticSpeechRecognitionOutput, # noqa: F401 AutomaticSpeechRecognitionOutputChunk, # noqa: F401 AutomaticSpeechRecognitionParameters, # noqa: F401 ChatCompletionInput, # noqa: F401 ChatCompletionInputFunctionDefinition, # noqa: F401 ChatCompletionInputFunctionName, # noqa: F401 ChatCompletionInputGrammarType, # noqa: F401 ChatCompletionInputJSONSchema, # noqa: F401 ChatCompletionInputMessage, # noqa: F401 ChatCompletionInputMessageChunk, # noqa: F401 ChatCompletionInputMessageChunkType, # noqa: F401 ChatCompletionInputResponseFormatJSONObject, # noqa: F401 ChatCompletionInputResponseFormatJSONSchema, # noqa: F401 ChatCompletionInputResponseFormatText, # noqa: F401 ChatCompletionInputStreamOptions, # noqa: F401 ChatCompletionInputTool, # noqa: F401 ChatCompletionInputToolCall, # noqa: F401 ChatCompletionInputToolChoiceClass, # noqa: F401 ChatCompletionInputToolChoiceEnum, # noqa: F401 ChatCompletionInputURL, # noqa: F401 ChatCompletionOutput, # noqa: F401 ChatCompletionOutputComplete, # noqa: F401 ChatCompletionOutputFunctionDefinition, # noqa: F401 ChatCompletionOutputLogprob, # noqa: F401 ChatCompletionOutputLogprobs, # noqa: F401 ChatCompletionOutputMessage, # noqa: F401 ChatCompletionOutputToolCall, # noqa: F401 ChatCompletionOutputTopLogprob, # noqa: F401 ChatCompletionOutputUsage, # noqa: F401 ChatCompletionStreamOutput, # noqa: F401 ChatCompletionStreamOutputChoice, # noqa: F401 ChatCompletionStreamOutputDelta, # noqa: F401 ChatCompletionStreamOutputDeltaToolCall, # noqa: F401 ChatCompletionStreamOutputFunction, # noqa: F401 ChatCompletionStreamOutputLogprob, # noqa: F401 ChatCompletionStreamOutputLogprobs, # noqa: F401 ChatCompletionStreamOutputTopLogprob, # noqa: F401 ChatCompletionStreamOutputUsage, # noqa: F401 DepthEstimationInput, # noqa: F401 DepthEstimationOutput, # noqa: F401 DocumentQuestionAnsweringInput, # noqa: F401 DocumentQuestionAnsweringInputData, # noqa: F401 DocumentQuestionAnsweringOutputElement, # noqa: F401 DocumentQuestionAnsweringParameters, # noqa: F401 FeatureExtractionInput, # noqa: F401 FeatureExtractionInputTruncationDirection, # noqa: F401 FillMaskInput, # noqa: F401 FillMaskOutputElement, # noqa: F401 FillMaskParameters, # noqa: F401 ImageClassificationInput, # noqa: F401 ImageClassificationOutputElement, # noqa: F401 ImageClassificationOutputTransform, # noqa: F401 ImageClassificationParameters, # noqa: F401 ImageSegmentationInput, # noqa: F401 ImageSegmentationOutputElement, # noqa: F401 ImageSegmentationParameters, # noqa: F401 ImageSegmentationSubtask, # noqa: F401 ImageTextToImageInput, # noqa: F401 ImageTextToImageOutput, # noqa: F401 ImageTextToImageParameters, # noqa: F401 ImageTextToImageTargetSize, # noqa: F401 ImageTextToVideoInput, # noqa: F401 ImageTextToVideoOutput, # noqa: F401 ImageTextToVideoParameters, # noqa: F401 ImageTextToVideoTargetSize, # noqa: F401 ImageToImageInput, # noqa: F401 ImageToImageOutput, # noqa: F401 ImageToImageParameters, # noqa: F401 ImageToImageTargetSize, # noqa: F401 ImageToTextEarlyStoppingEnum, # noqa: F401 ImageToTextGenerationParameters, # noqa: F401 ImageToTextInput, # noqa: F401 ImageToTextOutput, # noqa: F401 ImageToTextParameters, # noqa: F401 ImageToVideoInput, # noqa: F401 ImageToVideoOutput, # noqa: F401 ImageToVideoParameters, # noqa: F401 ImageToVideoTargetSize, # noqa: F401 ObjectDetectionBoundingBox, # noqa: F401 ObjectDetectionInput, # noqa: F401 ObjectDetectionOutputElement, # noqa: F401 ObjectDetectionParameters, # noqa: F401 Padding, # noqa: F401 QuestionAnsweringInput, # noqa: F401 QuestionAnsweringInputData, # noqa: F401 QuestionAnsweringOutputElement, # noqa: F401 QuestionAnsweringParameters, # noqa: F401 SentenceSimilarityInput, # noqa: F401 SentenceSimilarityInputData, # noqa: F401 SummarizationInput, # noqa: F401 SummarizationOutput, # noqa: F401 SummarizationParameters, # noqa: F401 SummarizationTruncationStrategy, # noqa: F401 TableQuestionAnsweringInput, # noqa: F401 TableQuestionAnsweringInputData, # noqa: F401 TableQuestionAnsweringOutputElement, # noqa: F401 TableQuestionAnsweringParameters, # noqa: F401 Text2TextGenerationInput, # noqa: F401 Text2TextGenerationOutput, # noqa: F401 Text2TextGenerationParameters, # noqa: F401 Text2TextGenerationTruncationStrategy, # noqa: F401 TextClassificationInput, # noqa: F401 TextClassificationOutputElement, # noqa: F401 TextClassificationOutputTransform, # noqa: F401 TextClassificationParameters, # noqa: F401 TextGenerationInput, # noqa: F401 TextGenerationInputGenerateParameters, # noqa: F401 TextGenerationInputGrammarType, # noqa: F401 TextGenerationOutput, # noqa: F401 TextGenerationOutputBestOfSequence, # noqa: F401 TextGenerationOutputDetails, # noqa: F401 TextGenerationOutputFinishReason, # noqa: F401 TextGenerationOutputPrefillToken, # noqa: F401 TextGenerationOutputToken, # noqa: F401 TextGenerationStreamOutput, # noqa: F401 TextGenerationStreamOutputStreamDetails, # noqa: F401 TextGenerationStreamOutputToken, # noqa: F401 TextToAudioEarlyStoppingEnum, # noqa: F401 TextToAudioGenerationParameters, # noqa: F401 TextToAudioInput, # noqa: F401 TextToAudioOutput, # noqa: F401 TextToAudioParameters, # noqa: F401 TextToImageInput, # noqa: F401 TextToImageOutput, # noqa: F401 TextToImageParameters, # noqa: F401 TextToSpeechEarlyStoppingEnum, # noqa: F401 TextToSpeechGenerationParameters, # noqa: F401 TextToSpeechInput, # noqa: F401 TextToSpeechOutput, # noqa: F401 TextToSpeechParameters, # noqa: F401 TextToVideoInput, # noqa: F401 TextToVideoOutput, # noqa: F401 TextToVideoParameters, # noqa: F401 TokenClassificationAggregationStrategy, # noqa: F401 TokenClassificationInput, # noqa: F401 TokenClassificationOutputElement, # noqa: F401 TokenClassificationParameters, # noqa: F401 TranslationInput, # noqa: F401 TranslationOutput, # noqa: F401 TranslationParameters, # noqa: F401 TranslationTruncationStrategy, # noqa: F401 TypeEnum, # noqa: F401 VideoClassificationInput, # noqa: F401 VideoClassificationOutputElement, # noqa: F401 VideoClassificationOutputTransform, # noqa: F401 VideoClassificationParameters, # noqa: F401 VisualQuestionAnsweringInput, # noqa: F401 VisualQuestionAnsweringInputData, # noqa: F401 VisualQuestionAnsweringOutputElement, # noqa: F401 VisualQuestionAnsweringParameters, # noqa: F401 ZeroShotClassificationInput, # noqa: F401 ZeroShotClassificationOutputElement, # noqa: F401 ZeroShotClassificationParameters, # noqa: F401 ZeroShotImageClassificationInput, # noqa: F401 ZeroShotImageClassificationOutputElement, # noqa: F401 ZeroShotImageClassificationParameters, # noqa: F401 ZeroShotObjectDetectionBoundingBox, # noqa: F401 ZeroShotObjectDetectionInput, # noqa: F401 ZeroShotObjectDetectionOutputElement, # noqa: F401 ZeroShotObjectDetectionParameters, # noqa: F401 ) from .inference._mcp.agent import Agent # noqa: F401 from .inference._mcp.mcp_client import MCPClient # noqa: F401 from .repocard import ( DatasetCard, # noqa: F401 ModelCard, # noqa: F401 RepoCard, # noqa: F401 SpaceCard, # noqa: F401 metadata_eval_result, # noqa: F401 metadata_load, # noqa: F401 metadata_save, # noqa: F401 metadata_update, # noqa: F401 ) from .repocard_data import ( CardData, # noqa: F401 DatasetCardData, # noqa: F401 EvalResult, # noqa: F401 ModelCardData, # noqa: F401 SpaceCardData, # noqa: F401 ) from .serialization import ( StateDictSplit, # noqa: F401 get_torch_storage_id, # noqa: F401 get_torch_storage_size, # noqa: F401 load_state_dict_from_file, # noqa: F401 load_torch_model, # noqa: F401 save_torch_model, # noqa: F401 save_torch_state_dict, # noqa: F401 split_state_dict_into_shards_factory, # noqa: F401 split_torch_state_dict_into_shards, # noqa: F401 ) from .serialization._dduf import ( DDUFEntry, # noqa: F401 export_entries_as_dduf, # noqa: F401 export_folder_as_dduf, # noqa: F401 read_dduf_file, # noqa: F401 ) from .utils import ( ASYNC_CLIENT_FACTORY_T, # noqa: F401 CLIENT_FACTORY_T, # noqa: F401 CachedFileInfo, # noqa: F401 CachedIncompleteFileInfo, # noqa: F401 CachedRepoInfo, # noqa: F401 CachedRevisionInfo, # noqa: F401 CacheNotFound, # noqa: F401 CorruptedCacheException, # noqa: F401 DeleteCacheStrategy, # noqa: F401 HFCacheInfo, # noqa: F401 HfUri, # noqa: F401 cached_assets_path, # noqa: F401 close_session, # noqa: F401 dump_environment_info, # noqa: F401 get_async_session, # noqa: F401 get_session, # noqa: F401 get_token, # noqa: F401 hf_raise_for_status, # noqa: F401 logging, # noqa: F401 parse_hf_uri, # noqa: F401 scan_cache_dir, # noqa: F401 set_async_client_factory, # noqa: F401 set_client_factory, # noqa: F401 )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244# Copyright 2026-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."""Shared logic for bucket operations.
This module contains the core buckets logic used by both the CLI and the Python API."""
import fnmatchimport jsonimport mimetypesimport osimport statimport sysimport timefrom collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal
from . import constants, loggingfrom .errors import BucketNotFoundErrorfrom .utils import ( HfUri, StatusLine, XetFileData, disable_progress_bars, enable_progress_bars, parse_datetime, parse_hf_uri,)from .utils._hf_uris import _looks_like_hf_url
if TYPE_CHECKING: from .hf_api import HfApi
logger = logging.get_logger(__name__)
BUCKET_PREFIX = "hf://buckets/"_SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons
# =============================================================================# Bucket data structures# =============================================================================
@dataclassclass BucketInfo: """ Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
Attributes: id (`str`): ID of the bucket. private (`bool`): Is the bucket private. created_at (`datetime`): Date of creation of the bucket on the Hub. size (`int`): Size of the bucket in bytes. total_files (`int`): Total number of files in the bucket. """
id: str private: bool created_at: datetime size: int total_files: int
def __init__(self, **kwargs): self.id = kwargs.pop("id") self.private = kwargs.pop("private") self.created_at = parse_datetime(kwargs.pop("createdAt")) self.size = kwargs.pop("size") self.total_files = kwargs.pop("totalFiles") self.__dict__.update(**kwargs)
@dataclassclass _BucketAddFile: source: str | Path | bytes destination: str
xet_hash: str | None = field(default=None) size: int | None = field(default=None) mtime: int = field(init=False) content_type: str | None = field(init=False)
def __post_init__(self) -> None: self.content_type = None if isinstance(self.source, (str, Path)): # guess content type from source path self.content_type = mimetypes.guess_type(self.source)[0] if self.content_type is None: # or default to destination path content type self.content_type = mimetypes.guess_type(self.destination)[0]
self.mtime = int( os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000 )
@dataclassclass _BucketCopyFile: destination: str xet_hash: str source_repo_type: str # "model", "dataset", "space", "bucket" source_repo_id: str size: int | None = field(default=None) mtime: int = field(init=False) content_type: str | None = field(init=False)
def __post_init__(self) -> None: self.content_type = mimetypes.guess_type(self.destination)[0] self.mtime = int(time.time() * 1000)
@dataclassclass _BucketDeleteFile: path: str
@dataclass(frozen=True)class BucketFileMetadata: """Data structure containing information about a file in a bucket.
Returned by [`get_bucket_file_metadata`].
Args: size (`int`): Size of the file in bytes. xet_file_data (`XetFileData`): Xet information for the file (hash and refresh route). """
size: int xet_file_data: XetFileData
@dataclassclass BucketUrl: """Describes a bucket URL on the Hub.
`BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties: - endpoint (`str`) - namespace (`str`) - bucket_id (`str`) - url (`str`) - uri (`HfUri`)
Args: url (`str`): String value of the bucket url. endpoint (`str`, *optional*): Endpoint of the Hub. Defaults to <https://huggingface.co>. """
url: str endpoint: str = "" namespace: str = field(init=False) bucket_id: str = field(init=False) uri: HfUri = field(init=False)
def __post_init__(self) -> None: self.endpoint = self.endpoint or constants.ENDPOINT
# Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}` url_path = self.url.replace(self.endpoint, "").strip("/") # Remove leading "buckets/" prefix if url_path.startswith("buckets/"): url_path = url_path[len("buckets/") :] parsed = _parse_bucket_uri(url_path) if parsed.path_in_repo: raise ValueError(f"Unable to parse bucket URL: {self.url}") self.namespace = parsed.id.split("/")[0] self.bucket_id = parsed.id self.uri = parsed
@dataclassclass BucketFile: """ Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
Similar to [`RepoFile`] but for files in buckets. """
type: Literal["file"] path: str size: int xet_hash: str mtime: datetime | None uploaded_at: datetime | None
def __init__(self, **kwargs): self.type = kwargs.pop("type") self.path = kwargs.pop("path") self.size = kwargs.pop("size") self.xet_hash = kwargs.pop("xetHash") mtime = kwargs.pop("mtime", None) self.mtime = parse_datetime(mtime) if mtime else None uploaded_at = kwargs.pop("uploadedAt", None) self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None
@dataclassclass BucketFolder: """ Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
Similar to [`RepoFolder`] but for directories in buckets. """
type: Literal["directory"] path: str uploaded_at: datetime | None
def __init__(self, **kwargs): self.type = kwargs.pop("type") self.path = kwargs.pop("path") uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None) self.uploaded_at = ( (uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at)) if uploaded_at else None )
# =============================================================================# Bucket path parsing# =============================================================================
def _parse_bucket_uri(path: str) -> HfUri: """Parse a bucket path into a HfUri.
Accepts: - `hf://buckets/namespace/name(/path/in/repo)` URIs, - Hugging Face web URLs such as `https://huggingface.co/buckets/namespace/name(/tree/path)`, - plain `namespace/name(/path/in/repo)` paths. """ if path.startswith(constants.HF_PROTOCOL) or _looks_like_hf_url(path): # Don't use 'if is_hf_uri(...)' here as we prefer 'parse_hf_uri(...)' to raise the exact error message. parsed = parse_hf_uri(path) if not parsed.is_bucket: raise ValueError(f"Invalid bucket path: {path}. Must be a bucket URI (hf://buckets/...).") return parsed parts = path.split("/", 2) if len(parts) < 2 or not parts[0] or not parts[1]: raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name") bucket_id = f"{parts[0]}/{parts[1]}" prefix = "/".join(parts[2:]) return HfUri(type="bucket", id=bucket_id, path_in_repo=prefix)
def _is_bucket_path(path: str) -> bool: """Check if a path is a bucket path.
Do not raise if the path is not a hf:// URI. Raise if the path is a hf:// URI but with an incorrect format. """ if not path.startswith(constants.HF_PROTOCOL): return False return parse_hf_uri(path).is_bucket
# =============================================================================# Sync data structures# =============================================================================
@dataclassclass SyncOperation: """Represents a sync operation to be performed."""
action: Literal["upload", "download", "delete", "skip"] path: str size: int | None = None reason: str = "" local_mtime: str | None = None remote_mtime: str | None = None bucket_file: BucketFile | None = None # BucketFile when available (not serialized to plan file)
@dataclassclass SyncPlan: """Represents a complete sync plan."""
source: str dest: str timestamp: str operations: list[SyncOperation] = field(default_factory=list)
def summary(self) -> dict[str, int | str]: uploads = sum(1 for op in self.operations if op.action == "upload") downloads = sum(1 for op in self.operations if op.action == "download") deletes = sum(1 for op in self.operations if op.action == "delete") skips = sum(1 for op in self.operations if op.action == "skip") total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download")) return { "uploads": uploads, "downloads": downloads, "deletes": deletes, "skips": skips, "total_size": total_size, }
# =============================================================================# Filter matching# =============================================================================
class FilterMatcher: """Matches file paths against include/exclude patterns."""
def __init__( self, include_patterns: list[str] | None = None, exclude_patterns: list[str] | None = None, filter_rules: list[tuple[str, str]] | None = None, ): """Initialize the filter matcher.
Args: include_patterns: Patterns to include (from --include) exclude_patterns: Patterns to exclude (from --exclude) filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples """ self.include_patterns = include_patterns or [] self.exclude_patterns = exclude_patterns or [] self.filter_rules = filter_rules or []
def matches(self, path: str) -> bool: """Check if a path should be included based on the filter rules.
Filtering rules: - Filters are evaluated in order, first matching rule decides - If no rules match, include by default (unless include patterns are specified) """ # First check filter rules from file (in order) for sign, pattern in self.filter_rules: if fnmatch.fnmatch(path, pattern): return sign == "+"
# Then check CLI patterns for pattern in self.exclude_patterns: if fnmatch.fnmatch(path, pattern): return False
for pattern in self.include_patterns: if fnmatch.fnmatch(path, pattern): return True
# If include patterns were specified but none matched, exclude if self.include_patterns: return False
# Default: include return True
def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]: """Parse a filter file and return a list of (sign, pattern) tuples.
Filter file format: - Lines starting with "+" are include patterns - Lines starting with "-" are exclude patterns - Empty lines and lines starting with "#" are ignored """ rules = [] with open(filter_file) as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue if line.startswith("+"): rules.append(("+", line[1:].strip())) elif line.startswith("-"): rules.append(("-", line[1:].strip())) else: # Default to include if no prefix rules.append(("+", line)) return rules
# =============================================================================# File listing# =============================================================================
def _stat_local(path: str) -> tuple[int, float] | None: """Stat a local file and return (size, mtime_ms).
Returns None if the path is missing or is a directory. Uses a single ``os.stat`` call so callers don't pay for multiple syscalls per file. """ try: st = os.stat(path) except OSError: return None if stat.S_ISDIR(st.st_mode): return None return st.st_size, st.st_mtime * 1000
def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]: """List all files in a local directory.
Yields: tuple: (relative_path, size, mtime_ms) for each file """ local_path = os.path.abspath(local_path) if not os.path.isdir(local_path): raise ValueError(f"Local path must be a directory: {local_path}")
for root, _, files in os.walk(local_path): for filename in files: full_path = os.path.join(root, filename) stat_info = _stat_local(full_path) if stat_info is None: continue rel_path = os.path.relpath(full_path, local_path) # Normalize to forward slashes for consistency rel_path = rel_path.replace(os.sep, "/") yield rel_path, stat_info[0], stat_info[1]
def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]: """List all files in a bucket with a given prefix.
Yields: tuple: (relative_path, size, mtime_ms, bucket_file) for each file. bucket_file is the BucketFile object from list_bucket_tree. """ for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True): if isinstance(item, BucketFolder): continue path = item.path # Remove prefix from path to get relative path # Only strip prefix if it's followed by "/" (directory boundary) or is exact match if prefix: if path.startswith(prefix + "/"): rel_path = path[len(prefix) + 1 :] elif path == prefix: # Exact match: the file IS the prefix (e.g., single file download) rel_path = path.rsplit("/", 1)[-1] if "/" in path else path else: # Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub") # Skip this file - it was returned by the API but doesn't belong to this prefix continue else: rel_path = path mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0 yield rel_path, item.size, mtime_ms, item
# =============================================================================# Sync plan computation# =============================================================================
def _mtime_to_iso(mtime_ms: float) -> str: """Convert mtime in milliseconds to ISO format string.""" return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat()
def _compare_files_for_sync( *, path: str, action: Literal["upload", "download"], source_size: int, source_mtime: float, dest_size: int, dest_mtime: float, source_newer_label: str, dest_newer_label: str, ignore_sizes: bool, ignore_times: bool, ignore_existing: bool, bucket_file: Any | None = None,) -> SyncOperation: """Compare source and dest files and return the appropriate sync operation.
This is a unified helper for both upload and download directions.
Args: path: Relative file path action: "upload" or "download" source_size: Size of the source file (bytes) source_mtime: Mtime of the source file (milliseconds) dest_size: Size of the destination file (bytes) dest_mtime: Mtime of the destination file (milliseconds) source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer") dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer") ignore_sizes: Only compare mtime ignore_times: Only compare size ignore_existing: Skip files that exist on receiver bucket_file: BucketFile object (for downloads only)
Returns: SyncOperation describing the action to take """ local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime) remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime)
base_kwargs: dict[str, Any] = { "path": path, "size": source_size, "local_mtime": local_mtime_iso, "remote_mtime": remote_mtime_iso, }
if ignore_existing: return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs)
size_differs = source_size != dest_size source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS
if ignore_sizes: if source_newer: return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs) else: dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS skip_reason = dest_newer_label if dest_newer else "same mtime" return SyncOperation(action="skip", reason=skip_reason, **base_kwargs) elif ignore_times: if size_differs: return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs) else: return SyncOperation(action="skip", reason="same size", **base_kwargs) else: if size_differs or source_newer: reason = "size differs" if size_differs else source_newer_label return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs) else: return SyncOperation(action="skip", reason="identical", **base_kwargs)
def _compute_sync_plan( source: str, dest: str, api: "HfApi", delete: bool = False, ignore_times: bool = False, ignore_sizes: bool = False, existing: bool = False, ignore_existing: bool = False, filter_matcher: FilterMatcher | None = None, status: Any | None = None,) -> SyncPlan: """Compute the sync plan by comparing source and destination.
Returns: SyncPlan with all operations to be performed """ filter_matcher = filter_matcher or FilterMatcher() is_upload = not _is_bucket_path(source) and _is_bucket_path(dest) is_download = _is_bucket_path(source) and not _is_bucket_path(dest)
if not is_upload and not is_download: raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.")
plan = SyncPlan( source=source, dest=dest, timestamp=datetime.now(timezone.utc).isoformat(), )
remote_total: int | None = None if is_upload: # Local -> Remote local_path = os.path.abspath(source) parsed = _parse_bucket_uri(dest) bucket_id, prefix = parsed.id, parsed.path_in_repo
if not os.path.isdir(local_path): raise ValueError(f"Source must be a directory: {local_path}")
# Get local and remote file lists local_files = {} for rel_path, size, mtime_ms in _list_local_files(local_path): if filter_matcher.matches(rel_path): local_files[rel_path] = (size, mtime_ms) if status: status.update(f"Scanning local directory ({len(local_files)} files)") if status: status.done(f"Scanning local directory ({len(local_files)} files)")
remote_files = {} if status: try: remote_total = api.bucket_info(bucket_id).total_files except Exception: pass try: for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix): if filter_matcher.matches(rel_path): remote_files[rel_path] = (size, mtime_ms) if status: total_str = f"/{remote_total}" if remote_total is not None else "" status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)") except BucketNotFoundError: # Bucket doesn't exist yet - this is expected for new uploads logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.") if status: status.done(f"Scanning remote bucket ({len(remote_files)} files)")
# Compare files all_paths = set(local_files.keys()) | set(remote_files.keys()) if status: status.done(f"Comparing files ({len(all_paths)} paths)") for path in sorted(all_paths): local_info = local_files.get(path) remote_info = remote_files.get(path)
if local_info and not remote_info: # New file if existing: # --existing: skip new files plan.operations.append( SyncOperation( action="skip", path=path, size=local_info[0], reason="new file (--existing)", local_mtime=_mtime_to_iso(local_info[1]), ) ) else: plan.operations.append( SyncOperation( action="upload", path=path, size=local_info[0], reason="new file", local_mtime=_mtime_to_iso(local_info[1]), ) ) elif local_info and remote_info: # File exists in both - use helper to determine action local_size, local_mtime = local_info remote_size, remote_mtime = remote_info plan.operations.append( _compare_files_for_sync( path=path, action="upload", source_size=local_size, source_mtime=local_mtime, dest_size=remote_size, dest_mtime=remote_mtime, source_newer_label="local newer", dest_newer_label="remote newer", ignore_sizes=ignore_sizes, ignore_times=ignore_times, ignore_existing=ignore_existing, ) ) elif not local_info and remote_info and delete: # File only in remote and --delete mode plan.operations.append( SyncOperation( action="delete", path=path, size=remote_info[0], reason="not in source (--delete)", remote_mtime=_mtime_to_iso(remote_info[1]), ) )
else: # Remote -> Local (download) parsed = _parse_bucket_uri(source) bucket_id, prefix = parsed.id, parsed.path_in_repo local_path = os.path.abspath(dest)
# Get remote and local file lists remote_files = {} bucket_file_map: dict[str, Any] = {} if status: try: remote_total = api.bucket_info(bucket_id).total_files except Exception: pass for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix): if filter_matcher.matches(rel_path): remote_files[rel_path] = (size, mtime_ms) bucket_file_map[rel_path] = bucket_file if status: total_str = f"/{remote_total}" if remote_total is not None else "" status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)") if status: status.done(f"Scanning remote bucket ({len(remote_files)} files)")
local_files = {} if os.path.isdir(local_path): if delete: # Full walk needed to discover local-only files for deletion. for rel_path, size, mtime_ms in _list_local_files(local_path): if filter_matcher.matches(rel_path): local_files[rel_path] = (size, mtime_ms) if status: status.update(f"Scanning local directory ({len(local_files)} files)") else: # Without --delete, the plan only depends on paths that exist # remotely. Stat just those instead of walking the whole tree, # which can take minutes when dest sits in a large directory # like ~/.cache/huggingface/. for rel_path in remote_files: local_file = os.path.join(local_path, rel_path) stat_info = _stat_local(local_file) if stat_info is None: continue local_files[rel_path] = stat_info if status: status.update(f"Scanning local directory ({len(local_files)} files)") if status: status.done(f"Scanning local directory ({len(local_files)} files)")
# Compare files all_paths = set(remote_files.keys()) | set(local_files.keys()) if status: status.done(f"Comparing files ({len(all_paths)} paths)") for path in sorted(all_paths): remote_info = remote_files.get(path) local_info = local_files.get(path)
if remote_info and not local_info: # New file if existing: # --existing: skip new files plan.operations.append( SyncOperation( action="skip", path=path, size=remote_info[0], reason="new file (--existing)", remote_mtime=_mtime_to_iso(remote_info[1]), ) ) else: plan.operations.append( SyncOperation( action="download", path=path, size=remote_info[0], reason="new file", remote_mtime=_mtime_to_iso(remote_info[1]), bucket_file=bucket_file_map.get(path), ) ) elif remote_info and local_info: # File exists in both - use helper to determine action remote_size, remote_mtime = remote_info local_size, local_mtime = local_info plan.operations.append( _compare_files_for_sync( path=path, action="download", source_size=remote_size, source_mtime=remote_mtime, dest_size=local_size, dest_mtime=local_mtime, source_newer_label="remote newer", dest_newer_label="local newer", ignore_sizes=ignore_sizes, ignore_times=ignore_times, ignore_existing=ignore_existing, bucket_file=bucket_file_map.get(path), ) ) elif not remote_info and local_info and delete: # File only in local and --delete mode plan.operations.append( SyncOperation( action="delete", path=path, size=local_info[0], reason="not in source (--delete)", local_mtime=_mtime_to_iso(local_info[1]), ) )
return plan
# =============================================================================# Plan serialization# =============================================================================
def _write_plan(plan: SyncPlan, f) -> None: """Write a sync plan as JSONL to a file-like object.""" # Write header header = { "type": "header", "source": plan.source, "dest": plan.dest, "timestamp": plan.timestamp, "summary": plan.summary(), } f.write(json.dumps(header) + "\n")
# Write operations for op in plan.operations: op_dict: dict[str, Any] = { "type": "operation", "action": op.action, "path": op.path, "reason": op.reason, } if op.size is not None: op_dict["size"] = op.size if op.local_mtime is not None: op_dict["local_mtime"] = op.local_mtime if op.remote_mtime is not None: op_dict["remote_mtime"] = op.remote_mtime f.write(json.dumps(op_dict) + "\n")
def _save_plan(plan: SyncPlan, plan_file: str) -> None: """Save a sync plan to a JSONL file.""" with open(plan_file, "w") as f: _write_plan(plan, f)
def _load_plan(plan_file: str) -> SyncPlan: """Load a sync plan from a JSONL file.""" with open(plan_file) as f: lines = f.readlines()
if not lines: raise ValueError(f"Empty plan file: {plan_file}")
# Parse header header = json.loads(lines[0]) if header.get("type") != "header": raise ValueError("Invalid plan file: expected header as first line")
plan = SyncPlan( source=header["source"], dest=header["dest"], timestamp=header["timestamp"], )
# Parse operations for line in lines[1:]: op_dict = json.loads(line) if op_dict.get("type") != "operation": continue plan.operations.append( SyncOperation( action=op_dict["action"], path=op_dict["path"], size=op_dict.get("size"), reason=op_dict.get("reason", ""), local_mtime=op_dict.get("local_mtime"), remote_mtime=op_dict.get("remote_mtime"), ) )
return plan
# =============================================================================# Plan execution# =============================================================================
def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Any | None = None) -> None: """Execute a sync plan.""" is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest) is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest)
if is_upload: local_path = os.path.abspath(plan.source) parsed = _parse_bucket_uri(plan.dest) bucket_id, prefix = parsed.id, parsed.path_in_repo
# Collect operations add_files: list[tuple[str | Path | bytes, str]] = [] delete_paths: list[str] = []
for op in plan.operations: match op.action: case "upload": local_file = os.path.join(local_path, op.path) remote_path = f"{prefix}/{op.path}" if prefix else op.path if verbose: print(f" Uploading: {op.path} ({op.reason})") add_files.append((local_file, remote_path)) case "delete": remote_path = f"{prefix}/{op.path}" if prefix else op.path if verbose: print(f" Deleting: {op.path} ({op.reason})") delete_paths.append(remote_path) case "skip" if verbose: print(f" Skipping: {op.path} ({op.reason})")
# Execute batch operations if add_files or delete_paths: if status: parts = [] if add_files: parts.append(f"uploading {len(add_files)} files") if delete_paths: parts.append(f"deleting {len(delete_paths)} files") status.done(", ".join(parts).capitalize()) api.batch_bucket_files( bucket_id, add=add_files or None, delete=delete_paths or None, )
elif is_download: parsed = _parse_bucket_uri(plan.source) bucket_id, prefix = parsed.id, parsed.path_in_repo local_path = os.path.abspath(plan.dest)
# Ensure local directory exists os.makedirs(local_path, exist_ok=True)
# Collect download operations download_files: list[tuple[str | BucketFile, str | Path]] = [] delete_files: list[str] = []
for op in plan.operations: if op.action == "download": local_file = os.path.join(local_path, op.path) # Ensure parent directory exists os.makedirs(os.path.dirname(local_file), exist_ok=True) if verbose: print(f" Downloading: {op.path} ({op.reason})") # Use BucketFile when available (avoids extra metadata fetch per file) if op.bucket_file is not None: download_files.append((op.bucket_file, local_file)) else: remote_path = f"{prefix}/{op.path}" if prefix else op.path download_files.append((remote_path, local_file)) elif op.action == "delete": local_file = os.path.join(local_path, op.path) if verbose: print(f" Deleting: {op.path} ({op.reason})") delete_files.append(local_file) elif op.action == "skip" and verbose: print(f" Skipping: {op.path} ({op.reason})")
# Execute downloads if len(download_files) > 0: if status: status.done(f"Downloading {len(download_files)} files") api.download_bucket_files(bucket_id, download_files)
# Execute deletes if status and delete_files: status.done(f"Deleting {len(delete_files)} local files") for file_path in delete_files: if os.path.exists(file_path): os.remove(file_path) # Remove empty parent directories parent = os.path.dirname(file_path) while parent != local_path: try: os.rmdir(parent) parent = os.path.dirname(parent) except OSError: break
def _print_plan_summary(plan: SyncPlan) -> None: """Print a summary of the sync plan.""" summary = plan.summary() print(f"Sync plan: {plan.source} -> {plan.dest}") print(f" Uploads: {summary['uploads']}") print(f" Downloads: {summary['downloads']}") print(f" Deletes: {summary['deletes']}") print(f" Skips: {summary['skips']}")
# =============================================================================# Public sync function (Python API)# =============================================================================
def sync_bucket_internal( source: str | None = None, dest: str | None = None, *, api: "HfApi", delete: bool = False, ignore_times: bool = False, ignore_sizes: bool = False, existing: bool = False, ignore_existing: bool = False, include: list[str] | None = None, exclude: list[str] | None = None, filter_from: str | None = None, plan: str | None = None, apply: str | None = None, dry_run: bool = False, verbose: bool = False, quiet: bool = False, token: bool | str | None = None,) -> SyncPlan: """Sync files between a local directory and a bucket.
This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path (``hf://buckets/...``) and the other must be a local directory path.
Args: source (`str`, *optional*): Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. Required unless using ``apply``. dest (`str`, *optional*): Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. Required unless using ``apply``. api ([`HfApi`]): The HfApi instance to use for API calls. delete (`bool`, *optional*, defaults to `False`): Delete destination files not present in source. ignore_times (`bool`, *optional*, defaults to `False`): Skip files only based on size, ignoring modification times. ignore_sizes (`bool`, *optional*, defaults to `False`): Skip files only based on modification times, ignoring sizes. existing (`bool`, *optional*, defaults to `False`): Skip creating new files on receiver (only update existing files). ignore_existing (`bool`, *optional*, defaults to `False`): Skip updating files that exist on receiver (only create new files). include (`list[str]`, *optional*): Include files matching patterns (fnmatch-style). exclude (`list[str]`, *optional*): Exclude files matching patterns (fnmatch-style). filter_from (`str`, *optional*): Path to a filter file with include/exclude rules. plan (`str`, *optional*): Save sync plan to this JSONL file instead of executing. apply (`str`, *optional*): Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed. dry_run (`bool`, *optional*, defaults to `False`): Print sync plan to stdout as JSONL without executing. verbose (`bool`, *optional*, defaults to `False`): Show detailed per-file operations. quiet (`bool`, *optional*, defaults to `False`): Suppress all output and progress bars. token (Union[bool, str, None], optional): A valid user access token. If not provided, the locally saved token will be used.
Returns: [`SyncPlan`]: The computed (or loaded) sync plan.
Raises: `ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).
Example: ```python >>> from huggingface_hub import HfApi >>> api = HfApi()
# Upload local directory to bucket >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
# Download bucket to local directory >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
# Sync with delete and filtering >>> api.sync_bucket( ... "./data", ... "hf://buckets/username/my-bucket", ... delete=True, ... include=["*.safetensors"], ... )
# Dry run: preview what would be synced >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True) >>> plan.summary() {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
# Save plan for review, then apply >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl") >>> api.sync_bucket(apply="sync-plan.jsonl") ``` """ # Build API with token if needed if token is not None: from .hf_api import HfApi
api = HfApi( endpoint=api.endpoint, token=token, library_name=api.library_name, library_version=api.library_version, user_agent=api.user_agent, headers=api.headers, ) # --- Apply mode --- if apply: if source or dest: raise ValueError("Cannot specify source/dest when using apply.") if plan is not None: raise ValueError("Cannot specify both plan and apply.") if delete: raise ValueError("Cannot specify delete when using apply.") if ignore_times: raise ValueError("Cannot specify ignore_times when using apply.") if ignore_sizes: raise ValueError("Cannot specify ignore_sizes when using apply.") if include: raise ValueError("Cannot specify include when using apply.") if exclude: raise ValueError("Cannot specify exclude when using apply.") if filter_from: raise ValueError("Cannot specify filter_from when using apply.") if existing: raise ValueError("Cannot specify existing when using apply.") if ignore_existing: raise ValueError("Cannot specify ignore_existing when using apply.") if dry_run: raise ValueError("Cannot specify dry_run when using apply.")
sync_plan = _load_plan(apply) status = StatusLine(enabled=not quiet) if not quiet: _print_plan_summary(sync_plan) print("Executing plan...")
if quiet: disable_progress_bars() try: _execute_plan(sync_plan, api, verbose=verbose, status=status) finally: if quiet: enable_progress_bars()
if not quiet: print("Sync completed.")
return sync_plan
# --- Normal mode --- if not source or not dest: raise ValueError("Both source and dest are required (unless using apply).")
source_is_bucket = _is_bucket_path(source) dest_is_bucket = _is_bucket_path(dest)
if source_is_bucket and dest_is_bucket: raise ValueError("Remote to remote sync is not supported. One path must be local.")
if not source_is_bucket and not dest_is_bucket: raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).")
if ignore_times and ignore_sizes: raise ValueError("Cannot specify both ignore_times and ignore_sizes.")
if existing and ignore_existing: raise ValueError("Cannot specify both existing and ignore_existing.")
if dry_run and plan: raise ValueError("Cannot specify both dry_run and plan.")
# Validate local path if source_is_bucket: if os.path.exists(dest) and not os.path.isdir(dest): raise ValueError(f"Destination must be a directory: {dest}") else: if not os.path.isdir(source): raise ValueError(f"Source must be an existing directory: {source}")
# Build filter matcher filter_rules = None if filter_from: filter_rules = _parse_filter_file(filter_from)
filter_matcher = FilterMatcher( include_patterns=include, exclude_patterns=exclude, filter_rules=filter_rules, )
# Compute sync plan status = StatusLine(enabled=not quiet and not dry_run) sync_plan = _compute_sync_plan( source=source, dest=dest, api=api, delete=delete, ignore_times=ignore_times, ignore_sizes=ignore_sizes, existing=existing, ignore_existing=ignore_existing, filter_matcher=filter_matcher, status=status, )
if dry_run: _write_plan(sync_plan, sys.stdout) return sync_plan
if plan: _save_plan(sync_plan, plan) if not quiet: _print_plan_summary(sync_plan) print(f"Plan saved to: {plan}") return sync_plan
# Execute plan if not quiet: _print_plan_summary(sync_plan)
summary = sync_plan.summary() if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0: if not quiet: print("Nothing to sync.") return sync_plan
if not quiet: print("Syncing...")
if quiet: disable_progress_bars() try: _execute_plan(sync_plan, api, verbose=verbose, status=status) finally: if quiet: enable_progress_bars()
if not quiet: print("Sync completed.")
return sync_plan1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075"""Type definitions and utilities for the `create_commit` API"""
import base64import ioimport jsonimport osimport warningsfrom collections import defaultdictfrom collections.abc import Iterable, Iteratorfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import contextmanagerfrom dataclasses import dataclass, fieldfrom itertools import groupbyfrom pathlib import Path, PurePosixPathfrom typing import TYPE_CHECKING, Any, BinaryIO, Literal, NamedTuple, Union
from tqdm.contrib.concurrent import thread_map
from . import constantsfrom .errors import EntryNotFoundErrorfrom .file_download import hf_hub_urlfrom .lfs import UploadInfo, lfs_upload, post_lfs_batch_infofrom .utils import ( FORBIDDEN_FOLDERS, are_progress_bars_disabled, chunk_iterable, get_session, hf_raise_for_status, http_backoff, logging, sha, tqdm_stream_file, validate_hf_hub_args,)from .utils import tqdm as hf_tqdmfrom .utils._runtime import is_xet_available
if TYPE_CHECKING: from .hf_api import CommitInfo, RepoFile
logger = logging.get_logger(__name__)
UploadMode = Literal["lfs", "regular"]
# Max is 1,000 per request on the Hub for HfApi.get_paths_info# Otherwise we get:# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters# See https://github.com/huggingface/huggingface_hub/issues/1503FETCH_LFS_BATCH_SIZE = 500DUPLICATE_LFS_BATCH_SIZE = 500
UPLOAD_BATCH_MAX_NUM_FILES = 256
@dataclassclass CommitOperationDelete: """ Data structure holding necessary info to delete a file or a folder from a repository on the Hub.
Args: path_in_repo (`str`): Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` for a file or `"checkpoints/1fec34a/"` for a folder. is_folder (`bool` or `Literal["auto"]`, *optional*) Whether the Delete Operation applies to a folder or not. If "auto", the path type (file or folder) is guessed automatically by looking if path ends with a "/" (folder) or not (file). To explicitly set the path type, you can set `is_folder=True` or `is_folder=False`. """
path_in_repo: str is_folder: bool | Literal["auto"] = "auto"
def __post_init__(self): self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
if self.is_folder == "auto": self.is_folder = self.path_in_repo.endswith("/") if not isinstance(self.is_folder, bool): raise ValueError( f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'." )
@dataclassclass CommitOperationCopy: """ Data structure holding necessary info to copy a file in a repository on the Hub.
Both LFS files and regular files are supported. LFS files are copied server-side while regular files are downloaded and re-uploaded as part of the commit.
Cross-repository copies are supported by setting `src_repo_id` and `src_repo_type`. For cross-repo LFS copies, the LFS objects are duplicated to the destination repository before the commit is created. This is handled automatically by [`create_commit`]. Note that cross-repository copies only work within the same [storage region](https://huggingface.co/docs/hub/storage-regions); copying across regions is not supported.
Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
Args: src_path_in_repo (`str`): Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`. path_in_repo (`str`): Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`. src_revision (`str`, *optional*): The git revision of the file to be copied. Can be any valid git revision. Default to the target commit revision. src_repo_id (`str`, *optional*): The source repository to copy from (e.g. `"username/source-model"`). Default to the destination repository (intra-repo copy). src_repo_type (`str`, *optional*): The type of the source repository (`"model"`, `"dataset"` or `"space"`). Required when `src_repo_id` is set. """
src_path_in_repo: str path_in_repo: str src_revision: str | None = None src_repo_id: str | None = None src_repo_type: str | None = None # set to the OID of the file to be copied if it has already been uploaded # useful to determine if a commit will be empty or not. _src_oid: str | None = None # set to the OID of the file to copy to if it has already been uploaded # useful to determine if a commit will be empty or not. _dest_oid: str | None = None # set to True once cross-repo LFS files have been duplicated to the destination repo _is_duplicated: bool = False
def __post_init__(self): self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo) self.path_in_repo = _validate_path_in_repo(self.path_in_repo) if self.src_repo_id is not None and self.src_repo_type is None: raise ValueError("`src_repo_type` is required when `src_repo_id` is set.") if self.src_repo_type is not None and self.src_repo_id is None: raise ValueError("`src_repo_id` is required when `src_repo_type` is set.")
@dataclassclass CommitOperationAdd: """ Data structure holding necessary info to upload a file to a repository on the Hub.
Args: path_in_repo (`str`): Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`): Either: - a path to a local file (as `str` or `pathlib.Path`) to upload - a buffer of bytes (`bytes`) holding the content of the file to upload - a "file object" (subclass of `io.BufferedIOBase`), typically obtained with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
Raises: [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both `seek()` and `tell()`. """
path_in_repo: str path_or_fileobj: str | Path | bytes | BinaryIO upload_info: UploadInfo = field(init=False, repr=False)
# Internal attributes
# set to "lfs" or "regular" once known _upload_mode: UploadMode | None = field(init=False, repr=False, default=None)
# set to True if .gitignore rules prevent the file from being uploaded as LFS # (server-side check) _should_ignore: bool | None = field(init=False, repr=False, default=None)
# set to the remote OID of the file if it has already been uploaded # useful to determine if a commit will be empty or not _remote_oid: str | None = field(init=False, repr=False, default=None)
# set to True once the file has been uploaded as LFS _is_uploaded: bool = field(init=False, repr=False, default=False)
# set to True once the file has been committed _is_committed: bool = field(init=False, repr=False, default=False)
def __post_init__(self) -> None: """Validates `path_or_fileobj` and compute `upload_info`.""" self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
# Validate `path_or_fileobj` value if isinstance(self.path_or_fileobj, Path): self.path_or_fileobj = str(self.path_or_fileobj) if isinstance(self.path_or_fileobj, str): path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj)) if not os.path.isfile(path_or_fileobj): raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system") elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)): # ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode raise ValueError( "path_or_fileobj must be either an instance of str, bytes or" " io.BufferedIOBase. If you passed a file-like object, make sure it is" " in binary mode." ) if isinstance(self.path_or_fileobj, io.BufferedIOBase): try: self.path_or_fileobj.tell() self.path_or_fileobj.seek(0, os.SEEK_CUR) except (OSError, AttributeError) as exc: raise ValueError( "path_or_fileobj is a file-like object but does not implement seek() and tell()" ) from exc
# Compute "upload_info" attribute if isinstance(self.path_or_fileobj, str): self.upload_info = UploadInfo.from_path(self.path_or_fileobj) elif isinstance(self.path_or_fileobj, bytes): self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj) else: self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
@contextmanager def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]: """ A context manager that yields a file-like object allowing to read the underlying data behind `path_or_fileobj`.
Args: with_tqdm (`bool`, *optional*, defaults to `False`): If True, iterating over the file object will display a progress bar. Only works if the file-like object is a path to a file. Pure bytes and buffers are not supported.
Example:
```python >>> operation = CommitOperationAdd( ... path_in_repo="remote/dir/weights.h5", ... path_or_fileobj="./local/weights.h5", ... ) CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
>>> with operation.as_file() as file: ... content = file.read()
>>> with operation.as_file(with_tqdm=True) as file: ... while True: ... data = file.read(1024) ... if not data: ... break config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
>>> with operation.as_file(with_tqdm=True) as file: ... httpx.put(..., data=file) config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] ``` """ if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path): if with_tqdm: with tqdm_stream_file(self.path_or_fileobj) as file: yield file else: with open(self.path_or_fileobj, "rb") as file: yield file elif isinstance(self.path_or_fileobj, bytes): yield io.BytesIO(self.path_or_fileobj) elif isinstance(self.path_or_fileobj, io.BufferedIOBase): prev_pos = self.path_or_fileobj.tell() yield self.path_or_fileobj self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
def b64content(self) -> bytes: """ The base64-encoded content of `path_or_fileobj`
Returns: `bytes` """ with self.as_file() as file: return base64.b64encode(file.read())
@property def _local_oid(self) -> str | None: """Return the OID of the local file.
This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one. If the file did not change, we won't upload it again to prevent empty commits.
For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref). For regular files, the OID corresponds to the SHA1 of the file content. Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes and more convenient client-side. """ if self._upload_mode is None: return None elif self._upload_mode == "lfs": return self.upload_info.sha256.hex() else: # Regular file => compute sha1 # => no need to read by chunk since the file is guaranteed to be <=5MB. with self.as_file() as file: return sha.git_hash(file.read())
def _validate_path_in_repo(path_in_repo: str) -> str: # Validate `path_in_repo` value to prevent a server-side issue if path_in_repo.startswith("/"): path_in_repo = path_in_repo[1:] if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"): raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'") if path_in_repo.startswith("./"): path_in_repo = path_in_repo[2:] for forbidden in FORBIDDEN_FOLDERS: if any(part == forbidden for part in path_in_repo.split("/")): raise ValueError( f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:" f" '{path_in_repo}')." ) return path_in_repo
CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None: """ Warn user when a list of operations is expected to overwrite itself in a single commit.
Rules: - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning message is triggered. - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted by a `CommitOperationDelete`, a warning is triggered. - If a `CommitOperationDelete` deletes a filepath that is then updated by a `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to delete before upload) but can happen if a user deletes an entire folder and then add new files to it. """ nb_additions_per_path: dict[str, int] = defaultdict(int) for operation in operations: path_in_repo = operation.path_in_repo if isinstance(operation, CommitOperationAdd): if nb_additions_per_path[path_in_repo] > 0: warnings.warn( "About to update multiple times the same file in the same commit:" f" '{path_in_repo}'. This can cause undesired inconsistencies in" " your repo." ) nb_additions_per_path[path_in_repo] += 1 for parent in PurePosixPath(path_in_repo).parents: # Also keep track of number of updated files per folder # => warns if deleting a folder overwrite some contained files nb_additions_per_path[str(parent)] += 1 if isinstance(operation, CommitOperationDelete): if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0: if operation.is_folder: warnings.warn( "About to delete a folder containing files that have just been" f" updated within the same commit: '{path_in_repo}'. This can" " cause undesired inconsistencies in your repo." ) else: warnings.warn( "About to delete a file that have just been updated within the" f" same commit: '{path_in_repo}'. This can cause undesired" " inconsistencies in your repo." )
@validate_hf_hub_argsdef _upload_files( *, additions: list[CommitOperationAdd], repo_type: str, repo_id: str, headers: dict[str, str], endpoint: str | None = None, num_threads: int = 5, revision: str | None = None, create_pr: bool | None = None,): """ Uploads the files through the Xet protocol if possible, otherwise through the legacy LFS protocol.
The Xet path does not require any Python-side sha256 computation: hashing happens inside `hf_xet` while chunking the files (single read pass) and is backfilled on the operations afterwards. """ has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in additions) if is_xet_available(): if not has_buffered_io_data: _upload_xet_files( additions=additions, repo_type=repo_type, repo_id=repo_id, headers=headers, endpoint=endpoint, revision=revision, create_pr=create_pr, ) return logger.warning( "Uploading files as a binary IO buffer is not supported by Xet Storage. Falling back to HTTP upload." )
# Legacy LFS path: sha256 is required by the LFS batch endpoint => compute missing ones (in parallel). _compute_missing_sha256s(additions, num_threads=num_threads)
lfs_actions: list[dict[str, Any]] = [] lfs_oid2addop: dict[str, CommitOperationAdd] = {} for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES): chunk_list = [op for op in chunk] actions_chunk, errors_chunk, _ = post_lfs_batch_info( upload_infos=[op.upload_info for op in chunk_list], repo_id=repo_id, repo_type=repo_type, revision=revision, endpoint=endpoint, headers=headers, token=None, # already passed in 'headers' transfers=["basic", "multipart"], ) if errors_chunk: message = "\n".join( [ f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}" for err in errors_chunk ] ) raise ValueError(f"LFS batch API returned errors:\n{message}") lfs_actions.extend(actions_chunk) for op in chunk_list: lfs_oid2addop[op.upload_info.sha256.hex()] = op
if len(lfs_actions) > 0: _upload_lfs_files( actions=lfs_actions, oid2addop=lfs_oid2addop, headers=headers, endpoint=endpoint, num_threads=num_threads, )
def _compute_missing_sha256s(additions: list[CommitOperationAdd], num_threads: int) -> None: """Compute the sha256 of the operations that don't have one yet, in parallel.""" not_hashed = [op for op in additions if not op.upload_info.is_hashed] if len(not_hashed) == 0: return logger.info(f"Computing sha256 for {len(not_hashed)} files.") if len(not_hashed) == 1: _ = not_hashed[0].upload_info.sha256 return with ThreadPoolExecutor(max_workers=num_threads) as executor: list(executor.map(lambda op: op.upload_info.sha256, not_hashed))
@validate_hf_hub_argsdef _upload_lfs_files( *, actions: list[dict[str, Any]], oid2addop: dict[str, CommitOperationAdd], headers: dict[str, str], endpoint: str | None = None, num_threads: int = 5,): """ Uploads the content of `additions` to the Hub using the large file storage protocol.
Relevant external documentation: - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
Args: actions (`list[dict[str, Any]]`): LFS batch actions returned by the server. oid2addop (`dict[str, CommitOperationAdd]`): A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. endpoint (`str`, *optional*): The endpoint to use for the request. Defaults to `constants.ENDPOINT`. num_threads (`int`, *optional*): The number of concurrent threads to use when uploading. Defaults to 5.
Raises: [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If an upload failed for any reason [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. num_threads (`int`, *optional*): The number of concurrent threads to use when uploading. Defaults to 5. revision (`str`, *optional*): The git revision to upload to.
Raises: [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If an upload failed for any reason [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the server returns malformed responses [`HfHubHTTPError`] If the LFS batch endpoint returned an HTTP error. """ # Filter out files already present upstream filtered_actions = [] for action in actions: if action.get("actions") is None: logger.debug( f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload." ) else: filtered_actions.append(action)
# Upload according to server-provided actions def _wrapped_lfs_upload(batch_action) -> None: try: operation = oid2addop[batch_action["oid"]] lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint) except Exception as exc: raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
if len(filtered_actions) == 1: logger.debug("Uploading 1 LFS file to the Hub") _wrapped_lfs_upload(filtered_actions[0]) else: logger.debug( f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently" ) thread_map( _wrapped_lfs_upload, filtered_actions, desc=f"Upload {len(filtered_actions)} LFS files", max_workers=num_threads, tqdm_class=hf_tqdm, )
@validate_hf_hub_argsdef _upload_xet_files( *, additions: list[CommitOperationAdd], repo_type: str, repo_id: str, headers: dict[str, str], endpoint: str | None = None, revision: str | None = None, create_pr: bool | None = None,): """ Uploads the content of `additions` to the Hub using the xet storage protocol. This chunks the files and deduplicates the chunks before uploading them to xetcas storage.
Args: additions (`` of `CommitOperationAdd`): The files to be uploaded. repo_type (`str`): Type of the repo (e.g. `"model"`, `"dataset"`, `"space"`). repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. endpoint: (`str`, *optional*): The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`. revision (`str`, *optional*): The git revision to upload to. create_pr (`bool`, *optional*): Whether or not to create a Pull Request with that commit.
Raises: [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) If an upload failed for any reason. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the server returns malformed responses or if the user is unauthorized to upload to xet storage. [`HfHubHTTPError`] If the LFS batch endpoint returned an HTTP error.
**How it works:** The file upload system uses Xet storage, which is a content-addressable storage system that breaks files into chunks for efficient storage and transfer.
``session.new_upload_commit()`` manages uploading files by: - Registering upload tasks and starting upload immediately in the background - Breaking files into smaller chunks for efficient storage - Avoiding duplicate storage by recognizing identical chunks across files - Connecting to a storage server (CAS server) that manages these chunks
Authentication works transparently: the upload commit accepts a ``token_refresh_url`` that is used to refresh the short-lived xet write token as needed.
The upload process works like this: 1. Upload tasks run in parallel: 1.1. Read the file content from a path, bytes array, or a stream. 1.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it. 1.3. For each chunk: - Check if it already exists in storage. - Skip uploading chunks that already exist. 1.4. Group chunks into larger blocks for efficient transfer. 1.5. Upload these blocks to the storage server. 1.6. Assemble the file manifest locally and send it to the server for validation. 2. Return reference files that contain information about the uploaded files, which can be used later to download them. """ if len(additions) == 0: return
# at this point, we know that hf_xet is installed from .utils._xet import ( XetTokenType, abort_xet_session, get_xet_session, xet_connection_info_refresh_url, xet_headers_without_auth, ) from .utils._xet_progress_reporting import XetUploadProgressReporter
refresh_url = xet_connection_info_refresh_url( token_type=XetTokenType.WRITE, repo_id=repo_id, repo_type=repo_type, revision=revision, endpoint=endpoint, ) if create_pr: refresh_url += "?create_pr=1"
xet_headers = xet_headers_without_auth(headers)
import hf_xet
session = get_xet_session() progress = None
def _sha256_arg(op: CommitOperationAdd): # If the sha256 is already known, pass it to avoid recomputation. Otherwise let hf_xet # compute it while chunking the file (single read pass) and backfill it afterwards. return op.upload_info.sha256.hex() if op.upload_info.is_hashed else hf_xet.COMPUTE_SHA256
try: if not are_progress_bars_disabled(): progress = XetUploadProgressReporter() progress_callback = progress.update_progress else: progress_callback = None
all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)] all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))]
handles: list[tuple[CommitOperationAdd, Any]] = [] with session.new_upload_commit( token_refresh_url=refresh_url, token_refresh_headers=headers, custom_headers=xet_headers, progress_callback=progress_callback, ) as commit: for op in all_paths_ops: handles.append((op, commit.start_upload_file(str(op.path_or_fileobj), sha256=_sha256_arg(op)))) for op in all_bytes_ops: handles.append((op, commit.start_upload_bytes(op.path_or_fileobj, sha256=_sha256_arg(op))))
# Backfill sha256 computed by hf_xet (needed later for the commit payload). for op, handle in handles: if not op.upload_info.is_hashed: op.upload_info.sha256 = bytes.fromhex(handle.result().xet_info.sha256) except KeyboardInterrupt: abort_xet_session() raise finally: if progress is not None: progress.close()
def _validate_preupload_info(preupload_info: dict): files = preupload_info.get("files") if not isinstance(files, list): raise ValueError("preupload_info is improperly formatted") for file_info in files: if not ( isinstance(file_info, dict) and isinstance(file_info.get("path"), str) and isinstance(file_info.get("uploadMode"), str) and (file_info["uploadMode"] in ("lfs", "regular")) ): raise ValueError("preupload_info is improperly formatted:") return preupload_info
@validate_hf_hub_argsdef _fetch_upload_modes( additions: Iterable[CommitOperationAdd], repo_type: str, repo_id: str, headers: dict[str, str], revision: str, endpoint: str | None = None, create_pr: bool = False, gitignore_content: str | None = None,) -> None: """ Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob, as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode.
Args: additions (`Iterable` of :class:`CommitOperationAdd`): Iterable of :class:`CommitOperationAdd` describing the files to upload to the Hub. repo_type (`str`): Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. revision (`str`): The git revision to upload the files to. Can be any valid git revision. 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). Raises: [`~utils.HfHubHTTPError`] If the Hub API returned an error. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the Hub API response is improperly formatted. """ endpoint = endpoint if endpoint is not None else constants.ENDPOINT
# Fetch upload mode (LFS or regular) chunk by chunk. upload_modes: dict[str, UploadMode] = {} should_ignore_info: dict[str, bool] = {} oid_info: dict[str, str | None] = {}
for chunk in chunk_iterable(additions, 256): payload: dict = { "files": [ { "path": op.path_in_repo, "sample": base64.b64encode(op.upload_info.sample).decode("ascii"), "size": op.upload_info.size, } for op in chunk ] } if gitignore_content is not None: payload["gitIgnore"] = gitignore_content
resp = http_backoff( "POST", f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}", json=payload, headers=headers, params={"create_pr": "1"} if create_pr else None, ) hf_raise_for_status(resp) preupload_info = _validate_preupload_info(resp.json()) upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]}) should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]}) oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]})
# Set upload mode for each addition operation for addition in additions: addition._upload_mode = upload_modes[addition.path_in_repo] addition._should_ignore = should_ignore_info[addition.path_in_repo] addition._remote_oid = oid_info[addition.path_in_repo]
# Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented) # => empty files are uploaded as "regular" to still allow users to commit them. for addition in additions: if addition.upload_info.size == 0: addition._upload_mode = "regular"
class _CopySource(NamedTuple): src_repo_id: str | None src_repo_type: str | None path: str revision: str | None
@validate_hf_hub_argsdef _fetch_files_to_copy( copies: Iterable[CommitOperationCopy], repo_type: str, repo_id: str, headers: dict[str, str], revision: str, endpoint: str | None = None,) -> dict[_CopySource, Union["RepoFile", bytes]]: """ Fetch information about the files to copy.
For LFS files, we only need their metadata (file size and sha256) while for regular files we need to download the raw content from the Hub.
Args: copies (`Iterable` of :class:`CommitOperationCopy`): Iterable of :class:`CommitOperationCopy` describing the files to copy on the Hub. repo_type (`str`): Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. repo_id (`str`): A namespace (user or an organization) and a repo name separated by a `/`. headers (`dict[str, str]`): Headers to use for the request, including authorization headers and user agent. revision (`str`): The git revision to upload the files to. Can be any valid git revision.
Returns: `dict[_CopySource, Union[RepoFile, bytes]]]` Key is `(src_repo_id, src_repo_type, path, revision)`. For intra-repo copies, `src_repo_id` and `src_repo_type` are `None`. Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
Raises: [`~utils.HfHubHTTPError`] If the Hub API returned an error. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) If the Hub API response is improperly formatted. """ from .hf_api import HfApi, RepoFolder
hf_api = HfApi(endpoint=endpoint, headers=headers) copies = list(copies) files_to_copy: dict[_CopySource, Union["RepoFile", bytes]] = {} oid_info: dict[tuple[str, str | None], str | None] = {}
# 1. Fetch OIDs for destination paths in batches. dest_paths = [op.path_in_repo for op in copies] for batch in chunk_iterable(dest_paths, FETCH_LFS_BATCH_SIZE): dest_repo_files = hf_api.get_paths_info( repo_id=repo_id, paths=list(batch), revision=revision, repo_type=repo_type, ) for file in dest_repo_files: if not isinstance(file, RepoFolder): oid_info[(file.path, revision)] = file.blob_id
# 2. Fetch source file info, grouped by (src_repo_id, src_repo_type, src_revision). copies.sort(key=lambda op: (op.src_repo_id or "", op.src_repo_type or "", op.src_revision or "")) for (src_repo_id_key, src_repo_type_key, src_revision_key), group in groupby( copies, key=lambda op: (op.src_repo_id, op.src_repo_type, op.src_revision) ): operations = list(group) is_cross_repo = src_repo_id_key is not None eff_repo_id = src_repo_id_key or repo_id eff_repo_type = src_repo_type_key or repo_type eff_revision = src_revision_key or ("main" if is_cross_repo else revision)
src_paths = [op.src_path_in_repo for op in operations] for paths_batch in chunk_iterable(src_paths, FETCH_LFS_BATCH_SIZE): src_repo_files = hf_api.get_paths_info( repo_id=eff_repo_id, paths=list(paths_batch), revision=eff_revision, repo_type=eff_repo_type, ) for src_repo_file in src_repo_files: if isinstance(src_repo_file, RepoFolder): raise NotImplementedError("Copying a folder is not implemented.") source = _CopySource(src_repo_id_key, src_repo_type_key, src_repo_file.path, src_revision_key) if src_repo_file.lfs: files_to_copy[source] = src_repo_file else: url = hf_hub_url( endpoint=endpoint, repo_type=eff_repo_type, repo_id=eff_repo_id, revision=eff_revision, filename=src_repo_file.path, ) response = get_session().get(url, headers=headers) hf_raise_for_status(response) files_to_copy[source] = response.content if not is_cross_repo: oid_info[(src_repo_file.path, src_revision_key)] = src_repo_file.blob_id
for operation in operations: key = _CopySource(src_repo_id_key, src_repo_type_key, operation.src_path_in_repo, src_revision_key) if key not in files_to_copy: source_desc = f" from {eff_repo_type}s/{eff_repo_id}" if is_cross_repo else "" raise EntryNotFoundError( f"Cannot copy {operation.src_path_in_repo} at revision " f"{eff_revision}{source_desc}: file is missing on repo." ) operation._dest_oid = oid_info.get((operation.path_in_repo, revision)) if not is_cross_repo: operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision))
return files_to_copy
def _prepare_commit_payload( operations: Iterable[CommitOperation], files_to_copy: dict[_CopySource, Union["RepoFile", bytes]], commit_message: str, commit_description: str | None = None, parent_commit: str | None = None,) -> Iterable[dict[str, Any]]: """ Builds the payload to POST to the `/commit` API of the Hub.
Payload is returned as an iterator so that it can be streamed as a ndjson in the POST request.
For more information, see: - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 - http://ndjson.org/ """ commit_description = commit_description if commit_description is not None else ""
# 1. Send a header item with the commit metadata header_value = {"summary": commit_message, "description": commit_description} if parent_commit is not None: header_value["parentCommit"] = parent_commit yield {"key": "header", "value": header_value}
nb_ignored_files = 0
# 2. Send operations, one per line for operation in operations: # Skip ignored files if isinstance(operation, CommitOperationAdd) and operation._should_ignore: logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).") nb_ignored_files += 1 continue
# 2.a. Case adding a regular file if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular": yield { "key": "file", "value": { "content": operation.b64content().decode(), "path": operation.path_in_repo, "encoding": "base64", }, } # 2.b. Case adding an LFS file elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs": yield { "key": "lfsFile", "value": { "path": operation.path_in_repo, "algo": "sha256", "oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size, }, } # 2.c. Case deleting a file or folder elif isinstance(operation, CommitOperationDelete): yield { "key": "deletedFolder" if operation.is_folder else "deletedFile", "value": {"path": operation.path_in_repo}, } # 2.d. Case copying a file or folder elif isinstance(operation, CommitOperationCopy): source = _CopySource( operation.src_repo_id, operation.src_repo_type, operation.src_path_in_repo, operation.src_revision, ) file_to_copy = files_to_copy[source] if isinstance(file_to_copy, bytes): yield { "key": "file", "value": { "content": base64.b64encode(file_to_copy).decode(), "path": operation.path_in_repo, "encoding": "base64", }, } elif file_to_copy.lfs: yield { "key": "lfsFile", "value": { "path": operation.path_in_repo, "algo": "sha256", "oid": file_to_copy.lfs.sha256, }, } else: raise ValueError( "Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info." ) # 2.e. Never expected to happen else: raise ValueError( f"Unknown operation to commit. Operation: {operation}. Upload mode:" f" {getattr(operation, '_upload_mode', None)}" )
if nb_ignored_files > 0: logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
def _send_commit( *, operations: Iterable[CommitOperation], files_to_copy: dict[_CopySource, Union["RepoFile", bytes]], commit_message: str, commit_description: str, repo_type: str, repo_id: str, headers: dict[str, str], revision: str, endpoint: str | None = None, parent_commit: str | None = None, create_pr: bool = False, hot_reload: bool = False, retry_on_error: bool = False,) -> "CommitInfo": """ Build the ndjson payload for `operations` and POST it to the `/commit` endpoint of the Hub.
`revision` must already be URL-quoted. Operations must be ready to commit: upload modes fetched and LFS/Xet content uploaded.
If `retry_on_error` is `True`, the POST is retried with exponential backoff on transient errors. Caution: if a commit succeeds but its response is lost, the retry will create a duplicate commit (and a duplicate pull request if `create_pr` is set) — only enable it when this is acceptable.
Returns a [`CommitInfo`] built from the server response.
Raises: [`~utils.HfHubHTTPError`] If the Hub API returned an error. """ endpoint = endpoint if endpoint is not None else constants.ENDPOINT payload = _prepare_commit_payload( operations=operations, files_to_copy=files_to_copy, commit_message=commit_message, commit_description=commit_description, parent_commit=parent_commit, ) data = b"".join(json.dumps(item).encode() + b"\n" for item in payload) # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 headers = {"Content-Type": "application/x-ndjson", **headers} url = f"{endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
params: dict[str, str] = {} if create_pr: params["create_pr"] = "1" if hot_reload: params["hot_reload"] = "1"
if retry_on_error: response = http_backoff("POST", url, headers=headers, content=data, params=params) else: response = get_session().post(url, headers=headers, content=data, params=params) hf_raise_for_status(response, endpoint_name="commit")
commit_data = response.json() from .hf_api import CommitInfo
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, _endpoint=endpoint, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353import atexitimport loggingimport osimport timefrom concurrent.futures import Futurefrom dataclasses import dataclassfrom io import SEEK_END, SEEK_SET, BytesIOfrom pathlib import Pathfrom threading import Lock, Threadfrom typing import Optional
from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApifrom .utils import filter_repo_objects
logger = logging.getLogger(__name__)
@dataclass(frozen=True)class _FileToUpload: """Temporary dataclass to store info about files to upload. Not meant to be used directly."""
local_path: Path path_in_repo: str size_limit: int last_modified: float
class CommitScheduler: """ Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads) to learn more about how to use it.
Args: repo_id (`str`): The id of the repo to commit to. folder_path (`str` or `Path`): Path to the local folder to upload regularly. every (`int` or `float`, *optional*): The number of minutes between each commit. Defaults to 5 minutes. path_in_repo (`str`, *optional*): Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder of the repository. repo_type (`str`, *optional*): The type of the repo to commit to. Defaults to `model`. revision (`str`, *optional*): The revision of the repo to commit to. Defaults to `main`. private (`bool`, *optional*): Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. token (`str`, *optional*): The token to use to commit to the repo. Defaults to the token saved on the machine. 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. squash_history (`bool`, *optional*): Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is useful to avoid degraded performances on the repo when it grows too large. hf_api (`HfApi`, *optional*): The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
Example: ```py >>> from pathlib import Path >>> from huggingface_hub import CommitScheduler
# Scheduler uploads every 10 minutes >>> csv_path = Path("watched_folder/data.csv") >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
>>> with csv_path.open("a") as f: ... f.write("first line")
# Some time later (...) >>> with csv_path.open("a") as f: ... f.write("second line") ```
Example using a context manager: ```py >>> from pathlib import Path >>> from huggingface_hub import CommitScheduler
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler: ... csv_path = Path("watched_folder/data.csv") ... with csv_path.open("a") as f: ... f.write("first line") ... (...) ... with csv_path.open("a") as f: ... f.write("second line")
# Scheduler is now stopped and last commit have been triggered ``` """
def __init__( self, *, repo_id: str, folder_path: str | Path, every: int | float = 5, path_in_repo: str | None = None, repo_type: str | None = None, revision: str | None = None, private: bool | None = None, token: str | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, squash_history: bool = False, hf_api: Optional["HfApi"] = None, ) -> None: self.api = hf_api or HfApi(token=token)
# Folder self.folder_path = Path(folder_path).expanduser().resolve() self.path_in_repo = path_in_repo or "" self.allow_patterns = allow_patterns
if ignore_patterns is None: ignore_patterns = [] elif isinstance(ignore_patterns, str): ignore_patterns = [ignore_patterns] self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
if self.folder_path.is_file(): raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.") self.folder_path.mkdir(parents=True, exist_ok=True)
# Repository repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True) self.repo_id = repo_url.repo_id self.repo_type = repo_type self.revision = revision self.token = token
# Keep track of already uploaded files self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp
# Scheduler if not every > 0: raise ValueError(f"'every' must be a positive integer, not '{every}'.") self.lock = Lock() self.every = every self.squash_history = squash_history
logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.") self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True) self._scheduler_thread.start() atexit.register(self._push_to_hub)
self.__stopped = False
def stop(self) -> None: """Stop the scheduler.
A stopped scheduler cannot be restarted. Mostly for tests purposes. """ self.__stopped = True
def __enter__(self) -> "CommitScheduler": return self
def __exit__(self, exc_type, exc_value, traceback) -> None: # Upload last changes before exiting self.trigger().result() self.stop() return
def _run_scheduler(self) -> None: """Dumb thread waiting between each scheduled push to Hub.""" while True: self.last_future = self.trigger() time.sleep(self.every * 60) if self.__stopped: break
def trigger(self) -> Future: """Trigger a `push_to_hub` and return a future.
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit immediately, without waiting for the next scheduled commit. """ return self.api.run_as_future(self._push_to_hub)
def _push_to_hub(self) -> CommitInfo | None: if self.__stopped: # If stopped, already scheduled commits are ignored return None
logger.info("(Background) scheduled commit triggered.") try: value = self.push_to_hub() if self.squash_history: logger.info("(Background) squashing repo history.") self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision) return value except Exception as e: logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced raise
def push_to_hub(self) -> CommitInfo | None: """ Push folder to the Hub and return the commit info.
> [!WARNING] > This method is not meant to be called directly. It is run in the background by the scheduler, respecting a > queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency > issues.
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and uploads only changed files. If no changes are found, the method returns without committing anything. If you want to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful for example to compress data together in a single file before committing. For more details and examples, check out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads). """ # Check files to upload (with lock) with self.lock: logger.debug("Listing files to upload for scheduled commit.")
# List files from folder (taken from `_prepare_upload_folder_additions`) relpath_to_abspath = { path.relative_to(self.folder_path).as_posix(): path for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic if path.is_file() } prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
# Filter with pattern + filter out unchanged files + retrieve current file size files_to_upload: list[_FileToUpload] = [] for relpath in filter_repo_objects( relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns ): local_path = relpath_to_abspath[relpath] stat = local_path.stat() if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime: files_to_upload.append( _FileToUpload( local_path=local_path, path_in_repo=prefix + relpath, size_limit=stat.st_size, last_modified=stat.st_mtime, ) )
# Return if nothing to upload if len(files_to_upload) == 0: logger.debug("Dropping schedule commit: no changed file to upload.") return None
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size) logger.debug("Removing unchanged files since previous scheduled commit.") add_operations = [ CommitOperationAdd( # Cap the file to its current size, even if the user append data to it while a scheduled commit is happening path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit), path_in_repo=file_to_upload.path_in_repo, ) for file_to_upload in files_to_upload ]
# Upload files (append mode expected - no need for lock) logger.debug("Uploading files for scheduled commit.") commit_info = self.api.create_commit( repo_id=self.repo_id, repo_type=self.repo_type, operations=add_operations, commit_message="Scheduled Commit", revision=self.revision, )
# Successful commit: keep track of the latest "last_modified" for each file for file in files_to_upload: self.last_uploaded[file.local_path] = file.last_modified return commit_info
class PartialFileIO(BytesIO): """A file-like object that reads only the first part of a file.
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the file is uploaded (i.e. the part that was available when the filesystem was first scanned).
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal disturbance for the user. The object is passed to `CommitOperationAdd`.
Only supports `read`, `tell` and `seek` methods.
Args: file_path (`str` or `Path`): Path to the file to read. size_limit (`int`): The maximum number of bytes to read from the file. If the file is larger than this, only the first part will be read (and uploaded). """
def __init__(self, file_path: str | Path, size_limit: int) -> None: self._file_path = Path(file_path) self._file = self._file_path.open("rb") self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
def __del__(self) -> None: self._file.close() return super().__del__()
def __repr__(self) -> str: return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
def __len__(self) -> int: return self._size_limit
def __getattribute__(self, name: str): if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported return super().__getattribute__(name) raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
def fileno(self): raise AttributeError("PartialFileIO does not have a fileno.")
def tell(self) -> int: """Return the current file position.""" return self._file.tell()
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int: """Change the stream position to the given offset.
Behavior is the same as a regular file, except that the position is capped to the size limit. """ if __whence == SEEK_END: # SEEK_END => set from the truncated end __offset = len(self) + __offset __whence = SEEK_SET
pos = self._file.seek(__offset, __whence) if pos > self._size_limit: return self._file.seek(self._size_limit) return pos
def read(self, __size: int | None = -1) -> bytes: """Read at most `__size` bytes from the file.
Behavior is the same as a regular file, except that it is capped to the size limit. """ current = self._file.tell() if __size is None or __size < 0: # Read until file limit truncated_size = self._size_limit - current else: # Read until file limit or __size truncated_size = min(__size, self._size_limit - current) return self._file.read(truncated_size)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172# Copyright 2026 The HuggingFace Team. All rights reserved.## 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.import jsonimport osimport shutilimport subprocessfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Union
from . import constantsfrom .utils import get_token
if TYPE_CHECKING: import duckdb
@dataclass(frozen=True)class DatasetParquetEntry: """Represents a single parquet file available for a dataset on the Hub."""
config: str split: str url: str size: int
def execute_raw_sql_query(sql_query: str, *, token: str | bool | None = None) -> list[dict[str, Any]]: normalized_query = sql_query.strip().rstrip(";").strip() _raise_on_forbidden_query(normalized_query)
connection = None try: connection = _get_duckdb_connection(token=token) relation = connection.sql(normalized_query) if relation is None: raise ValueError("SQL query must return rows.")
if isinstance(relation, _DuckDBCliRelation): # DuckDB binary => run CLI => parse JSON return relation.execute() else: # DuckDB Python API => fetch columns + rows => convert to dicts columns = tuple(column[0] for column in relation.description) rows = tuple(tuple(row) for row in relation.fetchall()) return [dict(zip(columns, row)) for row in rows] finally: if connection is not None: connection.close()
def _raise_on_forbidden_query(query: str) -> None: if len(query) == 0: raise ValueError("SQL query cannot be empty.")
# DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`). # Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line. for line in query.splitlines(): stripped = line.lstrip() if stripped.startswith(".") and stripped[1:2].isalpha(): raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.")
def _get_duckdb_connection( token: str | bool | None,) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]: try: # If DuckDB is installed as a Python package, use it! import duckdb except ImportError as error: # Otherwise, use the DuckDB CLI binary. duckdb_binary = shutil.which("duckdb") if duckdb_binary is None: raise ImportError( "DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or " "install the DuckDB CLI binary (for example `brew install duckdb`)." ) from error return _DuckDBCliConnection(binary_path=duckdb_binary, token=token)
# Create a new connection (Python API). connection = duckdb.connect() try: for statement in _build_duckdb_secret_statements(token): connection.execute(statement) return connection except Exception: connection.close() raise
@dataclassclass _DuckDBCliConnection: """DuckDB connection.
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary. """
binary_path: str token: str | bool | None
def __post_init__(self) -> None: self._setup_statements = _build_duckdb_secret_statements(self.token)
def sql(self, query: str) -> "_DuckDBCliRelation": return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query)
def close(self) -> None: pass
@dataclassclass _DuckDBCliRelation: """DuckDB relation.
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary. """
binary_path: str setup_statements: list[str] query: str
def execute(self) -> list[dict[str, Any]]: # Build the DuckDB CLI input. setup = [] if self.setup_statements: setup = [ f".output {os.devnull}", *(f"{stmt};" for stmt in self.setup_statements), ".output", ] full_query = "\n".join(setup + [self.query + ";"])
# Run DuckDB binary result = subprocess.run( [self.binary_path, "-json"], input=full_query, capture_output=True, text=True, check=False, ) if result.returncode != 0: error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed." raise RuntimeError(error_message)
# Parse JSON output and return return json.loads(result.stdout.strip())
def _build_duckdb_secret_statements(token: str | bool | None) -> list[str]: if token is None or token is True: token = get_token()
if not token: return []
escaped_token = token.replace("'", "''") escaped_endpoint = constants.ENDPOINT.replace("'", "''") return [ f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')", f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')", ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211"""Evaluation results utilities for the `.eval_results/*.yaml` format.
See https://huggingface.co/docs/hub/eval-results for more details.Specifications are available at https://github.com/huggingface/hub-docs/blob/main/eval_results.yaml."""
from dataclasses import dataclassfrom typing import Any
@dataclassclass EvalResultEntry: """ Evaluation result entry for the `.eval_results/*.yaml` format.
Represents evaluation scores stored in model repos that automatically appear on the model page and the benchmark dataset's leaderboard.
For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead.
See https://huggingface.co/docs/hub/eval-results for more details.
Args: dataset_id (`str`): Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa". task_id (`str`): Task identifier within the benchmark. Example: "gpqa_diamond". value (`Any`): The metric value. Example: 20.90. dataset_revision (`str`, *optional*): Git SHA of the benchmark dataset. verify_token (`str`, *optional*): A signature that can be used to prove that evaluation is provably auditable and reproducible. date (`str`, *optional*): When the evaluation was run (ISO-8601 datetime). Defaults to git commit time. source_url (`str`, *optional*): Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided. source_name (`str`, *optional*): Display name for the source. Example: "Eval Logs". source_user (`str`, *optional*): HF user name for attribution. Example: "celinah". source_org (`str`, *optional*): HF org name for attribution. Example: "cais". notes (`str`, *optional*): Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought".
Example: ```python >>> from huggingface_hub import EvalResultEntry >>> # Minimal example with required fields only >>> result = EvalResultEntry( ... dataset_id="Idavidrein/gpqa", ... task_id="gpqa_diamond", ... value=0.412, ... ) >>> # Full example with all fields >>> result = EvalResultEntry( ... dataset_id="cais/hle", ... task_id="default", ... value=20.90, ... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb", ... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", ... date="2025-01-15T10:30:00Z", ... source_url="https://huggingface.co/datasets/cais/hle", ... source_name="CAIS HLE", ... source_org="cais", ... notes="no-tools", ... )
``` """
dataset_id: str task_id: str value: Any dataset_revision: str | None = None verify_token: str | None = None date: str | None = None source_url: str | None = None source_name: str | None = None source_user: str | None = None source_org: str | None = None notes: str | None = None
def __post_init__(self) -> None: if ( self.source_name is not None or self.source_user is not None or self.source_org is not None ) and self.source_url is None: raise ValueError( "If `source_name`, `source_user`, or `source_org` is provided, `source_url` must also be provided." )
def eval_result_entries_to_yaml(entries: list[EvalResultEntry]) -> list[dict[str, Any]]: """Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts.
This produces the format expected in `.eval_results/*.yaml` files.
Args: entries (`list[EvalResultEntry]`): List of evaluation result entries to serialize.
Returns: `list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML.
Example: ```python >>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml >>> entries = [ ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90), ... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412), ... ] >>> yaml_data = eval_result_entries_to_yaml(entries) >>> yaml_data[0] {'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9}
```
To upload eval results to the Hub: ```python >>> import yaml >>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml >>> entries = [ ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90), ... ] >>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries)) >>> upload_file( ... path_or_fileobj=yaml_content.encode(), ... path_in_repo=".eval_results/hle.yaml", ... repo_id="your-username/your-model", ... )
``` """ result = [] for entry in entries: # build the dataset object dataset: dict[str, Any] = {"id": entry.dataset_id, "task_id": entry.task_id} if entry.dataset_revision is not None: dataset["revision"] = entry.dataset_revision
data: dict[str, Any] = {"dataset": dataset, "value": entry.value} if entry.verify_token is not None: data["verifyToken"] = entry.verify_token if entry.date is not None: data["date"] = entry.date # build the source object if entry.source_url is not None: source: dict[str, Any] = {"url": entry.source_url} if entry.source_name is not None: source["name"] = entry.source_name if entry.source_user is not None: source["user"] = entry.source_user if entry.source_org is not None: source["org"] = entry.source_org data["source"] = source if entry.notes is not None: data["notes"] = entry.notes
result.append(data) return result
def parse_eval_result_entries(data: list[dict[str, Any]]) -> list[EvalResultEntry]: """Parse a list of dicts into [`EvalResultEntry`] objects.
This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format, use [`model_index_to_eval_results`] instead.
Args: data (`list[dict[str, Any]]`): A list of dictionaries (e.g., parsed from YAML or API response).
Returns: `list[EvalResultEntry]`: A list of evaluation result entry objects.
Example: ```python >>> from huggingface_hub import parse_eval_result_entries >>> data = [ ... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90}, ... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412}, ... ] >>> entries = parse_eval_result_entries(data) >>> entries[0].dataset_id 'cais/hle' >>> entries[0].value 20.9
``` """ entries = [] for item in data: entry_data = item.get("data", item) dataset = entry_data.get("dataset", {}) source = entry_data.get("source", {}) entry = EvalResultEntry( dataset_id=dataset["id"], value=entry_data["value"], task_id=dataset["task_id"], dataset_revision=dataset.get("revision"), verify_token=entry_data.get("verifyToken"), date=entry_data.get("date"), source_url=source.get("url") if source else None, source_name=source.get("name") if source else None, source_user=source.get("user") if source else None, source_org=source.get("org") if source else None, notes=entry_data.get("notes"), ) entries.append(entry) return entries.cache/pip/http-v2/1/1/c/a/5/11ca53f6629b39be038f5f3f843243e294312a1cd0bda91c3e78a20bAdded
.cache/pip/http-v2/1/1/c/a/5/11ca53f6629b39be038f5f3f843243e294312a1cd0bda91c3e78a20b.bodyAdded+1091
.cache/pip/http-v2/1/7/9/c/1/179c1c4742bcaf5b6d7af8dc2f14a1b329b9b11f7f5b09e3faa897a1Added
.cache/pip/http-v2/1/8/e/c/b/18ecb372789efe49bbe46617b1f5d32a2b0eac245d58cbf930116174Added
.cache/pip/http-v2/1/e/b/f/d/1ebfddf16e338050f3c69ee3fb0551055792844fc428979435d11f85Added
.cache/pip/http-v2/1/e/b/f/d/1ebfddf16e338050f3c69ee3fb0551055792844fc428979435d11f85.bodyAdded+3
.cache/pip/http-v2/3/3/2/7/a/3327a46f678846be6cb46f3352e6fba668d9664c70a79484c770e358Added
.cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560Added
.cache/pip/http-v2/3/5/a/0/6/35a0615e0411edd59492c90e8f5cd0a1a0554d6f7d1dec5be2b30560.bodyAdded+97
.cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2dAdded
.cache/pip/http-v2/3/8/6/0/e/3860e4de9ae53c79d2fd61419e9049df314ccc8b640782c02c6e2e2d.bodyAdded
.cache/pip/http-v2/3/9/b/0/3/39b032291f3825af700bccccb41d7507c739ba2f89c5bbbc5b7b490dAdded
.cache/pip/http-v2/3/9/b/0/3/39b032291f3825af700bccccb41d7507c739ba2f89c5bbbc5b7b490d.bodyAdded
.cache/pip/http-v2/6/4/2/d/4/642d4b6a48573d7d40bd54626ef2bb21e5059817d13c7487dcfea9fdAdded
.cache/pip/http-v2/6/4/2/d/4/642d4b6a48573d7d40bd54626ef2bb21e5059817d13c7487dcfea9fd.bodyAdded+1600
.cache/pip/http-v2/6/4/6/7/b/6467bdd236eabb4648139f514441e5510842fbc90755e4738c64fcf3Added
.cache/pip/http-v2/6/4/6/7/b/6467bdd236eabb4648139f514441e5510842fbc90755e4738c64fcf3.bodyAdded+341
.cache/pip/http-v2/6/4/c/f/c/64cfc03e83f9fad4049b1d2a1d785c9273270a4ab9788b538f5054e3Added
.cache/pip/http-v2/6/5/1/e/5/651e58859e8db8c99b9e7068d03984cfd4577518ff0e021c717afbf4Added
.cache/pip/http-v2/6/5/1/e/5/651e58859e8db8c99b9e7068d03984cfd4577518ff0e021c717afbf4.bodyAdded+78
.cache/pip/http-v2/6/6/e/c/7/66ec76a7b6ed4081044f5c7821af293b63c17bc2ac523ff93d5ca7d5Added
.cache/pip/http-v2/6/8/0/d/4/680d4dd80dc6a3d2df9b9478dfcc8e81e0e4f130e154a3268b98b877Added
.cache/pip/http-v2/6/b/5/3/a/6b53a9dd0e4fce887cc28c1a921aa1befe8c1a82e6c213d2542d2acbAdded
.cache/pip/http-v2/6/b/5/3/a/6b53a9dd0e4fce887cc28c1a921aa1befe8c1a82e6c213d2542d2acb.bodyAdded
.cache/pip/http-v2/a/b/e/2/c/abe2c30c0d105321771461cb84423576f0ec11c835b815e82e629cf7.bodyAdded+3
.cache/pip/http-v2/c/1/6/c/6/c16c6c635e568e65136b95a15ea17f91b43799aeb0a7e80b55d7a898Added
.cache/pip/http-v2/c/1/6/c/6/c16c6c635e568e65136b95a15ea17f91b43799aeb0a7e80b55d7a898.bodyAdded+1366
.cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3Added
.cache/pip/http-v2/c/c/c/b/4/cccb41730ba9dcdb4cb7127715ba43b53bfd809d6ff652fe215567a3.bodyAdded+300
.cache/pip/http-v2/c/d/5/d/e/cd5de44b899cbe1869765c21b55cffc53c0c0ffa9d3c6f1fd40a42a2Added
.cache/pip/http-v2/e/5/0/3/0/e503010ce88b2bb388d7806c951cab4dd3e436342653b4835f430bcc.bodyAdded+3
.cache/pip/http-v2/e/a/2/2/a/ea22a79fcbb7a5195dc8846d5b7ddabfe6981d47f448fe52cbe95a8aAdded
.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832dAdded
.cache/pip/http-v2/e/c/8/b/3/ec8b32f74b33a66cdb59c6ce388ac68e5697696325dcbe84554f832d.bodyAdded+139
.cache/uv/.gitignoreAdded+1
.cache/uv/.lockAdded
.cache/uv/CACHEDIR.TAGAdded+1
.cache/uv/archive-v0/9vHEgYd05Zufvhj6EkjIX/typing_extensions.pyAdded
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/METADATAAdded+373
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/RECORDAdded+190
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/WHEELAdded+5
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/entry_points.txtAdded+7
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/licenses/LICENSEAdded+201
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub-1.24.0.dist-info/top_level.txtAdded+1
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/__init__.pyAdded+1804
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_buckets.pyAdded+1244
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_commit_api.pyAdded+1075
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_commit_scheduler.pyAdded+353
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_dataset_viewer.pyAdded+172
.cache/uv/archive-v0/WbiZCgDidtA5T1uiQ47d5/huggingface_hub/_eval_results.pyAdded+211