Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 5)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/METADATAAdded+59
- .venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/RECORDAdded+43
- .venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/WHEELAdded+6
- .venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSEAdded+20
- .venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/top_level.txtAdded+2
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/METADATAAdded+1600
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/RECORDAdded+72
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/WHEELAdded+5
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/entry_points.txtAdded+2
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/licenses/LICENCEAdded+49
- .venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/top_level.txtAdded+1
- .venv-deploy/lib/python3.14/site-packages/tqdm/__init__.pyAdded+38
- .venv-deploy/lib/python3.14/site-packages/tqdm/__main__.pyAdded+3
- .venv-deploy/lib/python3.14/site-packages/tqdm/_main.pyAdded+9
- .venv-deploy/lib/python3.14/site-packages/tqdm/_monitor.pyAdded+104
- .venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm.pyAdded+9
- .venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm_gui.pyAdded+9
- .venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm_notebook.pyAdded+9
- .venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm_pandas.pyAdded+24
- .venv-deploy/lib/python3.14/site-packages/tqdm/_utils.pyAdded+11
- .venv-deploy/lib/python3.14/site-packages/tqdm/asyncio.pyAdded+103
- .venv-deploy/lib/python3.14/site-packages/tqdm/auto.pyAdded+40
- .venv-deploy/lib/python3.14/site-packages/tqdm/autonotebook.pyAdded+38
- .venv-deploy/lib/python3.14/site-packages/tqdm/cli.pyAdded+324
- .venv-deploy/lib/python3.14/site-packages/tqdm/completion.shAdded+19
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/__init__.pyAdded+91
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/bells.pyAdded+28
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/concurrent.pyAdded+259
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/discord.pyAdded+155
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/itertools.pyAdded+92
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/logging.pyAdded+128
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/slack.pyAdded+119
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/telegram.pyAdded+152
- .venv-deploy/lib/python3.14/site-packages/tqdm/contrib/utils_worker.pyAdded+38
- .venv-deploy/lib/python3.14/site-packages/tqdm/dask.pyAdded+44
- .venv-deploy/lib/python3.14/site-packages/tqdm/gui.pyAdded+179
- .venv-deploy/lib/python3.14/site-packages/tqdm/keras.pyAdded+123
- .venv-deploy/lib/python3.14/site-packages/tqdm/notebook.pyAdded+317
- .venv-deploy/lib/python3.14/site-packages/tqdm/rich.pyAdded+154
- .venv-deploy/lib/python3.14/site-packages/tqdm/std.pyAdded+1533
- .venv-deploy/lib/python3.14/site-packages/tqdm/tk.pyAdded+196
- .venv-deploy/lib/python3.14/site-packages/tqdm/tqdm.1Added+241
- .venv-deploy/lib/python3.14/site-packages/tqdm/utils.pyAdded+328
- .venv-deploy/lib/python3.14/site-packages/tqdm/version.pyAdded+7
- .venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/METADATAAdded+73
- .venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/RECORDAdded+7
- .venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/WHEELAdded+4
1pip1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859Metadata-Version: 2.4Name: PyYAMLVersion: 6.0.3Summary: YAML parser and emitter for PythonHome-page: https://pyyaml.org/Download-URL: https://pypi.org/project/PyYAML/Author: Kirill SimonovAuthor-email: xi@resolvent.netLicense: MITProject-URL: Bug Tracker, https://github.com/yaml/pyyaml/issuesProject-URL: CI, https://github.com/yaml/pyyaml/actionsProject-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentationProject-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-coreProject-URL: Source Code, https://github.com/yaml/pyyamlPlatform: AnyClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: CythonClassifier: 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 :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Text Processing :: MarkupRequires-Python: >=3.8License-File: LICENSEDynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: download-urlDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: platformDynamic: project-urlDynamic: requires-pythonDynamic: summary
YAML is a data serialization format designed for human readabilityand interaction with scripting languages. PyYAML is a YAML parserand emitter for Python.
PyYAML features a complete YAML 1.1 parser, Unicode support, picklesupport, capable extension API, and sensible error messages. PyYAMLsupports standard YAML tags and provides Python-specific tags thatallow to represent an arbitrary Python object.
PyYAML is applicable for a broad range of tasks from complexconfiguration files to object serialization and persistence.12345678910111213141516171819202122232425262728293031323334353637383940414243_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402
_yaml/__pycache__/__init__.cpython-314.pyc,,
pyyaml-6.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
pyyaml-6.0.3.dist-info/METADATA,sha256=A8O0Fe040J-u3Ek2DpMHabQMWPaFhebeAOLkkWqFjTQ,2351
pyyaml-6.0.3.dist-info/RECORD,,
pyyaml-6.0.3.dist-info/WHEEL,sha256=2Id6qreet5t4wZv58bZfijJ58qrc2xkw6OVvWfeqxV0,136
pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101
pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11
yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311
yaml/__pycache__/__init__.cpython-314.pyc,,
yaml/__pycache__/composer.cpython-314.pyc,,
yaml/__pycache__/constructor.cpython-314.pyc,,
yaml/__pycache__/cyaml.cpython-314.pyc,,
yaml/__pycache__/dumper.cpython-314.pyc,,
yaml/__pycache__/emitter.cpython-314.pyc,,
yaml/__pycache__/error.cpython-314.pyc,,
yaml/__pycache__/events.cpython-314.pyc,,
yaml/__pycache__/loader.cpython-314.pyc,,
yaml/__pycache__/nodes.cpython-314.pyc,,
yaml/__pycache__/parser.cpython-314.pyc,,
yaml/__pycache__/reader.cpython-314.pyc,,
yaml/__pycache__/representer.cpython-314.pyc,,
yaml/__pycache__/resolver.cpython-314.pyc,,
yaml/__pycache__/scanner.cpython-314.pyc,,
yaml/__pycache__/serializer.cpython-314.pyc,,
yaml/__pycache__/tokens.cpython-314.pyc,,
yaml/_yaml.cpython-314-darwin.so,sha256=NbKLqNxnfiS818H8Fwaxlg8XO7l0l8NXOlJ7Ra7RIQc,381736
yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883
yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639
yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851
yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837
yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006
yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533
yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445
yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061
yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440
yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495
yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794
yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190
yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004
yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279
yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165
yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573123456Wheel-Version: 1.0Generator: setuptools (80.9.0)Root-Is-Purelib: falseTag: cp314-cp314-macosx_11_0_arm64Generator: delocate 0.13.0
1234567891011121314151617181920Copyright (c) 2017-2021 Ingy döt NetCopyright (c) 2006-2016 Kirill Simonov
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 copiesof the Software, and to permit persons to whom the Software is furnished to doso, 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,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.12_yamlyaml1pip1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600Metadata-Version: 2.4Name: tqdmVersion: 4.70.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 also be 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://static.pepy.tech/personalized-badge/tqdm?left_text=downloads%2Fmonth :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=social123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172../../../bin/tqdm,sha256=aTSUx3c2oW3GmXMHI8AKhq6ZIlEkkeEgYglw1dJHvYA,297
tqdm-4.70.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
tqdm-4.70.0.dist-info/METADATA,sha256=DZW4W5BCj4d2r8SpKxfFCU947pjRULMlWsvN9OnVeUE,57344
tqdm-4.70.0.dist-info/RECORD,,
tqdm-4.70.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
tqdm-4.70.0.dist-info/entry_points.txt,sha256=ReJCH7Ui3Zyh6M16E4OhsZ1oU7WtMXCfbtoyBhGO29Y,39
tqdm-4.70.0.dist-info/licenses/LICENCE,sha256=_P-Hw6R86AKKhRKqGC1PzwrRyQVE7nXPmzQ2hMrBlN4,1985
tqdm-4.70.0.dist-info/top_level.txt,sha256=NLiUJNfmc9At15s7JURiwvqMEjUi9G5PMGRrmMYzNSM,5
tqdm/__init__.py,sha256=9mQNYSSqP99JasubEC1POJLMmhkkBH6cJZxPIR5G2pQ,1572
tqdm/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
tqdm/__pycache__/__init__.cpython-314.pyc,,
tqdm/__pycache__/__main__.cpython-314.pyc,,
tqdm/__pycache__/_main.cpython-314.pyc,,
tqdm/__pycache__/_monitor.cpython-314.pyc,,
tqdm/__pycache__/_tqdm.cpython-314.pyc,,
tqdm/__pycache__/_tqdm_gui.cpython-314.pyc,,
tqdm/__pycache__/_tqdm_notebook.cpython-314.pyc,,
tqdm/__pycache__/_tqdm_pandas.cpython-314.pyc,,
tqdm/__pycache__/_utils.cpython-314.pyc,,
tqdm/__pycache__/asyncio.cpython-314.pyc,,
tqdm/__pycache__/auto.cpython-314.pyc,,
tqdm/__pycache__/autonotebook.cpython-314.pyc,,
tqdm/__pycache__/cli.cpython-314.pyc,,
tqdm/__pycache__/dask.cpython-314.pyc,,
tqdm/__pycache__/gui.cpython-314.pyc,,
tqdm/__pycache__/keras.cpython-314.pyc,,
tqdm/__pycache__/notebook.cpython-314.pyc,,
tqdm/__pycache__/rich.cpython-314.pyc,,
tqdm/__pycache__/std.cpython-314.pyc,,
tqdm/__pycache__/tk.cpython-314.pyc,,
tqdm/__pycache__/utils.cpython-314.pyc,,
tqdm/__pycache__/version.cpython-314.pyc,,
tqdm/_main.py,sha256=9ySvgmi_2Sw4CAo5UDW0Q2dxfTryboEWGHohfCJz0sA,283
tqdm/_monitor.py,sha256=1VcavuotYSN6K-1jbpNuy6HYtr3mwo5Nh_jZMQ-jg3A,4013
tqdm/_tqdm.py,sha256=LfLCuJ6bpsVo9xilmtBXyEm1vGnUCFrliW85j3J-nD4,283
tqdm/_tqdm_gui.py,sha256=03Hc8KayxJveieI5-0-2NGiDpLvw9jZekofJUV7CCwk,287
tqdm/_tqdm_notebook.py,sha256=BuHiLuxu6uEfZFaPJW3RPpPaxaVctEQA3kdSJSDL1hw,307
tqdm/_tqdm_pandas.py,sha256=c9jptUgigN6axRDhRd4Rif98Tmxeopc1nFNFhIpbFUE,888
tqdm/_utils.py,sha256=CfLztxFY-QRiNfxQCqAb2N8E13uauIM95RSQiFlaEuE,559
tqdm/asyncio.py,sha256=IpcGo6ZFwc6KKHYj5s7h4kaRiogcabJ6PcqHj6jdy0I,3196
tqdm/auto.py,sha256=nDZflj6p2zKkjBCNBourrhS81zYfZy1_dQvbckrdW8o,871
tqdm/autonotebook.py,sha256=2pNgGCJDsesNNyYnmSve8BNQLiGSgo97SsPoMXCrNRQ,1440
tqdm/cli.py,sha256=t1j_PqI0SuMyhJGoBxMPCXY-UTbfjciaAQYxAU_f_V0,11011
tqdm/completion.sh,sha256=j79KbSmpIj_E11jfTfBXrGnUTzKXVpQ1vGVQvsyDRl4,946
tqdm/contrib/__init__.py,sha256=1GMYYE866WCvlHg5MdmzOvPsQj4ZuMlXzz8xcRcJD60,2479
tqdm/contrib/__pycache__/__init__.cpython-314.pyc,,
tqdm/contrib/__pycache__/bells.cpython-314.pyc,,
tqdm/contrib/__pycache__/concurrent.cpython-314.pyc,,
tqdm/contrib/__pycache__/discord.cpython-314.pyc,,
tqdm/contrib/__pycache__/itertools.cpython-314.pyc,,
tqdm/contrib/__pycache__/logging.cpython-314.pyc,,
tqdm/contrib/__pycache__/slack.cpython-314.pyc,,
tqdm/contrib/__pycache__/telegram.cpython-314.pyc,,
tqdm/contrib/__pycache__/utils_worker.cpython-314.pyc,,
tqdm/contrib/bells.py,sha256=IaxC2YW57xHDinxdUDQHvSego0HSTdDTExQQENvSB_k,921
tqdm/contrib/concurrent.py,sha256=XAgKYE2of1XIOEsD-gtrK82xQzDA1PEwvIpP_jcEuTs,9849
tqdm/contrib/discord.py,sha256=LPjxDbmfiYtw3OAm_WhtwbX9BVYDlPc8lJ96aY3YZDE,5337
tqdm/contrib/itertools.py,sha256=MA9-Jvb3ToseppInvev2iF4bokN7GQy4Q4LgjUyYdA4,2949
tqdm/contrib/logging.py,sha256=0nFn2C7qUUiKPB19qTGuS9Lfja8aiFW0u9kybRdG0hU,3902
tqdm/contrib/slack.py,sha256=sC182v7xBkfGftnDeUmQALMOfwQzU3ZiNf1Q_XA1DjI,4049
tqdm/contrib/telegram.py,sha256=ybTraGjUQx5m443TsX6pJ7Uxrpsh1m4a43BTWVl_4e4,5081
tqdm/contrib/utils_worker.py,sha256=vaxyJyagYwOCQXLUMd86bCbI4sPqZysuMGbDSGmvEWo,1199
tqdm/dask.py,sha256=9Ei58eVqTossRLhAfWyUFCduXYKjmLmwkaXIy-CHYfs,1319
tqdm/gui.py,sha256=maQ7jgB5leWHwxMlbBv08hpe5lytvmH0hEARu22GRdU,5481
tqdm/keras.py,sha256=ugd80-xCxMqnrbx_DEOpmj6c2Sh1xoVtQ8V9-bw29eo,4396
tqdm/notebook.py,sha256=6xkUTcYRsFxN4_BSUYYZ51kAgI7ycnT0HLpP9HukEqg,10888
tqdm/rich.py,sha256=J04yq6y2Ur9012zC7PkczA1t7cDjet88hmBkrAv-s2s,5255
tqdm/std.py,sha256=t-7qDtaeZoxAw9_K7JWxYe7Wbn1c_GRsO4HEkluaYB0,58074
tqdm/tk.py,sha256=3VsB1MDAkCItaWu7CmMb2CoTLMiqmDiEgNi3yiqQ5GY,6702
tqdm/tqdm.1,sha256=MLg9qjeHThZpPEQbWVrf5P5gOXMKHE_X606FSOBI9eU,7538
tqdm/utils.py,sha256=o_f0V32H_wrn0XmRno3j9pJ9xlp5xL0fHT3gtqL-k58,9746
tqdm/version.py,sha256=0uH4TLe8I8H71x29dlmtEZBObLT3b5IW-nytF3V0IVw,23312345Wheel-Version: 1.0Generator: setuptools (83.0.0)Root-Is-Purelib: trueTag: py3-none-any
12[console_scripts]tqdm = tqdm.cli:main12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849`tqdm` is a product of collaborative work.Unless otherwise stated, all authors (see commit logs) retain copyrightfor their respective work, and release the work under the MIT licence(text below).
Exceptions or notable authors are listed belowin reverse chronological order:
* files: * MPL-2.0 2015-2026 (c) Casper da Costa-Luis [casperdcl](https://github.com/casperdcl).* files: tqdm/_tqdm.py MIT 2016 (c) [PR #96] on behalf of Google Inc.* files: tqdm/_tqdm.py README.rst .gitignore MIT 2013 (c) Noam Yorav-Raphael, original author.
[PR #96]: https://github.com/tqdm/tqdm/pull/96
Mozilla Public Licence (MPL) v. 2.0 - Exhibit A-----------------------------------------------
This Source Code Form is subject to the terms of theMozilla Public License, v. 2.0.If a copy of the MPL was not distributed with this project,You can obtain one at https://mozilla.org/MPL/2.0/.
MIT License (MIT)-----------------
Copyright (c) 2013 noamraph
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.1tqdm1234567891011121314151617181920212223242526272829303132333435363738from ._monitor import TMonitor, TqdmSynchronisationWarningfrom ._tqdm_pandas import tqdm_pandasfrom .cli import main # TODO: remove in v5.0.0from .gui import tqdm as tqdm_gui # TODO: remove in v5.0.0from .gui import trange as tgrange # TODO: remove in v5.0.0from .std import ( TqdmDeprecationWarning, TqdmExperimentalWarning, TqdmKeyError, TqdmMonitorWarning, TqdmTypeError, TqdmWarning, tqdm, trange)from .version import __version__
__all__ = ['tqdm', 'tqdm_gui', 'trange', 'tgrange', 'tqdm_pandas', 'tqdm_notebook', 'tnrange', 'main', 'TMonitor', 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning', 'TqdmDeprecationWarning', 'TqdmExperimentalWarning', 'TqdmMonitorWarning', 'TqdmSynchronisationWarning', '__version__']
def tqdm_notebook(*args, **kwargs): # pragma: no cover """See tqdm.notebook.tqdm for full documentation""" from warnings import warn
from .notebook import tqdm as _tqdm_notebook warn("This function will be removed in tqdm==5.0.0\n" "Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`", TqdmDeprecationWarning, stacklevel=2) return _tqdm_notebook(*args, **kwargs)
def tnrange(*args, **kwargs): # pragma: no cover """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`.""" from warnings import warn
from .notebook import trange as _tnrange warn("Please use `tqdm.notebook.trange` instead of `tqdm.tnrange`", TqdmDeprecationWarning, stacklevel=2) return _tnrange(*args, **kwargs)123from .cli import main
main()123456789from warnings import warn
from .cli import * # NOQAfrom .cli import __all__ # NOQAfrom .std import TqdmDeprecationWarning
warn("This function will be removed in tqdm==5.0.0\n" "Please use `tqdm.cli.*` instead of `tqdm._main.*`", TqdmDeprecationWarning, stacklevel=2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import atexitfrom threading import Event, Thread, current_threadfrom time import timefrom warnings import warn
__all__ = ["TMonitor", "TqdmSynchronisationWarning"]
class TqdmSynchronisationWarning(RuntimeWarning): """ tqdm multi-thread/-process errors which may cause incorrect nesting but otherwise no adverse effects """
class TMonitor(Thread): """ Monitoring thread for tqdm bars. Monitors if tqdm bars are taking too much time to display and readjusts miniters automatically if necessary.
Parameters ---------- tqdm_cls : class tqdm class to use (can be core tqdm or a submodule). sleep_interval : float Time to sleep between monitoring checks. """ _test = {} # internal vars for unit testing
def __init__(self, tqdm_cls, sleep_interval): Thread.__init__(self, name="tqdm_monitor") self.daemon = True # kill thread when main killed (KeyboardInterrupt) self.woken = 0 # last time woken up, to sync with monitor self.tqdm_cls = tqdm_cls self.sleep_interval = sleep_interval self._time = self._test.get("time", time) self.was_killed = self._test.get("Event", Event)() atexit.register(self._atexit_signal) self.start()
def _atexit_signal(self): """ Non-joining shutdown signal. Avoids deadlocks at interpreter exit from other threads, dead forks, etc. This daemon thread is auto-reaped on shutdown without needing a join. """ self.was_killed.set()
def exit(self): self.was_killed.set() if self is not current_thread(): self.join() return self.report()
def get_instances(self): # returns a copy of started `tqdm_cls` instances return [i for i in self.tqdm_cls._instances.copy() # Avoid race by checking that the instance started if hasattr(i, 'start_t')]
def run(self): cur_t = self._time() while True: # After processing and before sleeping, notify that we woke # Need to be done just before sleeping self.woken = cur_t # Sleep some time... self.was_killed.wait(self.sleep_interval) # Quit if killed if self.was_killed.is_set(): return # Then monitor! # Acquire lock (to access _instances) with self.tqdm_cls.get_lock(): cur_t = self._time() # Check tqdm instances are waiting too long to print instances = self.get_instances() for instance in instances: # Check event in loop to reduce blocking time on exit if self.was_killed.is_set(): return # Only if mininterval > 1 (else iterations are just slow) # and last refresh exceeded maxinterval if ( instance.miniters > 1 and (cur_t - instance.last_print_t) >= instance.maxinterval ): # force bypassing miniters on next iteration # (dynamic_miniters adjusts mininterval automatically) instance.miniters = 1 # Refresh now! (works only for manual tqdm) instance.refresh(nolock=True) # Remove accidental long-lived strong reference del instance if instances != self.get_instances(): # pragma: nocover warn("Set changed size during iteration" + " (see https://github.com/tqdm/tqdm/issues/481)", TqdmSynchronisationWarning, stacklevel=2) # Remove accidental long-lived strong references del instances
def report(self): return not self.was_killed.is_set()123456789from warnings import warn
from .std import * # NOQAfrom .std import __all__ # NOQAfrom .std import TqdmDeprecationWarning
warn("This function will be removed in tqdm==5.0.0\n" "Please use `tqdm.std.*` instead of `tqdm._tqdm.*`", TqdmDeprecationWarning, stacklevel=2)123456789from warnings import warn
from .gui import * # NOQAfrom .gui import __all__ # NOQAfrom .std import TqdmDeprecationWarning
warn("This function will be removed in tqdm==5.0.0\n" "Please use `tqdm.gui.*` instead of `tqdm._tqdm_gui.*`", TqdmDeprecationWarning, stacklevel=2)123456789from warnings import warn
from .notebook import * # NOQAfrom .notebook import __all__ # NOQAfrom .std import TqdmDeprecationWarning
warn("This function will be removed in tqdm==5.0.0\n" "Please use `tqdm.notebook.*` instead of `tqdm._tqdm_notebook.*`", TqdmDeprecationWarning, stacklevel=2)123456789101112131415161718192021222324import sys
__author__ = "github.com/casperdcl"__all__ = ['tqdm_pandas']
def tqdm_pandas(tclass, **tqdm_kwargs): """ Registers the given `tqdm` instance with `pandas.core.groupby.DataFrameGroupBy.progress_apply`. """ from tqdm import TqdmDeprecationWarning
if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith( 'tqdm_')): # delayed adapter case TqdmDeprecationWarning( "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.", fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write)) tclass.pandas(**tqdm_kwargs) else: TqdmDeprecationWarning( "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.", fp_write=getattr(tclass.fp, 'write', sys.stderr.write)) type(tclass).pandas(deprecated_t=tclass)1234567891011from warnings import warn
from .std import TqdmDeprecationWarningfrom .utils import ( # noqa: F401, pylint: disable=unused-import CUR_OS, IS_NIX, IS_WIN, RE_ANSI, Comparable, FormatReplace, SimpleTextIOWrapper, _environ_cols_wrapper, _is_ascii, _is_utf, _screen_shape_linux, _screen_shape_tput, _screen_shape_windows, _screen_shape_wrapper, _supports_unicode, _term_move_up, colorama)
warn("This function will be removed in tqdm==5.0.0\n" "Please use `tqdm.utils.*` instead of `tqdm._utils.*`", TqdmDeprecationWarning, stacklevel=2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Asynchronous progress bar decorator for iterators.Includes a default `range` iterator printing to `stderr`.
Usage:>>> from tqdm.asyncio import trange, tqdm>>> async for i in trange(10):... ..."""import asynciofrom sys import version_info
from .std import tqdm as std_tqdm
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['tqdm_asyncio', 'tarange', 'tqdm', 'trange']
class tqdm_asyncio(std_tqdm): """ Asynchronous-friendly version of tqdm. """ def __init__(self, iterable=None, *args, **kwargs): super().__init__(iterable, *args, **kwargs) self.iterable_awaitable = False if iterable is not None: if hasattr(iterable, "__anext__"): self.iterable_next = iterable.__anext__ self.iterable_awaitable = True elif hasattr(iterable, "__aiter__"): self.iterable_iterator = iterable.__aiter__() self.iterable_next = self.iterable_iterator.__anext__ self.iterable_awaitable = True elif hasattr(iterable, "__next__"): self.iterable_next = iterable.__next__ else: self.iterable_iterator = iter(iterable) self.iterable_next = self.iterable_iterator.__next__
def __aiter__(self): return self
async def __anext__(self): try: if self.iterable_awaitable: res = await self.iterable_next() else: res = self.iterable_next() self.update() return res except StopIteration: self.close() raise StopAsyncIteration except BaseException: self.close() raise
def send(self, *args, **kwargs): return self.iterable.send(*args, **kwargs)
@classmethod def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs): """ Wrapper for `asyncio.as_completed`. """ if total is None: total = len(fs) kwargs = {} if version_info[:2] < (3, 10): kwargs['loop'] = loop yield from cls(asyncio.as_completed(fs, timeout=timeout, **kwargs), total=total, **tqdm_kwargs)
@classmethod async def gather(cls, *fs, loop=None, timeout=None, total=None, return_exceptions=False, **tqdm_kwargs): """ Wrapper for `asyncio.gather`. """ async def wrap_awaitable(i, f): try: return i, await f except Exception as e: # noqa: BLE001 if return_exceptions: return i, e raise
ifs = [wrap_awaitable(i, f) for i, f in enumerate(fs)] res = [await f for f in cls.as_completed(ifs, loop=loop, timeout=timeout, total=total, **tqdm_kwargs)] return [i for _, i in sorted(res)]
def tarange(*args, **kwargs): """ A shortcut for `tqdm.asyncio.tqdm(range(*args), **kwargs)`. """ return tqdm_asyncio(range(*args), **kwargs)
# Aliasestqdm = tqdm_asynciotrange = tarange12345678910111213141516171819202122232425262728293031323334353637383940"""Enables multiple commonly used features.
Method resolution order:
- `tqdm.autonotebook` without import warnings- `tqdm.asyncio`- `tqdm.std` base class
Usage:>>> from tqdm.auto import trange, tqdm>>> for i in trange(10):... ..."""import warnings
from .std import TqdmExperimentalWarning
with warnings.catch_warnings(): warnings.simplefilter("ignore", category=TqdmExperimentalWarning) from .autonotebook import tqdm as notebook_tqdm
from .asyncio import tqdm as asyncio_tqdmfrom .std import tqdm as std_tqdm
if notebook_tqdm != std_tqdm: class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro passelse: tqdm = asyncio_tqdm
def trange(*args, **kwargs): """ A shortcut for `tqdm.auto.tqdm(range(*args), **kwargs)`. """ return tqdm(range(*args), **kwargs)
__all__ = ["tqdm", "trange"]1234567891011121314151617181920212223242526272829303132333435363738"""Automatically choose between `tqdm.notebook` and `tqdm.std`.
Usage:>>> from tqdm.autonotebook import trange, tqdm>>> for i in trange(10):... ..."""import osimport sysfrom warnings import warn
try: if 'ipykernel.zmqshell' in sys.modules: if any(i == 'QT_API' or i.startswith('SPYDER') for i in os.environ): raise ImportError("console") # jupyter-qtconsole/spyder ipy = sys.modules['IPython'].get_ipython().__class__.__name__.lower() if 'qt' in ipy or 'spyder' in ipy: raise ImportError("console") # older jupyter-qtconsole/spyder # jupyter-notebook/jupyterlab/vscode/binder/colab elif 'IPython.utils._process_emscripten' in sys.modules: pass # jupyterlite (pyodide)/jupyterlite-xeus else: raise ImportError("console") # ipython/jupyter-console from .notebook import WARN_NOIPYW, IProgress if IProgress is None: from .std import TqdmWarning warn(WARN_NOIPYW, TqdmWarning, stacklevel=2) raise ImportError('ipywidgets')except Exception: from .std import tqdm, trangeelse: # pragma: no cover from .notebook import tqdm, trange from .std import TqdmExperimentalWarning warn("Using `tqdm.autonotebook.tqdm` in notebook mode." " Use `tqdm.tqdm` instead to force console mode" " (e.g. in jupyter console)", TqdmExperimentalWarning, stacklevel=2)__all__ = ["tqdm", "trange"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324"""Module version for monitoring CLI pipes (`... | python -m tqdm | ...`)."""import loggingimport reimport sysfrom ast import literal_evalfrom textwrap import indent
from .std import TqdmKeyError, TqdmTypeError, tqdmfrom .version import __version__
__all__ = ["main"]log = logging.getLogger(__name__)
def cast(val, typ): log.debug((val, typ)) if " or " in typ: for t in typ.split(" or "): try: return cast(val, t) except TqdmTypeError: pass raise TqdmTypeError(f"{val} : {typ}")
# sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n') if typ == 'bool': if (val == 'True') or (val == ''): return True if val == 'False': return False raise TqdmTypeError(val + ' : ' + typ) if typ == 'chr': if len(val) == 1: return val.encode() if re.match(r"^\\\w+$", val): return literal_eval(f'"{val}"').encode() raise TqdmTypeError(f"{val} : {typ}") if typ == 'str': return val if typ == 'int': try: return int(val) except ValueError as exc: raise TqdmTypeError(f"{val} : {typ}") from exc if typ == 'float': try: return float(val) except ValueError as exc: raise TqdmTypeError(f"{val} : {typ}") from exc raise TqdmTypeError(f"{val} : {typ}")
def posix_pipe(fin, fout, delim=b'\\n', buf_size=256, callback=lambda float: None, callback_len=True): """ Params ------ fin : binary file with `read(buf_size : int)` method fout : binary file with `write` (and optionally `flush`) methods. callback : function(float), e.g.: `tqdm.update` callback_len : If (default: True) do `callback(len(buffer))`. Otherwise, do `callback(data) for data in buffer.split(delim)`. """ fp_write = fout.write
if not delim: while True: tmp = fin.read(buf_size)
# flush at EOF if not tmp: getattr(fout, 'flush', lambda: None)() return
fp_write(tmp) callback(len(tmp)) # return
buf = b'' len_delim = len(delim) # n = 0 while True: tmp = fin.read(buf_size)
# flush at EOF if not tmp: if buf: fp_write(buf) if callback_len: # n += 1 + buf.count(delim) callback(1 + buf.count(delim)) else: for i in buf.split(delim): callback(i) getattr(fout, 'flush', lambda: None)() return # n
while True: i = tmp.find(delim) if i < 0: buf += tmp break fp_write(buf + tmp[:i + len(delim)]) # n += 1 callback(1 if callback_len else (buf + tmp[:i])) buf = b'' tmp = tmp[i + len_delim:]
# ((opt, type), ... )RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)')# better split method assuming no positional argsRE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)')
# TODO: add custom support for some of the following?UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file')
# The 8 leading spaces are required for consistencyCLI_EXTRA_DOC = r""" Extra CLI Options ----------------- name : type, optional TODO: find out why this is needed. 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."""
def main(fp=sys.stderr, argv=None): """ Parameters (internal use only) --------- fp : file-like object for tqdm argv : list (default: sys.argv[1:]) """ if argv is None: argv = sys.argv[1:] try: log_idx = argv.index('--log') except ValueError: for i in argv: if i.startswith('--log='): logLevel = i[len('--log='):] break else: logLevel = 'INFO' else: # argv.pop(log_idx) # logLevel = argv.pop(log_idx) logLevel = argv[log_idx + 1] logging.basicConfig(level=getattr(logging, logLevel), format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
# py<3.13 doesn't dedent docstrings d = (tqdm.__doc__ if sys.version_info < (3, 13) else indent(tqdm.__doc__, " ")) + CLI_EXTRA_DOC
opt_types = dict(RE_OPTS.findall(d)) # opt_types['delim'] = 'chr'
for o in UNSUPPORTED_OPTS: opt_types.pop(o)
log.debug(sorted(opt_types.items()))
# d = RE_OPTS.sub(r' --\1=<\1> : \2', d) split = RE_OPTS.split(d) opt_types_desc = zip(split[1::3], split[2::3], split[3::3]) d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else '\n --{0}=<{1}> : {2}{3}').format( otd[0].replace('_', '-'), otd[0], *otd[1:]) for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS)
help_short = "Usage:\n tqdm [--help | options]\n" d = help_short + """Options: -h, --help Print this help and exit. -v, --version Print version and exit.""" + d.strip('\n') + '\n'
# opts = docopt(d, version=__version__) if any(v in argv for v in ('-v', '--version')): sys.stdout.write(__version__ + '\n') sys.exit(0) elif any(v in argv for v in ('-h', '--help')): sys.stdout.write(d + '\n') sys.exit(0) elif argv and argv[0][:2] != '--': sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}")
argv = RE_SHLEX.split(' '.join(["tqdm"] + argv)) opts = dict(zip(argv[1::3], argv[3::3]))
log.debug(opts) opts.pop('log', True)
tqdm_args = {'file': fp} try: for (o, v) in opts.items(): o = o.replace('-', '_') try: tqdm_args[o] = cast(v, opt_types[o]) except KeyError as e: raise TqdmKeyError(str(e)) log.debug('args:' + str(tqdm_args))
delim_per_char = tqdm_args.pop('bytes', False) update = tqdm_args.pop('update', False) update_to = tqdm_args.pop('update_to', False) if sum((delim_per_char, update, update_to)) > 1: raise TqdmKeyError("Can only have one of --bytes --update --update_to") except Exception: fp.write("\nError:\n" + help_short) stdin, stdout_write = sys.stdin, sys.stdout.write for i in stdin: stdout_write(i) raise else: buf_size = tqdm_args.pop('buf_size', 256) delim = tqdm_args.pop('delim', b'\\n') tee = tqdm_args.pop('tee', False) manpath = tqdm_args.pop('manpath', None) comppath = tqdm_args.pop('comppath', None) if tqdm_args.pop('null', False): class stdout: @staticmethod def write(_): pass else: stdout = sys.stdout stdout = getattr(stdout, 'buffer', stdout) stdin = getattr(sys.stdin, 'buffer', sys.stdin) if manpath or comppath: try: # py<3.9 import importlib_resources as resources except ImportError: from importlib import resources from pathlib import Path
def cp(name, dst): """copy resource `name` to `dst`""" fi = resources.files('tqdm') / name dst.write_bytes(fi.read_bytes()) log.info("written:%s", dst) if manpath is not None: cp('tqdm.1', Path(manpath) / 'tqdm.1') if comppath is not None: cp('completion.sh', Path(comppath) / 'tqdm_completion.sh') sys.exit(0) if tee: stdout_write = stdout.write fp_write = getattr(fp, 'buffer', fp).write
class stdout: # pylint: disable=function-redefined @staticmethod def write(x): with tqdm.external_write_mode(file=fp): fp_write(x) stdout_write(x) if delim_per_char: tqdm_args.setdefault('unit', 'B') tqdm_args.setdefault('unit_scale', True) tqdm_args.setdefault('unit_divisor', 1024) log.debug(tqdm_args) with tqdm(**tqdm_args) as t: posix_pipe(stdin, stdout, '', buf_size, t.update) elif delim == b'\\n': log.debug(tqdm_args) write = stdout.write if update or update_to: with tqdm(**tqdm_args) as t: if update: def callback(i): t.update(literal_eval(i.decode())) else: # update_to def callback(i): t.update(literal_eval(i.decode()) - t.n) for i in stdin: write(i) callback(i) else: for i in tqdm(stdin, **tqdm_args): write(i) else: log.debug(tqdm_args) with tqdm(**tqdm_args) as t: callback_len = False if update: def callback(i): t.update(literal_eval(i.decode())) elif update_to: def callback(i): t.update(literal_eval(i.decode()) - t.n) else: callback = t.update callback_len = True posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len)12345678910111213141516171819#!/usr/bin/env bash_tqdm(){ local cur prv cur="${COMP_WORDS[COMP_CWORD]}" prv="${COMP_WORDS[COMP_CWORD - 1]}"
case ${prv} in --bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor) # await user input ;; "--log") COMPREPLY=($(compgen -W 'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur})) ;; *) COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur})) ;; esac}complete -F _tqdm tqdm12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Thin wrappers around common functions.
Subpackages contain potentially unstable extensions."""from warnings import warn
from ..auto import tqdm as tqdm_autofrom ..std import TqdmDeprecationWarning, tqdmfrom ..utils import ObjectWrapper
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['tenumerate', 'tzip', 'tmap']
class DummyTqdmFile(ObjectWrapper): """Dummy file-like that will write to tqdm"""
def __init__(self, wrapped): super().__init__(wrapped) self._buf = []
def write(self, x, nolock=False): nl = b"\n" if isinstance(x, bytes) else "\n" pre, sep, post = x.rpartition(nl) if sep: blank = type(nl)() tqdm.write(blank.join(self._buf + [pre, sep]), end=blank, file=self._wrapped, nolock=nolock) self._buf = [post] else: self._buf.append(x)
def __del__(self): if self._buf: blank = type(self._buf[0])() try: tqdm.write(blank.join(self._buf), end=blank, file=self._wrapped) except (OSError, ValueError): pass
def builtin_iterable(func): """Returns `func`""" warn("This function has no effect, and will be removed in tqdm==5.0.0", TqdmDeprecationWarning, stacklevel=2) return func
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, **tqdm_kwargs): """ Equivalent of `numpy.ndenumerate` or builtin `enumerate`.
Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ try: import numpy as np except ImportError: pass else: if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or iterable.size, **tqdm_kwargs) return enumerate(tqdm_class(iterable, total=total, **tqdm_kwargs), start)
def tzip(iter1, *iter2plus, **tqdm_kwargs): """ Equivalent of builtin `zip`.
Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ kwargs = tqdm_kwargs.copy() tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) yield from zip(tqdm_class(iter1, **kwargs), *iter2plus)
def tmap(function, *sequences, **tqdm_kwargs): """ Equivalent of builtin `map`.
Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ for i in tzip(*sequences, **tqdm_kwargs): yield function(*i)12345678910111213141516171819202122232425262728"""Even more features than `tqdm.auto` (all the bells & whistles):
- `tqdm.auto`- `tqdm.tqdm.pandas`- `tqdm.contrib.slack` + uses `${TQDM_SLACK_TOKEN}` and `${TQDM_SLACK_CHANNEL}`- `tqdm.contrib.telegram` + uses `${TQDM_TELEGRAM_TOKEN}` and `${TQDM_TELEGRAM_CHAT_ID}`- `tqdm.contrib.discord` + uses `${TQDM_DISCORD_TOKEN}` and `${TQDM_DISCORD_CHANNEL_ID}`"""__all__ = ['tqdm', 'trange']import warningsfrom os import getenv
if getenv("TQDM_SLACK_TOKEN") and getenv("TQDM_SLACK_CHANNEL"): from .slack import tqdm, trangeelif getenv("TQDM_TELEGRAM_TOKEN") and getenv("TQDM_TELEGRAM_CHAT_ID"): from .telegram import tqdm, trangeelif getenv("TQDM_DISCORD_TOKEN") and getenv("TQDM_DISCORD_CHANNEL_ID"): from .discord import tqdm, trangeelse: from ..auto import tqdm, trange
with warnings.catch_warnings(): warnings.simplefilter("ignore", category=FutureWarning) tqdm.pandas()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259"""Thin wrappers around `concurrent.futures`."""import sysfrom contextlib import contextmanagerfrom operator import length_hint
from ..auto import tqdm as tqdm_autofrom ..std import TqdmWarning
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['thread_map', 'process_map', 'interpreter_map']
class _InterpreterLock: """Reentrant lock backed by a cross-interpreter queue.""" from threading import get_ident from time import monotonic as _time
def __init__(self, queue): from threading import RLock self._queue = queue self._lock = RLock() self._owner = None self._depth = 0
def acquire(self, blocking=True, timeout=-1): from queue import Empty start = self._time() if timeout == -1: acquired = self._lock.acquire(blocking) else: acquired = self._lock.acquire(blocking, timeout) if not acquired: return False if self._depth: self._depth += 1 return True try: if not blocking: self._queue.get_nowait() elif timeout == -1: self._queue.get() else: remaining = max(0, timeout - (self._time() - start)) self._queue.get(timeout=remaining) except Empty: self._lock.release() return False self._owner = self.get_ident() self._depth = 1 return True
def release(self): if self._owner != self.get_ident(): raise RuntimeError("cannot release un-acquired lock") self._depth -= 1 if not self._depth: self._owner = None self._queue.put(None) self._lock.release()
def __enter__(self): self.acquire() return self
def __exit__(self, *exc): self.release()
@contextmanagerdef ensure_lock(tqdm_class, lock_name="", lock=None): """get (create if necessary) and then restore `tqdm_class`'s lock""" old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock if lock is None: lock = old_lock or tqdm_class.get_lock() # maybe create a new lock lock = getattr(lock, lock_name, lock) # maybe subtype tqdm_class.set_lock(lock) yield lock if old_lock is None: del tqdm_class._lock else: tqdm_class.set_lock(old_lock)
def _get_interpreter_init(tqdm_class, lock_queue_id): """Return an initializer which bootstraps the parent import path and lock.""" code = ( "import sys\n" f"sys.path[:] = {sys.path!r}\n" "from concurrent import interpreters\n" "from importlib import import_module\n" "from tqdm.contrib.concurrent import _InterpreterLock\n" f"tqdm_class = import_module({tqdm_class.__module__!r})\n" f"for name in {tqdm_class.__qualname__.split('.')!r}:\n" " tqdm_class = getattr(tqdm_class, name)\n" "tqdm_class.monitor_interval = 0\n" f"tqdm_class.set_lock(_InterpreterLock(interpreters.Queue({lock_queue_id!r})))") return exec, (code,)
def _min_map_len(iterables): """min(map(length_hint, iterables))""" return min(n for it in iterables if (n := length_hint(it, -1)) >= 0)
def _executor_map( PoolExecutor, fn, *iterables, max_workers=None, timeout=None, chunksize=1, lock_name="", tqdm_class=tqdm_auto, smoothing=0.0, _lock=None, _initializer=None, _initargs=None, **tqdm_kwargs): """ Implementation of `thread_map`, `process_map` and `interpreter_map`.
Parameters ---------- max_workers : int timeout : int buffersize : int Requires Python>=3.14. thread_name_prefix : str max_tasks_per_child : int mp_context : str """ kwargs = tqdm_kwargs.copy() if 'total' not in kwargs: kwargs['total'] = _min_map_len(iterables) map_kwargs = {} if 'buffersize' in kwargs: map_kwargs['buffersize'] = kwargs.pop('buffersize') pool_kwargs = {} for k in ('thread_name_prefix', 'max_tasks_per_child', 'mp_context'): if k in kwargs: pool_kwargs[k] = kwargs.pop(k) dynamic_miniters = None if kwargs['total'] and 'miniters' not in kwargs: try: from os import process_cpu_count as cpu_count except ImportError: from os import cpu_count # thread & process pools have different default workers, but we KISS here rough_max = max_workers or min(32, (cpu_count() or 1) + 4) if kwargs['total'] > rough_max: kwargs['miniters'] = rough_max dynamic_miniters = True with ensure_lock(tqdm_class, lock_name=lock_name, lock=_lock) as lk: # share lock in case workers are already using `tqdm` if _initializer is None: _initializer = tqdm_class.set_lock _initargs = (lk,) with PoolExecutor(max_workers=max_workers, initializer=_initializer, initargs=_initargs, **pool_kwargs) as ex: with tqdm_class(smoothing=smoothing, **kwargs) as pbar: if dynamic_miniters is not None: pbar.dynamic_miniters = True orisubmit = ex.submit
def patchsubmit(*args, **kwargs): fut = orisubmit(*args, **kwargs) fut.add_done_callback(lambda _: pbar.update()) return fut ex.submit = patchsubmit return list(ex.map( fn, *iterables, timeout=timeout, chunksize=chunksize, **map_kwargs))
def thread_map(fn, *iterables, **tqdm_kwargs): """ Equivalent of `list(map(fn, *iterables))` driven by `concurrent.futures.ThreadPoolExecutor`.
Parameters ---------- max_workers : int, optional Maximum number of workers to spawn; passed to `concurrent.futures.ThreadPoolExecutor`. thread_name_prefix : str, optional Passed to `concurrent.futures.ThreadPoolExecutor` [default: '']. timeout : int or float, optional Seconds to wait before raising `TimeoutError` if `__next__` is called and the result isn't available. [default: None]. buffersize : int, optional Requires Python>=3.14 [default: None]. tqdm_class : optional `tqdm` class to use for bars [default: tqdm.auto.tqdm]. smoothing : float, optional Passed to `tqdm_class`; the [default: 0] is average (due to erratic update frequency). lock_name : str, optional Member of `tqdm_class.get_lock()` to use [default: '']. """ from concurrent.futures import ThreadPoolExecutor return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
def interpreter_map(fn, *iterables, **tqdm_kwargs): """ Equivalent of `list(map(fn, *iterables))` driven by `concurrent.futures.InterpreterPoolExecutor` (Python 3.14+).
Parameters ---------- Same as `thread_map`.
Notes ----- `fn`, its arguments, and its return values must be pickleable. Worker progress bars using the same `tqdm_class` share a cross-interpreter write lock. """ from concurrent import interpreters from concurrent.futures import InterpreterPoolExecutor lock_queue = interpreters.create_queue() lock_queue.put(None) tqdm_class = tqdm_kwargs.get("tqdm_class", tqdm_auto) initializer, initargs = _get_interpreter_init(tqdm_class, lock_queue.id) return _executor_map( InterpreterPoolExecutor, fn, *iterables, _lock=_InterpreterLock(lock_queue), _initializer=initializer, _initargs=initargs, **tqdm_kwargs)
def process_map(fn, *iterables, lock_name="mp_lock", **tqdm_kwargs): """ Equivalent of `list(map(fn, *iterables))` driven by `concurrent.futures.ProcessPoolExecutor`.
Parameters ---------- max_workers : int, optional Maximum number of workers to spawn; passed to `concurrent.futures.ProcessPoolExecutor`. timeout : int or float, optional Seconds to wait before raising `TimeoutError` if `__next__` is called and the result isn't available. [default: None]. chunksize : int, optional Approximate size of chunks sent to worker processes; passed to `concurrent.futures.ProcessPoolExecutor.map`. [default: 1]. buffersize : int, optional Requires Python>=3.14 [default: None]. max_tasks_per_child : int, optional Maximum number of tasks a worker process can complete before being replaced with a new process; passed to `concurrent.futures.ProcessPoolExecutor`. mp_context : multiprocessing.BaseContext, optional Multiprocessing context to use, e.g. `multiprocessing.get_context('fork')`. lock_name : str, optional Member of `tqdm_class.get_lock()` to use [default: mp_lock]. tqdm_class : optional `tqdm` class to use for bars [default: tqdm.auto.tqdm]. smoothing : float, optional Passed to `tqdm_class`; the [default: 0] is average (due to erratic update frequency). """ from concurrent.futures import ProcessPoolExecutor if iterables and 'chunksize' not in tqdm_kwargs: # default `chunksize=1` has poor performance for large iterables # (most time spent dispatching items to workers). shortest_iterable_len = _min_map_len(iterables) if shortest_iterable_len > 1000: from warnings import warn warn("Iterable length %d > 1000 but `chunksize` is not set." " This may seriously degrade multiprocess performance." " Set `chunksize=1` or more." % shortest_iterable_len, TqdmWarning, stacklevel=2) return _executor_map(ProcessPoolExecutor, fn, *iterables, lock_name=lock_name, **tqdm_kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Sends updates to a Discord bot.
Usage:>>> from tqdm.contrib.discord import tqdm, trange>>> for i in trange(10, token='{token}', channel_id='{channel_id}'):... ...
"""from warnings import warn
from requests import Sessionfrom requests.utils import default_user_agent
from ..auto import tqdm as tqdm_autofrom ..std import TqdmWarningfrom ..utils import envwrapfrom ..version import __version__from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl", "guigoruiz1"]}__all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange']
class DiscordIO(MonoWorker): """Non-blocking file-like IO using a Discord Bot.""" API = 'https://discord.com/api/v10' UA = f"tqdm (https://tqdm.github.io, {__version__}) {default_user_agent()}"
def __init__(self, token, channel_id): """Creates a new message in the given `channel_id`.""" super().__init__() self.token = token self.channel_id = channel_id self.session = Session() self.text = self.__class__.__name__ self.message_id # pylint: disable=pointless-statement
@property def message_id(self): if hasattr(self, '_message_id'): return self._message_id # pylint: disable=access-member-before-definition try: req = self.session.post( f'{self.API}/channels/{self.channel_id}/messages', headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}, json={'content': f"`{self.text}`"}) res = req.json() req.raise_for_status() except Exception as e: if req.status_code == 429: warn("Creation rate limit: try increasing `mininterval`.", TqdmWarning, stacklevel=2) else: tqdm_auto.write(str(e)) else: self._message_id = res['id'] return self._message_id
def write(self, s): """Replaces internal `message_id`'s text with `s`.""" if not s: s = "..." s = s.replace('\r', '').strip() if s == self.text: return # avoid duplicate message Bot error message_id = self.message_id if message_id is None: return self.text = s try: future = self.submit( self.session.patch, f'{self.API}/channels/{self.channel_id}/messages/{message_id}', headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}, json={'content': f"`{self.text}`"}) except Exception as e: tqdm_auto.write(str(e)) else: return future
def delete(self): """Deletes internal `message_id`.""" try: future = self.submit( self.session.delete, f'{self.API}/channels/{self.channel_id}/messages/{self.message_id}', headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}) except Exception as e: tqdm_auto.write(str(e)) else: return future
class tqdm_discord(tqdm_auto): # pylint: disable=inconsistent-mro """ Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot. May take a few seconds to create (`__init__`).
- create a discord bot (not public, no requirement of OAuth2 code grant, only send message permissions) & invite it to a channel: <https://discordpy.readthedocs.io/en/latest/discord.html> - copy the bot `{token}` & `{channel_id}` and paste below
>>> from tqdm.contrib.discord import tqdm, trange >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'): ... ... """ @envwrap("tqdm", "discord", is_method=True) def __init__(self, *args, token=None, channel_id=None, **kwargs): """ Parameters ---------- token : str, required. Discord bot token [default: ${TQDM_DISCORD_TOKEN}]. channel_id : int, required. Discord channel ID [default: ${TQDM_DISCORD_CHANNEL_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters. """ if not kwargs.get('disable'): kwargs = kwargs.copy() self.dio = DiscordIO(token, channel_id) super().__init__(*args, **kwargs)
def display(self, **kwargs): # pylint: disable=arguments-differ super().display(**kwargs) fmt = self.format_dict if fmt.get('bar_format', None): fmt['bar_format'] = fmt['bar_format'].replace( '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}') self.dio.write(self.format_meter(**fmt))
def clear(self, *args, **kwargs): super().clear(*args, **kwargs) if not self.disable: self.dio.write("")
def close(self): if self.disable: return super().close() if not (self.leave or (self.leave is None and self.pos == 0)): self.dio.delete()
def tdrange(*args, **kwargs): """Shortcut for `tqdm.contrib.discord.tqdm(range(*args), **kwargs)`.""" return tqdm_discord(range(*args), **kwargs)
# Aliasestqdm = tqdm_discordtrange = tdrange1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Thin wrappers around `itertools`."""import itertoolsimport math
from ..auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}__all__ = [ 'chain', 'product', 'permutations', 'combinations', 'combinations_with_replacement', 'batched']
def chain(*iterables, total=None, tqdm_class=tqdm_auto, **kwargs): """Equivalent of `itertools.chain`.""" if total is None: try: total = sum(map(len, iterables)) except (TypeError, AttributeError): pass return tqdm_class(itertools.chain(*iterables), total=total, **kwargs)
def product(*iterables, repeat=1, total=None, tqdm_class=tqdm_auto, **kwargs): """Equivalent of `itertools.product`.""" if total is None: try: lens = list(map(len, iterables)) except (TypeError, AttributeError): pass else: total = math.prod(lens) ** repeat yield from tqdm_class(itertools.product(*iterables, repeat=repeat), total=total, **kwargs)
def permutations(iterable, r=None, total=None, tqdm_class=tqdm_auto, **kwargs): """Equivalent of `itertools.permutations`.""" if total is None: try: n = len(iterable) except (TypeError, AttributeError): pass else: r = n if r is None else r if r > n: total = 0 else: total = math.perm(n, r) return tqdm_class(itertools.permutations(iterable, r), total=total, **kwargs)
def combinations(iterable, r, total=None, tqdm_class=tqdm_auto, **kwargs): """Equivalent of `itertools.combinations`.""" if total is None: try: n = len(iterable) except (TypeError, AttributeError): pass else: if r > n: total = 0 else: total = math.comb(n, r) return tqdm_class(itertools.combinations(iterable, r), total=total, **kwargs)
def combinations_with_replacement(iterable, r, total=None, tqdm_class=tqdm_auto, **kwargs): """Equivalent of `itertools.combinations_with_replacement`.""" if total is None: try: n = len(iterable) except (TypeError, AttributeError): pass else: total = 1 for i in range(n+r-1, n-1, -1): total *= i for i in range(1, r+1): total //= i return tqdm_class(itertools.combinations_with_replacement(iterable, r), total=total, **kwargs)
def batched(iterable, n, total=None, tqdm_class=tqdm_auto, **kwargs): """Equivalent of `itertools.batched`.""" if total is None: try: total = len(iterable) except (TypeError, AttributeError): pass return tqdm_class(itertools.batched(iterable, n), unit_scale=n, total=(total+n-1) // n if total is not None else None, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Helper functionality for interoperability with stdlib `logging`."""import loggingimport sysfrom contextlib import contextmanager
try: from typing import Iterator, List, Optional, Type # noqa: F401, pylint: disable=unused-importexcept ImportError: pass
from ..std import tqdm as std_tqdm
class _TqdmLoggingHandler(logging.StreamHandler): def __init__( self, tqdm_class=std_tqdm # type: Type[std_tqdm] ): super().__init__() self.tqdm_class = tqdm_class
def emit(self, record): try: msg = self.format(record) self.tqdm_class.write(msg, file=self.stream) self.flush() except (KeyboardInterrupt, SystemExit): raise except: # noqa pylint: disable=bare-except self.handleError(record)
def _is_console_logging_handler(handler): return (isinstance(handler, logging.StreamHandler) and handler.stream in {sys.stdout, sys.stderr})
def _get_first_found_console_logging_handler(handlers): for handler in handlers: if _is_console_logging_handler(handler): return handler
@contextmanagerdef logging_redirect_tqdm( loggers=None, # type: Optional[List[logging.Logger]], tqdm_class=std_tqdm # type: Type[std_tqdm]): # type: (...) -> Iterator[None] """ Context manager redirecting console logging to `tqdm.write()`, leaving other logging handlers (e.g. log files) unaffected.
Parameters ---------- loggers : list, optional Which handlers to redirect (default: [logging.root]). tqdm_class : optional
Example ------- ```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 ``` """ if loggers is None: loggers = [logging.root] original_handlers_list = [logger.handlers for logger in loggers] try: for logger in loggers: tqdm_handler = _TqdmLoggingHandler(tqdm_class) orig_handler = _get_first_found_console_logging_handler(logger.handlers) if orig_handler is not None: tqdm_handler.setFormatter(orig_handler.formatter) tqdm_handler.stream = orig_handler.stream for log_filter in orig_handler.filters: tqdm_handler.addFilter(log_filter) logger.handlers = [ handler for handler in logger.handlers if not _is_console_logging_handler(handler)] + [tqdm_handler] yield finally: for logger, original_handlers in zip(loggers, original_handlers_list): logger.handlers = original_handlers
@contextmanagerdef tqdm_logging_redirect( *args, # loggers=None, # type: Optional[List[logging.Logger]] # tqdm=None, # type: Optional[Type[tqdm.tqdm]] **kwargs): # type: (...) -> Iterator[None] """ Convenience shortcut for: ```python with tqdm_class(*args, **tqdm_kwargs) as pbar: with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): yield pbar ```
Parameters ---------- tqdm_class : optional, (default: tqdm.std.tqdm). loggers : optional, list. **tqdm_kwargs : passed to `tqdm_class`. """ tqdm_kwargs = kwargs.copy() loggers = tqdm_kwargs.pop('loggers', None) tqdm_class = tqdm_kwargs.pop('tqdm_class', std_tqdm) with tqdm_class(*args, **tqdm_kwargs) as pbar: with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): yield pbar123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Sends updates to a Slack app.
Usage:>>> from tqdm.contrib.slack import tqdm, trange>>> for i in trange(10, token='{token}', channel='{channel}'):... ...
"""import logging
try: from slack_sdk import WebClientexcept ImportError: raise ImportError("Please `pip install slack-sdk`")
from ..auto import tqdm as tqdm_autofrom ..utils import envwrapfrom .utils_worker import MonoWorker
__author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]}__all__ = ['SlackIO', 'tqdm_slack', 'tsrange', 'tqdm', 'trange']
class SlackIO(MonoWorker): """Non-blocking file-like IO using a Slack app.""" def __init__(self, token, channel): """Creates a new message in the given `channel`.""" super().__init__() self.client = WebClient(token=token) self.text = self.__class__.__name__ try: self.message = self.client.chat_postMessage(channel=channel, text=self.text) except Exception as e: tqdm_auto.write(str(e)) self.message = None
def write(self, s): """Replaces internal `message`'s text with `s`.""" if not s: s = "..." s = s.replace('\r', '').strip() if s == self.text: return # skip duplicate message message = self.message if message is None: return self.text = s try: future = self.submit(self.client.chat_update, channel=message['channel'], ts=message['ts'], text='`' + s + '`') except Exception as e: tqdm_auto.write(str(e)) else: return future
class tqdm_slack(tqdm_auto): # pylint: disable=inconsistent-mro """ Standard `tqdm.auto.tqdm` but also sends updates to a Slack app. May take a few seconds to create (`__init__`).
- create a Slack app with the `chat:write` scope & invite it to a channel: <https://api.slack.com/authentication/basics> - copy the bot `{token}` & `{channel}` and paste below >>> from tqdm.contrib.slack import tqdm, trange >>> for i in tqdm(iterable, token='{token}', channel='{channel}'): ... ... """ @envwrap("tqdm", "slack", is_method=True) def __init__(self, *args, token=None, channel=None, **kwargs): """ Parameters ---------- token : str, required. Slack token [default: ${TQDM_SLACK_TOKEN}]. channel : int, required. Slack channel [default: ${TQDM_SLACK_CHANNEL}]. mininterval : float, optional. Minimum of [default: 1.5] to avoid rate limit.
See `tqdm.auto.tqdm.__init__` for other parameters. """ if not kwargs.get('disable'): kwargs = kwargs.copy() logging.getLogger("HTTPClient").setLevel(logging.WARNING) self.sio = SlackIO(token, channel) kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5)) super().__init__(*args, **kwargs)
def display(self, **kwargs): # pylint: disable=arguments-differ super().display(**kwargs) fmt = self.format_dict if fmt.get('bar_format', None): fmt['bar_format'] = fmt['bar_format'].replace( '<bar/>', '`{bar:10}`').replace('{bar}', '`{bar:10u}`') elif self.total: fmt['bar_format'] = '{l_bar}`{bar:10}`{r_bar}' if fmt['ascii'] is False: fmt['ascii'] = [":black_square:", ":small_blue_diamond:", ":large_blue_diamond:", ":large_blue_square:"] fmt['ncols'] = 336 self.sio.write(self.format_meter(**fmt))
def clear(self, *args, **kwargs): super().clear(*args, **kwargs) if not self.disable: self.sio.write("")
def tsrange(*args, **kwargs): """Shortcut for `tqdm.contrib.slack.tqdm(range(*args), **kwargs)`.""" return tqdm_slack(range(*args), **kwargs)
# Aliasestqdm = tqdm_slacktrange = tsrange123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Sends updates to a Telegram bot.
Usage:>>> from tqdm.contrib.telegram import tqdm, trange>>> for i in trange(10, token='{token}', chat_id='{chat_id}'):... ...
"""from warnings import warn
from requests import Session
from ..auto import tqdm as tqdm_autofrom ..std import TqdmWarningfrom ..utils import envwrapfrom .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
class TelegramIO(MonoWorker): """Non-blocking file-like IO using a Telegram Bot.""" API = 'https://api.telegram.org/bot'
def __init__(self, token, chat_id): """Creates a new message in the given `chat_id`.""" super().__init__() self.token = token self.chat_id = chat_id self.session = Session() self.text = self.__class__.__name__ self.message_id # pylint: disable=pointless-statement
@property def message_id(self): if hasattr(self, '_message_id'): return self._message_id # pylint: disable=access-member-before-definition try: req = self.session.post( f'{self.API}{self.token}/sendMessage', data={'text': f"`{self.text}`", 'chat_id': self.chat_id, 'parse_mode': 'MarkdownV2'}) res = req.json() req.raise_for_status() except Exception as e: if req.status_code == 429: warn("Creation rate limit: try increasing `mininterval`.", TqdmWarning, stacklevel=2) else: tqdm_auto.write(str(e)) else: self._message_id = res['result']['message_id'] return self._message_id
def write(self, s): """Replaces internal `message_id`'s text with `s`.""" if not s: s = "..." s = s.replace('\r', '').strip() if s == self.text: return # avoid duplicate message Bot error message_id = self.message_id if message_id is None: return self.text = s try: future = self.submit( self.session.post, f'{self.API}{self.token}/editMessageText', data={'text': f"`{s}`", 'chat_id': self.chat_id, 'message_id': message_id, 'parse_mode': 'MarkdownV2'}) except Exception as e: tqdm_auto.write(str(e)) else: return future
def delete(self): """Deletes internal `message_id`.""" try: future = self.submit( self.session.post, '{self.API}{self.token}/deleteMessage', data={'chat_id': self.chat_id, 'message_id': self.message_id}) except Exception as e: tqdm_auto.write(str(e)) else: return future
class tqdm_telegram(tqdm_auto): # pylint: disable=inconsistent-mro """ Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot. May take a few seconds to create (`__init__`).
- create a bot <https://core.telegram.org/bots#6-botfather> - copy its `{token}` - add the bot to a chat and send it a message such as `/start` - go to <https://api.telegram.org/bot`{token}`/getUpdates> to find out the `{chat_id}` - paste the `{token}` & `{chat_id}` below
>>> from tqdm.contrib.telegram import tqdm, trange >>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'): ... ... """ @envwrap("tqdm", "telegram", is_method=True) def __init__(self, *args, token=None, chat_id=None, **kwargs): """ Parameters ---------- token : str, required. Telegram token [default: ${TQDM_TELEGRAM_TOKEN}]. chat_id : str, required. Telegram chat ID [default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters. """ if not kwargs.get('disable'): kwargs = kwargs.copy() self.tgio = TelegramIO(token, chat_id) super().__init__(*args, **kwargs)
def display(self, **kwargs): # pylint: disable=arguments-differ super().display(**kwargs) fmt = self.format_dict if fmt.get('bar_format', None): fmt['bar_format'] = fmt['bar_format'].replace( '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}') self.tgio.write(self.format_meter(**fmt))
def clear(self, *args, **kwargs): super().clear(*args, **kwargs) if not self.disable: self.tgio.write("")
def close(self): if self.disable: return super().close() if not (self.leave or (self.leave is None and self.pos == 0)): self.tgio.delete()
def ttgrange(*args, **kwargs): """Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`.""" return tqdm_telegram(range(*args), **kwargs)
# Aliasestqdm = tqdm_telegramtrange = ttgrange1234567891011121314151617181920212223242526272829303132333435363738"""IO/concurrency helpers for `tqdm.contrib`."""from collections import dequefrom concurrent.futures import ThreadPoolExecutor
from ..auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['MonoWorker']
class MonoWorker: """ Supports one running task and one waiting task. The waiting task is the most recent submitted (others are discarded). """ def __init__(self): self.pool = ThreadPoolExecutor(max_workers=1) self.futures = deque([], 2)
def submit(self, func, *args, **kwargs): """`func(*args, **kwargs)` may replace currently waiting task.""" futures = self.futures if len(futures) == futures.maxlen: running = futures.popleft() if not running.done(): if len(futures): # clear waiting waiting = futures.pop() waiting.cancel() futures.appendleft(running) # re-insert running try: waiting = self.pool.submit(func, *args, **kwargs) except Exception as e: tqdm_auto.write(str(e)) else: futures.append(waiting) return waiting1234567891011121314151617181920212223242526272829303132333435363738394041424344from functools import partial
from dask.callbacks import Callback
from .auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['TqdmCallback']
class TqdmCallback(Callback): """Dask callback for task progress.""" def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto, **tqdm_kwargs): """ Parameters ---------- tqdm_class : optional `tqdm` class to use for bars [default: `tqdm.auto.tqdm`]. tqdm_kwargs : optional Any other arguments used for all bars. """ super().__init__(start=start, pretask=pretask) if tqdm_kwargs: tqdm_class = partial(tqdm_class, **tqdm_kwargs) self.tqdm_class = tqdm_class
def _start_state(self, _, state): self.pbar = self.tqdm_class(total=sum( len(state[k]) for k in ['ready', 'waiting', 'running', 'finished']))
def _posttask(self, *_, **__): self.pbar.update()
def _finish(self, *_, **__): self.pbar.close()
def display(self): """Displays in the current cell in Notebooks.""" container = getattr(self.bar, 'container', None) if container is None: return from .notebook import display display(container)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""Matplotlib GUI progress bar decorator for iterators.
Usage:>>> from tqdm.gui import trange, tqdm>>> for i in trange(10):... ..."""# future division is important to divide integers and get as# a result precise floating numbers (instead of truncated int)import refrom warnings import warn
# to inherit from the tqdm classfrom .std import TqdmExperimentalWarningfrom .std import tqdm as std_tqdm
# import compatibility functions and utilities
__author__ = {"github.com/": ["casperdcl", "lrq3000"]}__all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
class tqdm_gui(std_tqdm): # pragma: no cover """Experimental Matplotlib GUI version of tqdm!""" # TODO: @classmethod: write() on GUI? def __init__(self, *args, **kwargs): from collections import deque
import matplotlib as mpl import matplotlib.pyplot as plt kwargs = kwargs.copy() kwargs['gui'] = True colour = kwargs.pop('colour', 'g') super().__init__(*args, **kwargs)
if self.disable: return
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) self.mpl = mpl self.plt = plt
# Remember if external environment uses toolbars self.toolbar = self.mpl.rcParams['toolbar'] self.mpl.rcParams['toolbar'] = 'None'
self.mininterval = max(self.mininterval, 0.5) self.fig, ax = plt.subplots(figsize=(9, 2.2)) # self.fig.subplots_adjust(bottom=0.2) total = self.__len__() # avoids TypeError on None #971 if total is not None: self.xdata = [] self.ydata = [] self.zdata = [] else: self.xdata = deque([]) self.ydata = deque([]) self.zdata = deque([]) self.line1, = ax.plot(self.xdata, self.ydata, color='b') self.line2, = ax.plot(self.xdata, self.zdata, color='k') ax.set_ylim(0, 0.001) if total is not None: ax.set_xlim(0, 100) ax.set_xlabel("percent") self.fig.legend((self.line1, self.line2), ("cur", "est"), loc='center right') # progress bar self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour) else: # ax.set_xlim(-60, 0) ax.set_xlim(0, 60) ax.invert_xaxis() ax.set_xlabel("seconds") ax.legend(("cur", "est"), loc='lower left') ax.grid() # ax.set_xlabel('seconds') ax.set_ylabel((self.unit if self.unit else "it") + "/s") if self.unit_scale: plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.yaxis.get_offset_text().set_x(-0.15)
# Remember if external environment is interactive self.wasion = plt.isinteractive() plt.ion() self.ax = ax
def close(self): if self.disable: return
self.disable = True
with self.get_lock(): self._instances.remove(self)
# Restore toolbars self.mpl.rcParams['toolbar'] = self.toolbar # Return to non-interactive mode if not self.wasion: self.plt.ioff() if self.leave: self.display() else: self.plt.close(self.fig)
def clear(self, *_, **__): pass
def display(self, *_, **__): n = self.n cur_t = self._time() elapsed = cur_t - self.start_t delta_it = n - self.last_print_n delta_t = cur_t - self.last_print_t
# Inline due to multiple calls total = self.total xdata = self.xdata ydata = self.ydata zdata = self.zdata ax = self.ax line1 = self.line1 line2 = self.line2 hspan = getattr(self, 'hspan', None) # instantaneous rate y = delta_it / delta_t # overall rate z = n / elapsed # update line data xdata.append(n * 100.0 / total if total else cur_t) ydata.append(y) zdata.append(z)
# Discard old values # xmin, xmax = ax.get_xlim() # if (not total) and elapsed > xmin * 1.1: if (not total) and elapsed > 66: xdata.popleft() ydata.popleft() zdata.popleft()
ymin, ymax = ax.get_ylim() if y > ymax or z > ymax: ymax = 1.1 * y ax.set_ylim(ymin, ymax) ax.figure.canvas.draw()
if total: line1.set_data(xdata, ydata) line2.set_data(xdata, zdata) if hspan: hspan.set_xy((0, ymin)) hspan.set_height(ymax - ymin) hspan.set_width(n / total) else: t_ago = [cur_t - i for i in xdata] line1.set_data(t_ago, ydata) line2.set_data(t_ago, zdata)
d = self.format_dict # remove {bar} d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace( "{bar}", "<bar/>") msg = self.format_meter(**d) if '<bar/>' in msg: msg = "".join(re.split(r'\|?<bar/>\|?', msg, maxsplit=1)) ax.set_title(msg, fontname="DejaVu Sans Mono", fontsize=11) self.plt.pause(1e-9)
def tgrange(*args, **kwargs): """Shortcut for `tqdm.gui.tqdm(range(*args), **kwargs)`.""" return tqdm_gui(range(*args), **kwargs)
# Aliasestqdm = tqdm_guitrange = tgrange123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123from copy import copyfrom functools import partial
from .auto import tqdm as tqdm_auto
try: import kerasexcept (ImportError, AttributeError) as e: try: from tensorflow import keras except ImportError: raise e__author__ = {"github.com/": ["casperdcl"]}__all__ = ['TqdmCallback']
class TqdmCallback(keras.callbacks.Callback): """Keras callback for epoch and batch progress.""" @staticmethod def bar2callback(bar, pop=None, delta=(lambda logs: 1)): def callback(_, logs=None): n = delta(logs) if logs: if pop: logs = copy(logs) for i in pop: logs.pop(i, 0) bar.set_postfix(logs, refresh=False) bar.update(n)
return callback
def __init__(self, epochs=None, data_size=None, batch_size=None, verbose=1, tqdm_class=tqdm_auto, **tqdm_kwargs): """ Parameters ---------- epochs : int, optional data_size : int, optional Number of training pairs. batch_size : int, optional Number of training pairs per batch. verbose : int 0: epoch, 1: batch (transient), 2: batch. [default: 1]. Will be set to `0` unless both `data_size` and `batch_size` are given. tqdm_class : optional `tqdm` class to use for bars [default: `tqdm.auto.tqdm`]. tqdm_kwargs : optional Any other arguments used for all bars. """ if tqdm_kwargs: tqdm_class = partial(tqdm_class, **tqdm_kwargs) self.tqdm_class = tqdm_class self.epoch_bar = tqdm_class(total=epochs, unit='epoch') self.on_epoch_end = self.bar2callback(self.epoch_bar) if data_size and batch_size: self.batches = batches = (data_size + batch_size - 1) // batch_size else: self.batches = batches = None self.verbose = verbose if verbose == 1: self.batch_bar = tqdm_class(total=batches, unit='batch', leave=False) self.on_batch_end = self.bar2callback( self.batch_bar, pop=['batch', 'size'], delta=lambda logs: logs.get('size', 1))
def on_train_begin(self, *_, **__): params = self.params.get auto_total = params('epochs', params('nb_epoch', None)) if auto_total is not None and auto_total != self.epoch_bar.total: self.epoch_bar.reset(total=auto_total)
def on_epoch_begin(self, epoch, *_, **__): if self.epoch_bar.n < epoch: ebar = self.epoch_bar ebar.n = ebar.last_print_n = ebar.initial = epoch if self.verbose: params = self.params.get total = params('samples', params( 'nb_sample', params('steps', None))) or self.batches if self.verbose == 2: if hasattr(self, 'batch_bar'): self.batch_bar.close() self.batch_bar = self.tqdm_class( total=total, unit='batch', leave=True, unit_scale=1 / (params('batch_size', 1) or 1)) self.on_batch_end = self.bar2callback( self.batch_bar, pop=['batch', 'size'], delta=lambda logs: logs.get('size', 1)) elif self.verbose == 1: self.batch_bar.unit_scale = 1 / (params('batch_size', 1) or 1) self.batch_bar.reset(total=total) else: raise KeyError('Unknown verbosity')
def on_train_end(self, *_, **__): if hasattr(self, 'batch_bar'): self.batch_bar.close() self.epoch_bar.close()
def display(self): """Displays in the current cell in Notebooks.""" container = getattr(self.epoch_bar, 'container', None) if container is None: return from .notebook import display display(container) batch_bar = getattr(self, 'batch_bar', None) if batch_bar is not None: display(batch_bar.container)
@staticmethod def _implements_train_batch_hooks(): return True
@staticmethod def _implements_test_batch_hooks(): return True
@staticmethod def _implements_predict_batch_hooks(): return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317"""IPython/Jupyter Notebook progress bar decorator for iterators.Includes a default `range` iterator printing to `stderr`.
Usage:>>> from tqdm.notebook import trange, tqdm>>> for i in trange(10):... ..."""# import compatibility functions and utilitiesimport reimport sysfrom html import escapefrom weakref import proxy
# to inherit from the tqdm classfrom .std import tqdm as std_tqdm
if True: # pragma: no cover # import IPython/Jupyter base widget and display utilities IPY = 0 try: # IPython 4.x import ipywidgets # noqa: F401, pylint: disable=unused-import IPY = 4 except ImportError: # IPython 3.x / 2.x IPY = 32 import warnings with warnings.catch_warnings(): warnings.filterwarnings( 'ignore', message=".*The `IPython.html` package has been deprecated.*") try: import IPython.html.widgets except ImportError: pass else: ipywidgets = IPython.html.widgets
try: # IPython 4.x / 3.x if IPY == 32: from IPython.html.widgets import HTML from IPython.html.widgets import FloatProgress as IProgress from IPython.html.widgets import HBox IPY = 3 else: from ipywidgets import HTML from ipywidgets import FloatProgress as IProgress from ipywidgets import HBox except ImportError: try: # IPython 2.x from IPython.html.widgets import HTML from IPython.html.widgets import ContainerWidget as HBox from IPython.html.widgets import FloatProgressWidget as IProgress IPY = 2 except ImportError: IPY = 0 IProgress = None HBox = object
try: from IPython.display import display # , clear_output except ImportError: pass
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}__all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange']WARN_NOIPYW = ("IProgress not found. Please update jupyter and ipywidgets." " See https://ipywidgets.readthedocs.io/en/stable" "/user_install.html")
class TqdmHBox(HBox): """`ipywidgets.HBox` with a pretty representation""" def _json_(self, pretty=None): pbar = getattr(self, 'pbar', None) if pbar is None: return {} d = pbar.format_dict if pretty is not None: d["ascii"] = not pretty return d
def __repr__(self, pretty=False): pbar = getattr(self, 'pbar', None) if pbar is None: return super().__repr__() return pbar.format_meter(**self._json_(pretty))
def _repr_pretty_(self, pp, *_, **__): pp.text(self.__repr__(True))
class tqdm_notebook(std_tqdm): """ Experimental IPython/Jupyter Notebook widget using tqdm! """ @staticmethod def status_printer(_, total=None, desc=None, ncols=None): """ Manage the printing of an IPython/Jupyter Notebook progress bar widget. """ # Fallback to text bar if there's no total # DEPRECATED: replaced with an 'info' style bar # if not total: # return super(tqdm_notebook, tqdm_notebook).status_printer(file)
# fp = file
# Prepare IPython progress bar if IProgress is None: # #187 #451 #558 #872 raise ImportError(WARN_NOIPYW) if total: pbar = IProgress(min=0, max=total) else: # No total? Show info style bar with no progress tqdm status pbar = IProgress(min=0, max=1) pbar.value = 1 pbar.bar_style = 'info' if ncols is None: pbar.layout.width = "20px"
ltext = HTML() rtext = HTML() if desc: ltext.value = desc container = TqdmHBox(children=[ltext, pbar, rtext]) # Prepare layout if ncols is not None: # use default style of ipywidgets # ncols could be 100, "100px", "100%" ncols = str(ncols) # ipywidgets only accepts string try: if int(ncols) > 0: # isnumeric and positive ncols += 'px' except ValueError: pass pbar.layout.flex = '2' container.layout.width = ncols container.layout.display = 'inline-flex' container.layout.flex_flow = 'row wrap'
return container
def display(self, msg=None, pos=None, # additional signals close=False, bar_style=None, check_delay=True): # Note: contrary to native tqdm, msg='' does NOT clear bar # goal is to keep all infos if error happens so user knows # at which iteration the loop failed.
# Clear previous output (really necessary?) # clear_output(wait=1)
if not msg and not close: d = self.format_dict # remove {bar} d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace( "{bar}", "<bar/>") msg = self.format_meter(**d)
ltext, pbar, rtext = self.container.children pbar.value = self.n
if msg: msg = msg.replace(' ', '\u2007') # fix html space padding # html escape special characters (like '&') if '<bar/>' in msg: left, right = map(escape, re.split(r'\|?<bar/>\|?', msg, maxsplit=1)) else: left, right = '', escape(msg)
# Update description ltext.value = left # never clear the bar (signal: msg='') if right: rtext.value = right
# Change bar style if bar_style: # Hack-ish way to avoid the danger bar_style being overridden by # success because the bar gets closed after the error... if pbar.bar_style != 'danger' or bar_style != 'success': pbar.bar_style = bar_style
# Special signal to close the bar if close and pbar.bar_style != 'danger': # hide only if no error try: self.container.close() except AttributeError: self.container.visible = False self.container.layout.visibility = 'hidden' # IPYW>=8
if check_delay and self.delay > 0 and not self.displayed: display(self.container) self.displayed = True
@property def colour(self): if hasattr(self, 'container'): return self.container.children[-2].style.bar_color
@colour.setter def colour(self, bar_color): if hasattr(self, 'container'): self.container.children[-2].style.bar_color = bar_color
def __init__(self, *args, **kwargs): """ Supports the usual `tqdm.tqdm` parameters as well as those listed below.
Parameters ---------- display : Whether to call `display(self.container)` immediately [default: True]. """ kwargs = kwargs.copy() # Setup default output file_kwarg = kwargs.get('file', sys.stderr) if file_kwarg is sys.stderr or file_kwarg is None: kwargs['file'] = sys.stdout # avoid the red block in IPython
# Initialize parent class + avoid printing by using gui=True kwargs['gui'] = True # convert disable = None to False kwargs['disable'] = bool(kwargs.get('disable', False)) colour = kwargs.pop('colour', None) display_here = kwargs.pop('display', True) super().__init__(*args, **kwargs) if self.disable or not kwargs['gui']: self.disp = lambda *_, **__: None return
# Get bar width self.ncols = '100%' if self.dynamic_ncols else kwargs.get("ncols", None)
# Replace with IPython progress bar display (with correct total) unit_scale = 1 if self.unit_scale is True else self.unit_scale or 1 total = self.total * unit_scale if self.total else self.total self.container = self.status_printer(self.fp, total, self.desc, self.ncols) self.container.pbar = proxy(self) self.displayed = False if display_here and self.delay <= 0: display(self.container) self.displayed = True self.disp = self.display self.colour = colour
# Print initial bar state if not self.disable: self.display(check_delay=False)
def __iter__(self): try: it = super().__iter__() yield from it # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt except: # NOQA self.disp(bar_style='danger') raise # NB: don't `finally: close()` # since this could be a shared bar which the user will `reset()`
def update(self, n=1): try: return super().update(n=n) # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt except: # NOQA # cannot catch KeyboardInterrupt when using manual tqdm # as the interrupt will most likely happen on another statement self.disp(bar_style='danger') raise # NB: don't `finally: close()` # since this could be a shared bar which the user will `reset()`
def close(self): if self.disable: return super().close() # Try to detect if there was an error or KeyboardInterrupt # in manual mode: if n < total, things probably got wrong if self.total and self.n < self.total: self.disp(bar_style='danger', check_delay=False) else: if self.leave: self.disp(bar_style='success', check_delay=False) else: self.disp(close=True, check_delay=False)
def clear(self, *_, **__): pass
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. """ if self.disable: return super().reset(total=total) _, pbar, _ = self.container.children pbar.bar_style = '' if total is not None: pbar.max = total if not self.total and self.ncols is None: # no longer unknown total pbar.layout.width = None # reset width return super().reset(total=total)
def tnrange(*args, **kwargs): """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`.""" return tqdm_notebook(range(*args), **kwargs)
# Aliasestqdm = tqdm_notebooktrange = tnrange123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""`rich.progress` decorator for iterators.
Usage:>>> from tqdm.rich import trange, tqdm>>> for i in trange(10):... ..."""from warnings import warn
from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
from .std import TqdmExperimentalWarningfrom .std import tqdm as std_tqdm
__author__ = {"github.com/": ["casperdcl"]}__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
class FractionColumn(ProgressColumn): """Renders completed/total, e.g. '0.5/2.3 G'.""" def __init__(self, unit_scale=False, unit_divisor=1000): self.unit_scale = unit_scale self.unit_divisor = unit_divisor super().__init__()
def render(self, task): """Calculate common unit for completed and total.""" completed = int(task.completed) # total is None when the iterable has no length (e.g. a generator) total = int(task.total) if task.total is not None else None base = total if total is not None else completed if self.unit_scale: unit, suffix = filesize.pick_unit_and_suffix( base, ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], self.unit_divisor, ) else: unit, suffix = filesize.pick_unit_and_suffix(base, [""], 1) precision = 0 if unit == 1 else 1 total_str = f"{total/unit:,.{precision}f}" if total is not None else "?" return Text( f"{completed/unit:,.{precision}f}/{total_str} {suffix}", style="progress.download")
class RateColumn(ProgressColumn): """Renders human readable transfer speed.""" def __init__(self, unit="", unit_scale=False, unit_divisor=1000): self.unit = unit self.unit_scale = unit_scale self.unit_divisor = unit_divisor super().__init__()
def render(self, task): """Show data transfer speed.""" speed = task.speed if speed is None: return Text(f"? {self.unit}/s", style="progress.data.speed") if self.unit_scale: unit, suffix = filesize.pick_unit_and_suffix( speed, ["", "K", "M", "G", "T", "P", "E", "Z", "Y"], self.unit_divisor, ) else: unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1) precision = 0 if unit == 1 else 1 return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s", style="progress.data.speed")
class tqdm_rich(std_tqdm): # pragma: no cover """Experimental rich.progress GUI version of tqdm!""" # TODO: @classmethod: write()? def __init__(self, *args, **kwargs): """ This class accepts the following parameters *in addition* to the parameters accepted by `tqdm`.
Parameters ---------- progress : tuple, optional arguments for `rich.progress.Progress()`. options : dict, optional keyword arguments for `rich.progress.Progress()`. """ kwargs = kwargs.copy() kwargs['gui'] = True # convert disable = None to False kwargs['disable'] = bool(kwargs.get('disable', False)) progress = kwargs.pop('progress', None) options = kwargs.pop('options', {}).copy() super().__init__(*args, **kwargs)
if self.disable: return
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) d = self.format_dict if progress is None: progress = ( "[progress.description]{task.description}" "[progress.percentage]{task.percentage:>4.0f}%", BarColumn(bar_width=None), FractionColumn( unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']), "[", TimeElapsedColumn(), "<", TimeRemainingColumn(), ",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']), "]" ) options.setdefault('transient', not self.leave) self._prog = Progress(*progress, **options) self._prog.__enter__() self._task_id = self._prog.add_task(self.desc or "", **d)
def close(self): if self.disable: return self.display() # print 100%, vis #1306 super().close() self._prog.__exit__(None, None, None)
def clear(self, *_, **__): pass
def display(self, *_, **__): if not hasattr(self, '_task_id'): return self._prog.update(self._task_id, completed=self.n, description=self.desc)
def reset(self, total=None): """ Resets to 0 iterations for repeated use.
Parameters ---------- total : int or float, optional. Total to use for the new bar. """ if hasattr(self, '_prog'): self._prog.reset(total=total) super().reset(total=total)
def trrange(*args, **kwargs): """Shortcut for `tqdm.rich.tqdm(range(*args), **kwargs)`.""" return tqdm_rich(range(*args), **kwargs)
# Aliasestqdm = tqdm_richtrange = trrange123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533"""Customisable progress bar decorator for iterators.Includes a default `range` iterator printing to `stderr`.
Usage:>>> from tqdm import trange, tqdm>>> for i in trange(10):... ..."""import sysfrom collections import OrderedDict, defaultdictfrom contextlib import contextmanagerfrom datetime import datetime, timedelta, timezonefrom numbers import Numberfrom time import timefrom warnings import warnfrom weakref import WeakSet
from ._monitor import TMonitorfrom .utils import ( CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper, _is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim, envwrap)
__author__ = "https://github.com/tqdm/tqdm#contributions"__all__ = ['tqdm', 'trange', 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning', 'TqdmExperimentalWarning', 'TqdmDeprecationWarning', 'TqdmMonitorWarning']
class TqdmTypeError(TypeError): pass
class TqdmKeyError(KeyError): pass
class TqdmWarning(Warning): """base class for all tqdm warnings.
Used for non-external-code-breaking errors, such as garbled printing. """ def __init__(self, msg, fp_write=None): # noqa: B042 if fp_write is not None: fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n') else: super().__init__(msg)
class TqdmExperimentalWarning(TqdmWarning, FutureWarning): """beta feature, unstable API and behaviour"""
class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning): """may be removed in a future release""" # not suppressed if raised
class TqdmMonitorWarning(TqdmWarning, RuntimeWarning): """tqdm monitor errors which do not affect external functionality"""
def TRLock(*args, **kwargs): """threading RLock""" try: from threading import RLock return RLock(*args, **kwargs) except (ImportError, OSError): # pragma: no cover pass
class TqdmDefaultWriteLock: """ Provide a default write lock for thread and multiprocessing safety. Works only on platforms supporting `fork` (so Windows is excluded). You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance before forking in order for the write lock to work. On Windows, you need to supply the lock from the parent to the children as an argument to joblib or the parallelism lib you use. """ # global thread lock so no setup required for multithreading. # NB: Do not create multiprocessing lock as it sets the multiprocessing # context, disallowing `spawn()`/`forkserver()` th_lock = TRLock()
def __init__(self): # Create global parallelism locks to avoid racing issues with parallel # bars works only if fork available (Linux/MacOSX, but not Windows) cls = type(self) root_lock = cls.th_lock if root_lock is not None: root_lock.acquire() cls.create_mp_lock() self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None] if root_lock is not None: root_lock.release()
def acquire(self, *a, **k): for lock in self.locks: lock.acquire(*a, **k)
def release(self): for lock in self.locks[::-1]: # Release in inverse order of acquisition lock.release()
def __enter__(self): self.acquire()
def __exit__(self, *exc): self.release()
@classmethod def create_mp_lock(cls): if not hasattr(cls, 'mp_lock'): try: from multiprocessing import RLock cls.mp_lock = RLock() except (ImportError, OSError): # pragma: no cover cls.mp_lock = None
@classmethod def create_th_lock(cls): assert hasattr(cls, 'th_lock') warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
class Bar: """ `str.format`-able bar with format specifiers: `[width][type]`
- `width` + unspecified (default): use `self.default_len` + `int >= 0`: overrides `self.default_len` + `int < 0`: subtract from `self.default_len` - `type` + `a`: ascii (`charset=self.ASCII` override) + `u`: unicode (`charset=self.UTF` override) + `b`: blank (`charset=" "` override) """ ASCII = " 123456789#" UTF = " " + ''.join(map(chr, range(0x258F, 0x2587, -1))) BLANK = " " COLOUR_RESET = '\x1b[0m' COLOUR_RGB = '\x1b[38;2;%d;%d;%dm' COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m', 'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m', 'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
def __init__(self, frac, default_len=10, charset=UTF, colour=None): if not 0 <= frac <= 1: warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2) frac = max(0, min(1, frac)) assert default_len > 0 self.frac = frac self.default_len = default_len self.charset = charset self.colour = colour
@property def colour(self): return self._colour
@colour.setter def colour(self, value): if not value: self._colour = None return try: if value.upper() in self.COLOURS: self._colour = self.COLOURS[value.upper()] elif value[0] == '#' and len(value) == 7: self._colour = self.COLOUR_RGB % tuple( int(i, 16) for i in (value[1:3], value[3:5], value[5:7])) else: raise KeyError except (KeyError, AttributeError): warn(f"Unknown colour ({value}); valid choices:" f" [hex (#00ff00), {', '.join(self.COLOURS)}]", TqdmWarning, stacklevel=2) self._colour = None
def __format__(self, format_spec): if format_spec: _type = format_spec[-1].lower() try: charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type] except KeyError: charset = self.charset else: format_spec = format_spec[:-1] if format_spec: N_BARS = int(format_spec) if N_BARS < 0: N_BARS += self.default_len else: N_BARS = self.default_len else: charset = self.charset N_BARS = self.default_len
nsyms = len(charset) - 1 bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
res = charset[-1] * bar_length if bar_length < N_BARS: # whitespace padding res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1) return self.colour + res + self.COLOUR_RESET if self.colour else res
class EMA: """ Exponential moving average: smoothing to give progressively lower weights to older values.
Parameters ---------- smoothing : float, optional Smoothing factor in range [0, 1], [default: 0.3]. Increase to give more weight to recent values. Ranges from 0 (yields old value) to 1 (yields new value). """ def __init__(self, smoothing=0.3): self.alpha = smoothing self.last = 0 self.calls = 0
def __call__(self, x=None): """ Parameters ---------- x : float New value to include in EMA. """ beta = 1 - self.alpha if x is not None: self.last = self.alpha * x + beta * self.last self.calls += 1 return self.last / (1 - beta ** self.calls) if self.calls else self.last
class tqdm(Comparable): """ 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.
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. gui : bool, optional WARNING: internal parameter - do not use. Use tqdm.gui.tqdm(...) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False].
Returns ------- out : decorated iterator. """
monitor_interval = 10 # set to 0 to disable the thread monitor = None _instances = WeakSet()
@staticmethod def format_sizeof(num, suffix='', divisor=1000): """ Formats a number (greater than unity) with SI Order of Magnitude prefixes.
Parameters ---------- num : float Number ( >= 1) to format. suffix : str, optional Post-postfix [default: '']. divisor : float, optional Divisor between prefixes [default: 1000].
Returns ------- out : str Number with Order of Magnitude SI unit postfix. """ for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 999.5: if abs(num) < 99.95: if abs(num) < 9.995: return f'{num:1.2f}{unit}{suffix}' return f'{num:2.1f}{unit}{suffix}' return f'{num:3.0f}{unit}{suffix}' num /= divisor return f'{num:3.1f}Y{suffix}'
@staticmethod def format_interval(t): """ Formats a number of seconds as a clock time, [H:]MM:SS
Parameters ---------- t : int Number of seconds.
Returns ------- out : str [H:]MM:SS """ sign = '-' if t < 0 else '' mins, s = divmod(abs(int(t)), 60) h, m = divmod(mins, 60) return f'{sign}{h:d}:{m:02d}:{s:02d}' if h else f'{sign}{m:02d}:{s:02d}'
@staticmethod def format_num(n): """ Intelligent scientific notation (.3g).
Parameters ---------- n : int or float or Numeric A Number.
Returns ------- out : str Formatted number. """ f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-') n = str(n) return f if len(f) < len(n) else n
@staticmethod def status_printer(file): """ Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh). """ fp = file fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover if fp in (sys.stderr, sys.stdout): getattr(sys.stderr, 'flush', lambda: None)() getattr(sys.stdout, 'flush', lambda: None)()
def fp_write(s): fp.write(str(s)) fp_flush()
last_len = [0]
def print_status(s): len_s = disp_len(s) fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0))) last_len[0] = len_s
return print_status
@staticmethod def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, # pylint: disable=redefined-builtin unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs): """ Return a string-based progress bar given some parameters
Parameters ---------- n : int or float Number of finished iterations. total : int or float The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA). elapsed : float Number of seconds passed since start. ncols : int, optional The width of the entire output message. If specified, dynamically resizes `{bar}` to stay within this bound [default: None]. If `0`, will not print any bar (only stats). The fallback is `{bar:10}`. prefix : str, optional Prefix message (included in total width) [default: '']. Use as {desc} in bar_format string. ascii : bool, optional or str, optional If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters " 123456789#". unit : str, optional The iteration unit [default: 'it']. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. rate : float, optional Manual override for iteration rate. If [default: None], uses n/elapsed. 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. postfix : *, optional Similar to `prefix`, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ', ' + postfix. However other types are supported (#382). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. initial : int or float, optional The initial counter value [default: 0]. colour : str, optional Bar colour (e.g. 'green', '#00ff00').
Returns ------- out : Formatted meter and stats, ready to display. """
# sanity check: total if total and (n >= (total + 0.5) or total == float("inf")): # allow float imprecision (#849) or inf (#651) total = None
# apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): if total: total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt unit_scale = False
elapsed_str = tqdm.format_interval(elapsed)
# if unspecified, attempt to use rate = average speed # (we allow manual override since predicting time is an arcane art) if rate is None and elapsed: rate = (n - initial) / elapsed inv_rate = 1 / rate if rate else None format_sizeof = tqdm.format_sizeof rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}') if rate else '?') + unit + '/s' rate_inv_fmt = ( (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}') if inv_rate else '?') + 's/' + unit rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
if unit_scale: n_fmt = format_sizeof(n, divisor=unit_divisor) total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?' else: n_fmt = str(n) total_fmt = str(total) if total is not None else '?'
try: postfix = ', ' + postfix if postfix else '' except TypeError: pass
remaining = (total - n) / rate if rate and total else 0 remaining_str = tqdm.format_interval(remaining) if rate else '?' try: eta_dt = (datetime.now() + timedelta(seconds=remaining) if rate and total else datetime.fromtimestamp(0, timezone.utc)) except OverflowError: eta_dt = datetime.max
# format the stats displayed to the left and right sides of the bar if prefix: # old prefix setup work around bool_prefix_colon_already = (prefix[-2:] == ": ") l_bar = prefix if bool_prefix_colon_already else prefix + ": " else: l_bar = ''
r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
# Custom bar formatting # Populate a dict with all available progress indicators format_dict = { # slight extension of self.format_dict 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt, 'elapsed': elapsed_str, 'elapsed_s': elapsed, 'ncols': ncols, 'desc': prefix or '', 'unit': unit, 'rate': inv_rate if inv_rate and inv_rate > 1 else rate, 'rate_fmt': rate_fmt, 'rate_noinv': rate, 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate, 'rate_inv_fmt': rate_inv_fmt, 'postfix': postfix, 'unit_divisor': unit_divisor, 'colour': colour, # plus more useful definitions 'remaining': remaining_str, 'remaining_s': remaining, 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt, **extra_kwargs}
# total is known: we can predict some stats if total: # fractional and percentage progress frac = n / total percentage = frac * 100
l_bar += f'{percentage:3.0f}%|'
if ncols == 0: return l_bar[:-1] + r_bar[1:]
format_dict.update(l_bar=l_bar) if bar_format: format_dict.update(percentage=percentage)
# auto-remove colon for empty `{desc}` if not prefix: bar_format = bar_format.replace("{desc}: ", '') else: bar_format = "{l_bar}{bar}{r_bar}"
full_bar = FormatReplace() nobar = bar_format.format(bar=full_bar, **format_dict) # no `{bar}` if not full_bar.format_called: return disp_trim(nobar, ncols) if ncols else nobar
# Formatting progress bar space available for bar's display full_bar = Bar(frac, max(1, ncols - disp_len(nobar)) if ncols else 10, charset=Bar.ASCII if ascii is True else ascii or Bar.UTF, colour=colour) if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = str(bar_format) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res
elif bar_format: # user-specified bar_format but no total l_bar += '|' format_dict.update(l_bar=l_bar, percentage=0) full_bar = FormatReplace() nobar = bar_format.format(bar=full_bar, **format_dict) if not full_bar.format_called: return disp_trim(nobar, ncols) if ncols else nobar full_bar = Bar(0, max(1, ncols - disp_len(nobar)) if ncols else 10, charset=Bar.BLANK, colour=colour) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res else: # no total: no bar & ETA, just progress stats res = (f'{(prefix + ": ") if prefix else ""}' f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]') return disp_trim(res, ncols) if ncols else res
def __new__(cls, *_, **__): instance = object.__new__(cls) with cls.get_lock(): # also constructs lock if non-existent cls._instances.add(instance) # create monitoring thread if cls.monitor_interval and (cls.monitor is None or not cls.monitor.report()): try: cls.monitor = TMonitor(cls, cls.monitor_interval) except Exception as e: # pragma: nocover warn("tqdm:disabling monitor support" " (monitor_interval = 0) due to:\n" + str(e), TqdmMonitorWarning, stacklevel=2) cls.monitor_interval = 0 return instance
@classmethod def _get_free_pos(cls, instance=None): """Skips specified instance.""" positions = {abs(inst.pos) for inst in cls._instances if inst is not instance and hasattr(inst, "pos")} return min(set(range(len(positions) + 1)).difference(positions))
@classmethod def _decr_instances(cls, instance): """ Remove from list and reposition another unfixed bar to fill the new gap.
This means that by default (where all nested bars are unfixed), order is not maintained but screen flicker/blank space is minimised. (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.) """ with cls._lock: try: cls._instances.remove(instance) except KeyError: # if not instance.gui: # pragma: no cover # raise pass # py2: maybe magically removed already # else: if not instance.gui: last = (instance.nrows or 20) - 1 # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`) instances = list(filter( lambda i: hasattr(i, "pos") and last <= i.pos, cls._instances)) # set first found to current `pos` if instances: inst = min(instances, key=lambda i: i.pos) inst.clear(nolock=True) inst.pos = abs(instance.pos)
@classmethod def write(cls, s, file=None, end="\n", nolock=False): """Print a message via tqdm (without overlap with bars).""" fp = file if file is not None else sys.stdout if fp is None: return with cls.external_write_mode(file=file, nolock=nolock): # Write the message fp.write(s) fp.write(end)
@classmethod @contextmanager def external_write_mode(cls, file=None, nolock=False): """ Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream """ fp = file if file is not None else sys.stdout if fp is None: yield return
try: if not nolock: cls.get_lock().acquire() # Clear all bars inst_cleared = [] for inst in getattr(cls, '_instances', []): # Clear instance if in the target output file # or if write output + tqdm output are both either # sys.stdout or sys.stderr (because both are mixed in terminal) if hasattr(inst, "start_t") and (inst.fp == fp or all( f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))): inst.clear(nolock=True) inst_cleared.append(inst) yield # Force refresh display of bars we cleared for inst in inst_cleared: inst.refresh(nolock=True) finally: if not nolock: cls._lock.release()
@classmethod def set_lock(cls, lock): """Set the global lock.""" cls._lock = lock
@classmethod def get_lock(cls): """Get the global lock. Construct it if it does not exist.""" if not hasattr(cls, '_lock'): cls._lock = TqdmDefaultWriteLock() return cls._lock
@classmethod def pandas(cls, **tqdm_kwargs): """ Registers the current `tqdm` class with pandas.core. ( frame.DataFrame | series.Series | groupby.(generic.)DataFrameGroupBy | groupby.(generic.)SeriesGroupBy ).progress_apply
A new instance will be created every time `progress_apply` is called, and each instance will automatically `close()` upon completion.
Parameters ---------- tqdm_kwargs : arguments for the tqdm instance
Examples -------- >>> import pandas as pd >>> import numpy as np >>> from tqdm import tqdm >>> from tqdm.gui import tqdm as tqdm_gui >>> >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6))) >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc >>> # Now you can use `progress_apply` instead of `apply` >>> df.groupby(0).progress_apply(lambda x: x**2)
References ---------- <https://stackoverflow.com/questions/18603270/\ progress-indicator-during-pandas-operations-python> """ from warnings import catch_warnings, simplefilter
from pandas.core.frame import DataFrame from pandas.core.series import Series try: with catch_warnings(): simplefilter("ignore", category=FutureWarning) from pandas import Panel except ImportError: # pandas>=1.2.0 Panel = None Rolling, Expanding = None, None try: # pandas>=1.0.0 from pandas.core.window.rolling import _Rolling_and_Expanding except ImportError: try: # pandas>=0.18.0 from pandas.core.window import _Rolling_and_Expanding except ImportError: # pandas>=1.2.0 try: # pandas>=1.2.0 from pandas.core.window.expanding import Expanding from pandas.core.window.rolling import Rolling _Rolling_and_Expanding = Rolling, Expanding except ImportError: # pragma: no cover _Rolling_and_Expanding = None try: # pandas>=0.25.0 from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy from pandas.core.groupby.generic import DataFrameGroupBy except ImportError: # pragma: no cover try: # pandas>=0.23.0 from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy except ImportError: from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy try: # pandas>=0.23.0 from pandas.core.groupby.groupby import GroupBy except ImportError: # pragma: no cover from pandas.core.groupby import GroupBy
try: # pandas>=0.23.0 from pandas.core.groupby.groupby import PanelGroupBy except ImportError: try: from pandas.core.groupby import PanelGroupBy except ImportError: # pandas>=0.25.0 PanelGroupBy = None
tqdm_kwargs = tqdm_kwargs.copy() deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
def inner_generator(df_function='apply'): def inner(df, func, *args, **kwargs): """ Parameters ---------- df : (DataFrame|Series)[GroupBy] Data (may be grouped). func : function To be applied on the (grouped) data. **kwargs : optional Transmitted to `df.apply()`. """
# Precompute total iterations total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None)) if total is None: # not grouped if df_function == 'applymap': total = df.size elif isinstance(df, Series): total = len(df) elif (_Rolling_and_Expanding is None or not isinstance(df, _Rolling_and_Expanding)): # DataFrame or Panel axis = kwargs.get('axis', 0) if axis == 'index': axis = 0 elif axis == 'columns': axis = 1 # when axis=0, total is shape[axis1] total = df.size // df.shape[axis]
# Init bar if deprecated_t[0] is not None: t = deprecated_t[0] deprecated_t[0] = None else: t = cls(total=total, **tqdm_kwargs)
if len(args) > 0: # *args intentionally not supported (see #244, #299) TqdmDeprecationWarning( "Except func, normal arguments are intentionally" + " not supported by" + " `(DataFrame|Series|GroupBy).progress_apply`." + " Use keyword arguments instead.", fp_write=getattr(t.fp, 'write', sys.stderr.write))
try: # pandas>=1.3.0,<3.0 from pandas.core.common import is_builtin_func except ImportError: # pandas<1.3.0 is_builtin_func = getattr(df, '_is_builtin_func', lambda f: f) try: func = is_builtin_func(func) except TypeError: pass
# Define bar updating wrapper def wrapper(*args, **kwargs): # update tbar correctly # it seems `pandas apply` calls `func` twice # on the first column/row to decide whether it can # take a fast or slow code path; so stop when t.total==t.n t.update(n=1 if not t.total or t.n < t.total else 0) return func(*args, **kwargs)
# Apply the provided function (in **kwargs) # on the df using our wrapper (which provides bar updating) try: return getattr(df, df_function)(wrapper, **kwargs) finally: t.close()
return inner
# Monkeypatch pandas to provide easy methods # Enable custom tqdm progress in pandas! Series.progress_apply = inner_generator() SeriesGroupBy.progress_apply = inner_generator() Series.progress_map = inner_generator('map') SeriesGroupBy.progress_map = inner_generator('map')
DataFrame.progress_apply = inner_generator() DataFrameGroupBy.progress_apply = inner_generator() DataFrame.progress_applymap = inner_generator('applymap') DataFrame.progress_map = inner_generator('map') DataFrameGroupBy.progress_map = inner_generator('map')
if Panel is not None: Panel.progress_apply = inner_generator() if PanelGroupBy is not None: PanelGroupBy.progress_apply = inner_generator()
GroupBy.progress_apply = inner_generator() GroupBy.progress_aggregate = inner_generator('aggregate') GroupBy.progress_transform = inner_generator('transform')
if Rolling is not None and Expanding is not None: Rolling.progress_apply = inner_generator() Expanding.progress_apply = inner_generator() elif _Rolling_and_Expanding is not None: _Rolling_and_Expanding.progress_apply = inner_generator()
# override defaults via env vars @envwrap("tqdm", is_method=True, types={'total': float, 'ncols': int, 'miniters': float, 'position': int, 'nrows': int}) 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, # pylint: disable=redefined-builtin 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.0, gui=False, **kwargs): """see tqdm.tqdm for arguments""" if file is None: file = sys.stderr
if write_bytes: # Despite coercing unicode into bytes, py2 sys.std* streams # should have bytes written to them. file = SimpleTextIOWrapper( file, encoding=getattr(file, 'encoding', None) or 'utf-8')
file = DisableOnWriteError(file, tqdm_instance=self)
if disable is None and hasattr(file, "isatty") and not file.isatty(): disable = True
if total is None and iterable is not None: try: total = len(iterable) except (TypeError, AttributeError): total = None if total == float("inf"): total = None # same as unknown
if disable: self.iterable = iterable self.disable = disable with self._lock: self.pos = self._get_free_pos(self) self._instances.remove(self) self.n = initial self.total = total self.leave = leave return
if kwargs: self.disable = True with self._lock: self.pos = self._get_free_pos(self) self._instances.remove(self) raise ( TqdmDeprecationWarning( "`nested` is deprecated and automated.\n" "Use `position` instead for manual control.\n", fp_write=getattr(file, 'write', sys.stderr.write)) if "nested" in kwargs else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments if ( (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout)) ) or dynamic_ncols: # pragma: no cover if dynamic_ncols: dynamic_ncols = _screen_shape_wrapper() if dynamic_ncols: ncols, nrows = dynamic_ncols(file) else: _dynamic_ncols = _screen_shape_wrapper() if _dynamic_ncols: _ncols, _nrows = _dynamic_ncols(file) if ncols is None: ncols = _ncols if nrows is None: nrows = _nrows
if miniters is None: miniters = 0 dynamic_miniters = True else: dynamic_miniters = False
if mininterval is None: mininterval = 0
if maxinterval is None: maxinterval = 0
if ascii is None: ascii = not _supports_unicode(file)
if bar_format and ascii is not True and not _is_ascii(ascii): # Convert bar format into unicode since terminal uses unicode bar_format = str(bar_format)
if smoothing is None: smoothing = 0
# Store the arguments self.iterable = iterable self.desc = desc or '' self.total = total self.leave = leave self.fp = file self.ncols = ncols self.nrows = nrows self.mininterval = mininterval self.maxinterval = maxinterval self.miniters = miniters self.dynamic_miniters = dynamic_miniters self.ascii = ascii self.disable = disable self.unit = unit self.unit_scale = unit_scale self.unit_divisor = unit_divisor self.initial = initial self.lock_args = lock_args self.delay = delay self.gui = gui self.dynamic_ncols = dynamic_ncols self.smoothing = smoothing self._ema_dn = EMA(smoothing) self._ema_dt = EMA(smoothing) self._ema_miniters = EMA(smoothing) self.bar_format = bar_format self.postfix = None self.colour = colour self._time = time if postfix: try: self.set_postfix(refresh=False, **postfix) except TypeError: self.postfix = postfix
# Init the iterations counters self.last_print_n = initial self.n = initial
# if nested, at initial sp() call we replace '\r' by '\n' to # not overwrite the outer progress bar with self._lock: # mark fixed positions as negative self.pos = self._get_free_pos(self) if position is None else -position
if not gui: # Initialize the screen printer self.sp = self.status_printer(self.fp) if delay <= 0: self.refresh(lock_args=self.lock_args)
# Init the time counter self.last_print_t = self._time() # NB: Avoid race conditions by setting start_t at the very end of init self.start_t = self.last_print_t
def __bool__(self): if self.total is not None: return self.total > 0 if self.iterable is None: raise TypeError('bool() undefined when iterable == total == None') return bool(self.iterable)
def __len__(self): return ( self.total if self.iterable is None else self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__") else getattr(self, "total", None))
def __reversed__(self): try: orig = self.iterable except AttributeError: raise TypeError("'tqdm' object is not reversible") else: self.iterable = reversed(self.iterable) return self.__iter__() finally: self.iterable = orig
def __contains__(self, item): contains = getattr(self.iterable, '__contains__', None) return (contains(item) if contains is not None # pylint: disable=not-callable else item in self.__iter__())
def __enter__(self): return self
def __exit__(self, exc_type, exc_value, traceback): try: self.close() except AttributeError: # maybe eager thread cleanup upon external error if (exc_type, exc_value, traceback) == (None, None, None): raise warn("AttributeError ignored", TqdmWarning, stacklevel=2)
def __del__(self): self.close()
def __str__(self): return self.format_meter(**self.format_dict)
@property def _comparable(self): return abs(getattr(self, "pos", 1 << 31))
def __hash__(self): return id(self)
def __iter__(self): """Backward-compatibility to use: for x in tqdm(iterable)"""
# Inlining instance variables as locals (speed optimisation) iterable = self.iterable
# If the bar is disabled, then just walk the iterable # (note: keep this check outside the loop for performance) if self.disable: for obj in iterable: yield obj return
mininterval = self.mininterval last_print_t = self.last_print_t last_print_n = self.last_print_n min_start_t = self.start_t + self.delay n = self.n time = self._time
try: for obj in iterable: yield obj # Update and possibly print the progress bar. # Note: does not call self.update(1) for speed optimisation. n += 1
if n - last_print_n >= self.miniters: cur_t = time() dt = cur_t - last_print_t if dt >= mininterval and cur_t >= min_start_t: self.update(n - last_print_n) last_print_n = self.last_print_n last_print_t = self.last_print_t finally: self.n = n self.close()
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. """ if self.disable: return
if n < 0: self.last_print_n += n # for auto-refresh logic to work self.n += n
# check counter first to reduce calls to time() if self.n - self.last_print_n >= self.miniters: cur_t = self._time() dt = cur_t - self.last_print_t if dt >= self.mininterval and cur_t >= self.start_t + self.delay: cur_t = self._time() dn = self.n - self.last_print_n # >= n if self.smoothing and dt and dn: # EMA (not just overall average) self._ema_dn(dn) self._ema_dt(dt) self.refresh(lock_args=self.lock_args) if self.dynamic_miniters: # If no `miniters` was specified, adjust automatically to the # maximum iteration rate seen so far between two prints. # e.g.: After running `tqdm.update(5)`, subsequent # calls to `tqdm.update()` will only cause an update after # at least 5 more iterations. if self.maxinterval and dt >= self.maxinterval: self.miniters = dn * (self.mininterval or self.maxinterval) / dt elif self.smoothing: # EMA miniters update self.miniters = self._ema_miniters( dn * (self.mininterval / dt if self.mininterval and dt else 1)) else: # max iters between two prints self.miniters = max(self.miniters, dn)
# Store old values for next call self.last_print_n = self.n self.last_print_t = cur_t return True
def close(self): """Cleanup and (if leave=False) close the progress bar.""" if getattr(self, 'disable', True): return
# Prevent multiple closures self.disable = True
# decrement instance pos and remove from internal set pos = abs(self.pos) self._decr_instances(self)
if not hasattr(self, 'last_print_t'): return if self.last_print_t < self.start_t + self.delay: # haven't ever displayed; nothing to clear return
# GUI mode if getattr(self, 'sp', None) is None: return
# annoyingly, _supports_unicode isn't good enough def fp_write(s): self.fp.write(str(s))
try: fp_write('') except ValueError as e: if 'closed' in str(e): return raise # pragma: no cover
leave = pos == 0 if self.leave is None else self.leave
with self._lock: if leave: # stats for overall rate (no weighted average) self._ema_dt = lambda: None self.display(pos=0) fp_write('\n') else: # clear previous display if self.display(msg='', pos=pos) and not pos: fp_write('\r')
def clear(self, nolock=False): """Clear current bar display.""" if self.disable: return
if not nolock: self._lock.acquire() pos = abs(self.pos) if pos < (self.nrows or 20): self.moveto(pos) self.sp('') self.fp.write('\r') # place cursor back at the beginning of line self.moveto(-pos) if not nolock: self._lock.release()
def refresh(self, nolock=False, lock_args=None): """ 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`. """ if self.disable: return
if not nolock: if lock_args: if not self._lock.acquire(*lock_args): return False else: self._lock.acquire() self.display() if not nolock: self._lock.release() return True
def unpause(self): """Restart tqdm timer from last print time.""" if self.disable: return cur_t = self._time() self.start_t += cur_t - self.last_print_t self.last_print_t = cur_t
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. """ self.n = 0 if total is not None: self.total = None if total == float("inf") else total if self.disable: return self.last_print_n = 0 self.last_print_t = self.start_t = self._time() self._ema_dn = EMA(self.smoothing) self._ema_dt = EMA(self.smoothing) self._ema_miniters = EMA(self.smoothing) self.refresh()
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]. """ self.desc = desc + ': ' if desc else '' if refresh: self.refresh()
def set_description_str(self, desc=None, refresh=True): """Set/modify description without ': ' appended.""" self.desc = desc or '' if refresh: self.refresh()
def set_postfix(self, ordered_dict=None, refresh=True, **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 """ # Sort in alphabetical order to be more deterministic postfix = OrderedDict([] if ordered_dict is None else ordered_dict) for key in sorted(kwargs.keys()): postfix[key] = kwargs[key] # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = self.format_num(postfix[key]) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], str): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything # Stitch together to get the final postfix self.postfix = ', '.join(key + '=' + postfix[key].strip() for key in postfix.keys()) if refresh: self.refresh()
def set_postfix_str(self, s='', refresh=True): """ Postfix without dictionary expansion, similar to prefix handling. """ self.postfix = str(s) if refresh: self.refresh()
def moveto(self, n): # TODO: private method self.fp.write('\n' * n + _term_move_up() * -n) getattr(self.fp, 'flush', lambda: None)()
@property def format_dict(self): """Public API for read-only member access.""" if self.disable and not hasattr(self, 'unit'): return defaultdict(lambda: None, { 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'}) if self.dynamic_ncols: self.ncols, self.nrows = self.dynamic_ncols(self.fp) return { 'n': self.n, 'total': self.total, 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0, 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc, 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale, 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None, 'bar_format': self.bar_format, 'postfix': self.postfix, 'unit_divisor': self.unit_divisor, 'initial': self.initial, 'colour': self.colour}
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)`). """ if pos is None: pos = abs(self.pos)
nrows = self.nrows or 20 if pos >= nrows - 1: if pos >= nrows: return False if msg or msg is None: # override at `nrows - 1` msg = " ... (more hidden) ..."
if not hasattr(self, "sp"): raise TqdmDeprecationWarning( "Please use `tqdm.gui.tqdm(...)`" " instead of `tqdm(..., gui=True)`\n", fp_write=getattr(self.fp, 'write', sys.stderr.write))
if pos: self.moveto(pos) self.sp(self.__str__() if msg is None else msg) if pos: self.moveto(-pos) return True
@classmethod @contextmanager def wrapattr(cls, stream, method, total=None, bytes=True, # pylint: disable=redefined-builtin **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 """ with cls(total=total, **tqdm_kwargs) as t: if bytes: t.unit = "B" t.unit_scale = True t.unit_divisor = 1024 yield CallbackIOWrapper(t.update, stream, method)
def trange(*args, **kwargs): """Shortcut for tqdm(range(*args), **kwargs).""" return tqdm(range(*args), **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196"""Tkinter GUI progress bar decorator for iterators.
Usage:>>> from tqdm.tk import trange, tqdm>>> for i in trange(10):... ..."""import reimport sysimport tkinterimport tkinter.ttk as ttkfrom warnings import warn
from .std import TqdmExperimentalWarning, TqdmWarningfrom .std import tqdm as std_tqdm
__author__ = {"github.com/": ["richardsheridan", "casperdcl"]}__all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange']
class tqdm_tk(std_tqdm): # pragma: no cover """ Experimental Tkinter GUI version of tqdm!
Note: Window interactivity suffers if `tqdm_tk` is not running within a Tkinter mainloop and values are generated infrequently. In this case, consider calling `tqdm_tk.refresh()` frequently in the Tk thread. """
# TODO: @classmethod: write()?
def __init__(self, *args, **kwargs): """ This class accepts the following parameters *in addition* to the parameters accepted by `tqdm`.
Parameters ---------- grab : bool, optional Grab the input across all windows of the process. tk_parent : `tkinter.Wm`, optional Parent Tk window. cancel_callback : Callable, optional Create a cancel button and set `cancel_callback` to be called when the cancel or window close button is clicked. """ kwargs = kwargs.copy() kwargs['gui'] = True # convert disable = None to False kwargs['disable'] = bool(kwargs.get('disable', False)) self._warn_leave = 'leave' in kwargs grab = kwargs.pop('grab', False) tk_parent = kwargs.pop('tk_parent', None) self._cancel_callback = kwargs.pop('cancel_callback', None) super().__init__(*args, **kwargs)
if self.disable: return
if tk_parent is None: # Discover parent widget try: tk_parent = tkinter._default_root except AttributeError: raise AttributeError( "`tk_parent` required when using `tkinter.NoDefaultRoot()`") if tk_parent is None: # use new default root window as display self._tk_window = tkinter.Tk() else: # some other windows already exist self._tk_window = tkinter.Toplevel() else: self._tk_window = tkinter.Toplevel(tk_parent)
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2) self._tk_dispatching = self._tk_dispatching_helper()
self._tk_window.protocol("WM_DELETE_WINDOW", self.cancel) self._tk_window.wm_title(self.desc) self._tk_window.wm_attributes("-topmost", 1) self._tk_window.after(0, lambda: self._tk_window.wm_attributes("-topmost", 0)) self._tk_n_var = tkinter.DoubleVar(self._tk_window, value=0) self._tk_text_var = tkinter.StringVar(self._tk_window) pbar_frame = ttk.Frame(self._tk_window, padding=5) pbar_frame.pack() _tk_label = ttk.Label(pbar_frame, textvariable=self._tk_text_var, wraplength=600, anchor="center", justify="center") _tk_label.pack() self._tk_pbar = ttk.Progressbar( pbar_frame, variable=self._tk_n_var, length=450) if self.total is not None: self._tk_pbar.configure(maximum=self.total) else: self._tk_pbar.configure(mode="indeterminate") self._tk_pbar.pack() if self._cancel_callback is not None: _tk_button = ttk.Button(pbar_frame, text="Cancel", command=self.cancel) _tk_button.pack() if grab: self._tk_window.grab_set()
def close(self): if self.disable: return
self.disable = True
with self.get_lock(): self._instances.remove(self)
def _close(): self._tk_window.after('idle', self._tk_window.destroy) if not self._tk_dispatching: self._tk_window.update()
self._tk_window.protocol("WM_DELETE_WINDOW", _close)
# if leave is set but we are self-dispatching, the left window is # totally unresponsive unless the user manually dispatches if not self.leave: _close() elif not self._tk_dispatching: if self._warn_leave: warn("leave flag ignored if not in tkinter mainloop", TqdmWarning, stacklevel=2) _close()
def clear(self, *_, **__): pass
def display(self, *_, **__): self._tk_n_var.set(self.n) d = self.format_dict # remove {bar} d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace( "{bar}", "<bar/>") msg = self.format_meter(**d) if '<bar/>' in msg: msg = "".join(re.split(r'\|?<bar/>\|?', msg, maxsplit=1)) self._tk_text_var.set(msg) if not self._tk_dispatching: self._tk_window.update()
def set_description(self, desc=None, refresh=True): self.set_description_str(desc, refresh)
def set_description_str(self, desc=None, refresh=True): self.desc = desc if not self.disable: self._tk_window.wm_title(desc) if refresh and not self._tk_dispatching: self._tk_window.update()
def cancel(self): """ `cancel_callback()` followed by `close()` when close/cancel buttons clicked. """ if self._cancel_callback is not None: self._cancel_callback() self.close()
def reset(self, total=None): """ Resets to 0 iterations for repeated use.
Parameters ---------- total : int or float, optional. Total to use for the new bar. """ if hasattr(self, '_tk_pbar'): if total is None: self._tk_pbar.configure(maximum=100, mode="indeterminate") else: self._tk_pbar.configure(maximum=total, mode="determinate") super().reset(total=total)
@staticmethod def _tk_dispatching_helper(): """determine if Tkinter mainloop is dispatching events""" codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__} for frame in sys._current_frames().values(): while frame: if frame.f_code in codes: return True frame = frame.f_back return False
def ttkrange(*args, **kwargs): """Shortcut for `tqdm.tk.tqdm(range(*args), **kwargs)`.""" return tqdm_tk(range(*args), **kwargs)
# Aliasestqdm = tqdm_tktrange = ttkrange123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241.TH "TQDM" "1" "2015\-2026" "tqdm User Manuals".SH NAMEtqdm \- fast, extensible progress bar for Python and CLI.SH SYNOPSIStqdm [\f[I]options\f[R]].SH DESCRIPTIONSee \c.UR https://github.com/tqdm/tqdm.UE \c\&.Can be used as a pipe:.IP.EX$ \f[I]# count lines of code\f[R]$ cat *.py \f[B]|\f[R] tqdm \f[B]|\f[R] wc \-l327it [00:00, 981773.38it/s]327
$ \f[I]# find all files\f[R]$ find . \-name \(dq*.py\(dq \f[B]|\f[R] tqdm \f[B]|\f[R] wc \-l432it [00:00, 833842.30it/s]432
\f[I]# ... and more info\f[R]$ find . \-name \(aq*.py\(aq \-exec wc \-l \(rs{} \(rs; \(rs \f[B]|\f[R] tqdm \-\-total 432 \-\-unit files \-\-desc counting \(rs \f[B]|\f[R] awk \(aq{ sum += $1 }; END { print sum }\(aqcounting: 100%\f[B]|\f[R]█████████\f[B]|\f[R] 432/432 [00:00<00:00, 794361.83files/s]131998.EE.SH OPTIONS.TP\-h, \-\-helpPrint this help and exit..TP\-v, \-\-versionPrint version and exit..TP\-\-desc=\f[I]desc\f[R]str, optional.Prefix for the progress bar..TP\-\-total=\f[I]total\f[R]int or float, optional.The number of expected iterations.If unspecified, len(iterable) is used if possible.If float(\(lqinf\(rq) or as a last resort, only basic progressstatistics are displayed (no ETA, no progress bar).If \f[CR]gui\f[R] is True and this parameter needs subsequent updating,specify an initial arbitrary large positive number, e.g.\ 9e9..TP\-\-leavebool, optional.If [default: True], keeps all traces of the progress bar upontermination of iteration.If \f[CR]None\f[R], will leave only if \f[CR]position\f[R] is\f[CR]0\f[R]..TP\-\-ncols=\f[I]ncols\f[R]int, optional.The width of the entire output message.If specified, dynamically resizes the progress bar to stay within thisbound.If unspecified, attempts to use environment width.The fallback is a meter width of 10 and no limit for the counter andstatistics.If 0, will not print any meter (only stats)..TP\-\-mininterval=\f[I]mininterval\f[R]float, optional.Minimum progress display update interval [default: 0.1] seconds..TP\-\-maxinterval=\f[I]maxinterval\f[R]float, optional.Maximum progress display update interval [default: 10] seconds.Automatically adjusts \f[CR]miniters\f[R] to correspond to\f[CR]mininterval\f[R] after long display update lag.Only works if \f[CR]dynamic_miniters\f[R] or monitor thread is enabled..TP\-\-miniters=\f[I]miniters\f[R]int or float, optional.Minimum progress display update interval, in iterations.If 0 and \f[CR]dynamic_miniters\f[R], will automatically adjust to equal\f[CR]mininterval\f[R] (more CPU efficient, good for tight loops).If > 0, will skip display of specified number of iterations.Tweak this and \f[CR]mininterval\f[R] 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..TP\-\-ascii=\f[I]ascii\f[R]bool or str, optional.If unspecified or False, use unicode (smooth blocks) to fill the meter.The fallback is to use ASCII characters \(rq 123456789#\(lq..TP\-\-disablebool, optional.Whether to disable the entire progress bar wrapper [default: False].If set to None, disable on non\-TTY..TP\-\-unit=\f[I]unit\f[R]str, optional.String that will be used to define the unit of each iteration [default:it]..TP\-\-unit\-scale=\f[I]unit_scale\f[R]bool or int or float, optional.If 1 or True, the number of iterations will be reduced/scaledautomatically and a metric prefix following the International System ofUnits standard will be added (kilo, mega, etc.)[default: False].If any other non\-zero number, will scale \f[CR]total\f[R] and\f[CR]n\f[R]..TP\-\-dynamic\-ncolsbool, optional.If set, constantly alters \f[CR]ncols\f[R] and \f[CR]nrows\f[R] to theenvironment (allowing for window resizes) [default: False]..TP\-\-smoothing=\f[I]smoothing\f[R]float, optional.Exponential moving average smoothing factor for speed estimates (ignoredin GUI mode).Ranges from 0 (average speed) to 1 (current/instantaneous speed)[default: 0.3]..TP\-\-bar\-format=\f[I]bar_format\f[R]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}, \(cq \(cq{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 \(lq:\(rq is automatically removed after {desc} ifthe latter is empty..TP\-\-initial=\f[I]initial\f[R]int or float, optional.The initial counter value.Useful when restarting a progress bar [default: 0].If using float, consider specifying \f[CR]{n:.3f}\f[R] or similar in\f[CR]bar_format\f[R], or specifying \f[CR]unit_scale\f[R]..TP\-\-position=\f[I]position\f[R]int, optional.Specify the line offset to print this bar (starting from 0) Automatic ifunspecified.Useful to manage multiple bars at once (eg, from threads)..TP\-\-postfix=\f[I]postfix\f[R]dict or *, optional.Specify additional stats to display at the end of the bar.Calls \f[CR]set_postfix(**postfix)\f[R] if possible (dict)..TP\-\-unit\-divisor=\f[I]unit_divisor\f[R]float, optional.[default: 1000], ignored unless \f[CR]unit_scale\f[R] is True..TP\-\-write\-bytesbool, optional.Whether to write bytes.If (default: False) will write unicode..TP\-\-lock\-args=\f[I]lock_args\f[R]tuple, optional.Passed to \f[CR]refresh\f[R] for intermediate output (initialisation,iterating, and updating)..TP\-\-nrows=\f[I]nrows\f[R]int, optional.The screen height.If specified, hides nested bars outside this bound.If unspecified, attempts to use environment height.The fallback is 20..TP\-\-colour=\f[I]colour\f[R]str, optional.Bar colour (e.g.\ `green', `#00ff00')..TP\-\-delay=\f[I]delay\f[R]float, optional.Don\(cqt display until [default: 0] seconds have elapsed..TP\-\-delim=\f[I]delim\f[R]chr, optional.Delimiting character [default: `\(rsn'].Use `\(rs0' for null.N.B.: on Windows systems, Python converts `\(rsn' to `\(rsr\(rsn'..TP\-\-buf\-size=\f[I]buf_size\f[R]int, optional.String buffer size in bytes [default: 256] used when \f[CR]delim\f[R] isspecified..TP\-\-bytesbool, optional.If true, will count bytes, ignore \f[CR]delim\f[R], and default\f[CR]unit_scale\f[R] to True, \f[CR]unit_divisor\f[R] to 1024, and\f[CR]unit\f[R] to `B'..TP\-\-teebool, optional.If true, passes \f[CR]stdin\f[R] to both \f[CR]stderr\f[R] and\f[CR]stdout\f[R]..TP\-\-updatebool, optional.If true, will treat input as newly elapsed iterations, i.e.\ numbers topass to \f[CR]update()\f[R].Note that this is slow (\(ti2e5 it/s) since every input must be decodedas a number..TP\-\-update\-tobool, optional.If true, will treat input as total elapsed iterations, i.e.\ numbers toassign to \f[CR]self.n\f[R].Note that this is slow (\(ti2e5 it/s) since every input must be decodedas a number..TP\-\-nullbool, optional.If true, will discard input (no stdout)..TP\-\-manpath=\f[I]manpath\f[R]str, optional.Directory in which to install tqdm man pages..TP\-\-comppath=\f[I]comppath\f[R]str, optional.Directory in which to place tqdm completion..TP\-\-log=\f[I]log\f[R]str, optional.CRITICAL|FATAL|ERROR|WARN(ING)|[default: `INFO']|DEBUG|NOTSET..SH AUTHORStqdm developers \c.UR https://github.com/tqdm.UE \c.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328"""General helpers required for `tqdm.std`."""import osimport reimport sysfrom functools import partial, partialmethod, wrapsfrom inspect import signature# TODO consider using wcswidth third-party package for 0-width charactersfrom unicodedata import east_asian_widthfrom warnings import warnfrom weakref import proxy
_range, _unich, _unicode, _basestring = range, chr, str, strCUR_OS = sys.platformIS_WIN = any(CUR_OS.startswith(i) for i in ['win32', 'cygwin'])IS_NIX = any(CUR_OS.startswith(i) for i in ['aix', 'linux', 'darwin', 'freebsd'])RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]")
try: if IS_WIN: import colorama else: raise ImportErrorexcept ImportError: colorama = Noneelse: try: colorama.init(strip=False) except TypeError: colorama.init()
def envwrap(name, app="", types=None, is_method=False): """ Basic (env-only) version of [envwrap](https://github.com/tqdm/envwrap). Install `envwrap` for config file support. """ if types is None: types = {} if name[-1] == "_": name = name[:-1] warn("Trailing underscore in `name` is automatic", DeprecationWarning, stacklevel=2) prefixes = (name, f"{name}_{app}") if app else (name,) env_overrides = {} for prefix in prefixes: prefix = prefix.upper() + "_" i = len(prefix) env_overrides.update( (k[i:].lower(), v) for k, v in os.environ.items() if k.startswith(prefix)) part = partialmethod if is_method else partial
def wrap(func): params = signature(func).parameters # ignore unknown env vars overrides = {k: v for k, v in env_overrides.items() if k in params} # infer overrides' `type`s for k in overrides: param = params[k] if param.annotation is not param.empty: # typehints for typ in getattr(param.annotation, '__args__', (param.annotation,)): try: overrides[k] = typ(overrides[k]) except Exception: # nosec B110 pass else: break elif param.default is not None: # type of default value overrides[k] = type(param.default)(overrides[k]) else: try: # `types` fallback overrides[k] = types[k](overrides[k]) except KeyError: # keep unconverted (`str`) pass return part(func, **overrides) return wrap
try: from envwrap import envwrap # noqa: F401, F811, pylint: disable=unused-importexcept ModuleNotFoundError: pass
class FormatReplace: """ >>> a = FormatReplace('something') >>> f"{a:5d}" 'something' """ # NOQA: P102 def __init__(self, replace=''): self.replace = replace self.format_called = 0
def __format__(self, _): self.format_called += 1 return self.replace
class Comparable: """Assumes child has self._comparable attr/@property""" def __lt__(self, other): return self._comparable < other._comparable
def __le__(self, other): return (self < other) or (self == other)
def __eq__(self, other): return self._comparable == other._comparable
def __ne__(self, other): return not self == other
def __gt__(self, other): return not self <= other
def __ge__(self, other): return not self < other
class ObjectWrapper: def __getattr__(self, name): return getattr(self._wrapped, name)
def __setattr__(self, name, value): return setattr(self._wrapped, name, value)
def wrapper_getattr(self, name): """Actual `self.getattr` rather than self._wrapped.getattr""" try: return object.__getattr__(self, name) except AttributeError: # py2 return getattr(self, name)
def wrapper_setattr(self, name, value): """Actual `self.setattr` rather than self._wrapped.setattr""" return object.__setattr__(self, name, value)
def __init__(self, wrapped): """ Thin wrapper around a given object """ self.wrapper_setattr('_wrapped', wrapped)
class SimpleTextIOWrapper(ObjectWrapper): """ Change only `.write()` of the wrapped object by encoding the passed value and passing the result to the wrapped object's `.write()` method. """ # pylint: disable=too-few-public-methods def __init__(self, wrapped, encoding): super().__init__(wrapped) self.wrapper_setattr('encoding', encoding)
def write(self, s): """ Encode `s` and pass to the wrapped object's `.write()` method. """ return self._wrapped.write(s.encode(self.wrapper_getattr('encoding')))
def __eq__(self, other): return self._wrapped == getattr(other, '_wrapped', other)
class DisableOnWriteError(ObjectWrapper): """ Disable the given `tqdm_instance` upon `write()` or `flush()` errors. """ @staticmethod def disable_on_exception(tqdm_instance, func): """ Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`. """ tqdm_instance = proxy(tqdm_instance)
def inner(*args, **kwargs): try: return func(*args, **kwargs) except OSError as e: if e.errno != 5: raise try: tqdm_instance.miniters = float('inf') except ReferenceError: pass except ValueError as e: if 'closed' not in str(e): raise try: tqdm_instance.miniters = float('inf') except ReferenceError: pass return inner
def __init__(self, wrapped, tqdm_instance): # noqa: B042 super().__init__(wrapped) if hasattr(wrapped, 'write'): self.wrapper_setattr( 'write', self.disable_on_exception(tqdm_instance, wrapped.write)) if hasattr(wrapped, 'flush'): self.wrapper_setattr( 'flush', self.disable_on_exception(tqdm_instance, wrapped.flush))
def __eq__(self, other): return self._wrapped == getattr(other, '_wrapped', other)
class CallbackIOWrapper(ObjectWrapper): def __init__(self, callback, stream, method="read"): """ Wrap a given `file`-like object's `read()` or `write()` to report lengths to the given `callback` """ super().__init__(stream) func = getattr(stream, method) if method == "write": @wraps(func) def write(data, *args, **kwargs): res = func(data, *args, **kwargs) callback(len(data)) return res self.wrapper_setattr('write', write) elif method == "read": @wraps(func) def read(*args, **kwargs): data = func(*args, **kwargs) callback(len(data)) return data self.wrapper_setattr('read', read) else: raise KeyError("Can only wrap read/write methods")
def _is_utf(encoding): try: '\u2588\u2589'.encode(encoding) except UnicodeEncodeError: return False except Exception: try: return encoding.lower().startswith('utf-') or ('U8' == encoding) except Exception: return False else: return True
def _supports_unicode(fp): try: return _is_utf(fp.encoding) except AttributeError: return False
def _is_ascii(s): if isinstance(s, str): for c in s: if ord(c) > 255: return False return True return _supports_unicode(s)
def _screen_shape_wrapper(): # pragma: no cover """ Return a function which returns console dimensions (width, height). Supported: linux, osx, windows, cygwin. """ def inner(fp): try: from os import get_terminal_size cols, lines = get_terminal_size(getattr(fp, 'fileno', lambda: None)()) return cols - 1, lines - 1 except Exception: return None, None
return inner
def _environ_cols_wrapper(): # pragma: no cover """ Return a function which returns console width. Supported: linux, osx, windows, cygwin. """ warn("Use `_screen_shape_wrapper()(file)[0]` instead of" " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2) shape = _screen_shape_wrapper() if not shape: return None
@wraps(shape) def inner(fp): return shape(fp)[0]
return inner
def _term_move_up(): # pragma: no cover return '' if (os.name == 'nt') and (colorama is None) else '\x1b[A'
def _text_width(s): return sum(2 if east_asian_width(ch) in 'FW' else 1 for ch in str(s))
def disp_len(data): """ Returns the real on-screen length of a string which may contain ANSI control codes and wide chars. """ return _text_width(RE_ANSI.sub('', data))
def disp_trim(data, length): """ Trim a string which may contain ANSI control characters. """ if len(data) == disp_len(data): return data[:length]
ansi_present = bool(RE_ANSI.search(data)) while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if ansi_present and bool(RE_ANSI.search(data)): # assume ANSI reset is required return data if data.endswith("\033[0m") else data + "\033[0m" return data1234567"""`tqdm` version detector. Precedence: installed dist, git, 'UNKNOWN'."""from importlib.metadata import PackageNotFoundError, version
try: __version__ = version('tqdm')except PackageNotFoundError: __version__ = "UNKNOWN"1pip12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273Metadata-Version: 2.4Name: typing_extensionsVersion: 4.16.0Summary: Backported and Experimental Type Hints for Python 3.9+Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typingAuthor-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" <levkivskyi@gmail.com>Requires-Python: >=3.9Description-Content-Type: text/markdownLicense-Expression: PSF-2.0Classifier: Development Status :: 5 - Production/StableClassifier: Environment :: ConsoleClassifier: Intended Audience :: DevelopersClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: 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.15Classifier: Topic :: Software DevelopmentLicense-File: LICENSEProject-URL: Bug Tracker, https://github.com/python/typing_extensions/issuesProject-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.mdProject-URL: Documentation, https://typing-extensions.readthedocs.io/Project-URL: Home, https://github.com/python/typing_extensionsProject-URL: Q & A, https://github.com/python/typing/discussionsProject-URL: Repository, https://github.com/python/typing_extensions
# Typing Extensions
[](https://gitter.im/python/typing)
[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) –[PyPI](https://pypi.org/project/typing-extensions/)
## Overview
The `typing_extensions` module serves two related purposes:
- Enable use of new type system features on older Python versions. For example, `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows users on previous Python versions to use it too.- Enable experimentation with new type system PEPs before they are accepted and added to the `typing` module.
`typing_extensions` is treated specially by static type checkers such asmypy and pyright. Objects defined in `typing_extensions` are treated the sameway as equivalent forms in `typing`.
`typing_extensions` uses[Semantic Versioning](https://semver.org/). Themajor version will be incremented only for backwards-incompatible changes.Therefore, it's safe to dependon `typing_extensions` like this: `typing_extensions ~=x.y`,where `x.y` is the first version that includes all features you need.[This](https://packaging.python.org/en/latest/specifications/version-specifiers/#compatible-release)is equivalent to `typing_extensions >=x.y, <(x+1)`. Do not depend on `~= x.y.z`unless you really know what you're doing; that defeats the purpose ofsemantic versioning.
## Included items
See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for acomplete listing of module contents.
## Contributing
See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md)for how to contribute to `typing_extensions`.
1234567__pycache__/typing_extensions.cpython-314.pyc,,
typing_extensions-4.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
typing_extensions-4.16.0.dist-info/METADATA,sha256=sFCEyh1Qh5hlF42f_5-r6rYb37HzYb-96VQh_8j5vkY,3310
typing_extensions-4.16.0.dist-info/RECORD,,
typing_extensions-4.16.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
typing_extensions-4.16.0.dist-info/licenses/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936
typing_extensions.py,sha256=QEDKGh7L7gDROFwSqTCE0cW9RvC3dPB-WufpHE9V5pY,1650121234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any.venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/METADATAAdded+59
.venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/RECORDAdded+43
.venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/WHEELAdded+6
.venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/licenses/LICENSEAdded+20
.venv-deploy/lib/python3.14/site-packages/pyyaml-6.0.3.dist-info/top_level.txtAdded+2
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/METADATAAdded+1600
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/RECORDAdded+72
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/WHEELAdded+5
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/entry_points.txtAdded+2
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/licenses/LICENCEAdded+49
.venv-deploy/lib/python3.14/site-packages/tqdm-4.70.0.dist-info/top_level.txtAdded+1
.venv-deploy/lib/python3.14/site-packages/tqdm/__init__.pyAdded+38
.venv-deploy/lib/python3.14/site-packages/tqdm/__main__.pyAdded+3
.venv-deploy/lib/python3.14/site-packages/tqdm/_main.pyAdded+9
.venv-deploy/lib/python3.14/site-packages/tqdm/_monitor.pyAdded+104
.venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm.pyAdded+9
.venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm_gui.pyAdded+9
.venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm_notebook.pyAdded+9
.venv-deploy/lib/python3.14/site-packages/tqdm/_tqdm_pandas.pyAdded+24
.venv-deploy/lib/python3.14/site-packages/tqdm/_utils.pyAdded+11
.venv-deploy/lib/python3.14/site-packages/tqdm/asyncio.pyAdded+103
.venv-deploy/lib/python3.14/site-packages/tqdm/auto.pyAdded+40
.venv-deploy/lib/python3.14/site-packages/tqdm/autonotebook.pyAdded+38
.venv-deploy/lib/python3.14/site-packages/tqdm/cli.pyAdded+324
.venv-deploy/lib/python3.14/site-packages/tqdm/completion.shAdded+19
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/__init__.pyAdded+91
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/bells.pyAdded+28
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/concurrent.pyAdded+259
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/discord.pyAdded+155
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/itertools.pyAdded+92
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/logging.pyAdded+128
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/slack.pyAdded+119
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/telegram.pyAdded+152
.venv-deploy/lib/python3.14/site-packages/tqdm/contrib/utils_worker.pyAdded+38
.venv-deploy/lib/python3.14/site-packages/tqdm/dask.pyAdded+44
.venv-deploy/lib/python3.14/site-packages/tqdm/gui.pyAdded+179
.venv-deploy/lib/python3.14/site-packages/tqdm/keras.pyAdded+123
.venv-deploy/lib/python3.14/site-packages/tqdm/notebook.pyAdded+317
.venv-deploy/lib/python3.14/site-packages/tqdm/rich.pyAdded+154
.venv-deploy/lib/python3.14/site-packages/tqdm/std.pyAdded+1533
.venv-deploy/lib/python3.14/site-packages/tqdm/tk.pyAdded+196
.venv-deploy/lib/python3.14/site-packages/tqdm/tqdm.1Added+241
.venv-deploy/lib/python3.14/site-packages/tqdm/utils.pyAdded+328
.venv-deploy/lib/python3.14/site-packages/tqdm/version.pyAdded+7
.venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/METADATAAdded+73
.venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/RECORDAdded+7
.venv-deploy/lib/python3.14/site-packages/typing_extensions-4.16.0.dist-info/WHEELAdded+4