"""
IPython/Jupyter Notebook progressbar decorator for iterators.
Includes a default (x)range iterator printing to stderr.
Usage:
>>> from tqdm_notebook import tnrange[, tqdm_notebook]
>>> for i in tnrange(10): #same as: for i in tqdm_notebook(xrange(10))
... ...
"""
from __future__ import division, absolute_import
import sys
from ._utils import _range
from ._tqdm import tqdm
if True:
try:
import ipywidgets
IPY = 4
except ImportError:
IPY = 32
import warnings
with warnings.catch_warnings():
ipy_deprecation_msg = "The `IPython.html` package" \
" has been deprecated"
warnings.filterwarnings('error',
message=".*" + ipy_deprecation_msg + ".*")
try:
import IPython.html.widgets as ipywidgets
except Warning as e:
if ipy_deprecation_msg not in str(e):
raise
warnings.simplefilter('ignore')
try:
import IPython.html.widgets as ipywidgets
except ImportError:
pass
except ImportError:
pass
try:
if IPY == 32:
from IPython.html.widgets import IntProgress, HBox, HTML
IPY = 3
else:
from ipywidgets import IntProgress, HBox, HTML
except ImportError:
try:
from IPython.html.widgets import IntProgressWidget as IntProgress
from IPython.html.widgets import ContainerWidget as HBox
from IPython.html.widgets import HTML
IPY = 2
except ImportError:
IPY = 0
try:
from IPython.display import display
except ImportError:
pass
try:
from html import escape
except ImportError:
from cgi import escape
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
__all__ = ['tqdm_notebook', 'tnrange']
class tqdm_notebook(tqdm):
"""
Experimental IPython/Jupyter Notebook widget using tqdm!
"""
@staticmethod
def status_printer(_, total=None, desc=None):
"""
Manage the printing of an IPython/Jupyter Notebook progress bar widget.
"""
if total:
pbar = IntProgress(min=0, max=total)
else:
pbar = IntProgress(min=0, max=1)
pbar.value = 1
pbar.bar_style = 'info'
if desc:
pbar.description = desc
ptext = HTML()
container = HBox(children=[pbar, ptext])
display(container)
def print_status(s='', close=False, bar_style=None):
if total:
n = None
if s:
npos = s.find(r'/|/')
if npos >= 0:
n = int(s[:npos])
s = s[npos + 3:]
if n is not None:
pbar.value = n
if s:
s = s.replace('||', '')
s = escape(s)
ptext.value = s
if bar_style:
if not (pbar.bar_style == 'danger' and bar_style == 'success'):
pbar.bar_style = bar_style
if close and pbar.bar_style != 'danger':
container.visible = False
return print_status
@classmethod
def write(cls, s, file=sys.stdout, end="\n"):
"""
Print a message via tqdm_notebook (just an alias for print)
"""
file.write(s)
file.write(end)
def __init__(self, *args, **kwargs):
if kwargs.get('file', sys.stderr) is sys.stderr:
kwargs['file'] = sys.stdout
if not kwargs.get('bar_format', None):
kwargs['bar_format'] = r'{n}/|/{l_bar}{r_bar}'
kwargs['gui'] = True
super(tqdm_notebook, self).__init__(*args, **kwargs)
if self.disable or not kwargs['gui']:
return
self.sp = self.status_printer(self.fp, self.total, self.desc)
self.desc = None
if not self.disable:
self.sp(self.__repr__())
def __iter__(self, *args, **kwargs):
try:
for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs):
yield obj
except:
self.sp(bar_style='danger')
raise
def update(self, *args, **kwargs):
try:
super(tqdm_notebook, self).update(*args, **kwargs)
except Exception as exc:
self.sp(bar_style='danger')
raise exc
def close(self, *args, **kwargs):
super(tqdm_notebook, self).close(*args, **kwargs)
if self.total and self.n < self.total:
self.sp(bar_style='danger')
else:
if self.leave:
self.sp(bar_style='success')
else:
self.sp(close=True)
def moveto(*args, **kwargs):
return
def tnrange(*args, **kwargs):
"""
A shortcut for tqdm_notebook(xrange(*args), **kwargs).
On Python3+ range is used instead of xrange.
"""
return tqdm_notebook(_range(*args), **kwargs)