Incremental GSC parsing (exact copy of the tutorials shared as a separate project) / tqdm / _tqdm_notebook.py
1576 views"""1IPython/Jupyter Notebook progressbar decorator for iterators.2Includes a default (x)range iterator printing to stderr.34Usage:5>>> from tqdm_notebook import tnrange[, tqdm_notebook]6>>> for i in tnrange(10): #same as: for i in tqdm_notebook(xrange(10))7... ...8"""9# future division is important to divide integers and get as10# a result precise floating numbers (instead of truncated int)11from __future__ import division, absolute_import12# import compatibility functions and utilities13import sys14from ._utils import _range15# to inherit from the tqdm class16from ._tqdm import tqdm171819if True: # pragma: no cover20# import IPython/Jupyter base widget and display utilities21try: # IPython 4.x22import ipywidgets23IPY = 424except ImportError: # IPython 3.x / 2.x25IPY = 3226import warnings27with warnings.catch_warnings():28ipy_deprecation_msg = "The `IPython.html` package" \29" has been deprecated"30warnings.filterwarnings('error',31message=".*" + ipy_deprecation_msg + ".*")32try:33import IPython.html.widgets as ipywidgets34except Warning as e:35if ipy_deprecation_msg not in str(e):36raise37warnings.simplefilter('ignore')38try:39import IPython.html.widgets as ipywidgets # NOQA40except ImportError:41pass42except ImportError:43pass4445try: # IPython 4.x / 3.x46if IPY == 32:47from IPython.html.widgets import IntProgress, HBox, HTML48IPY = 349else:50from ipywidgets import IntProgress, HBox, HTML51except ImportError:52try: # IPython 2.x53from IPython.html.widgets import IntProgressWidget as IntProgress54from IPython.html.widgets import ContainerWidget as HBox55from IPython.html.widgets import HTML56IPY = 257except ImportError:58IPY = 05960try:61from IPython.display import display # , clear_output62except ImportError:63pass6465# HTML encoding66try: # Py367from html import escape68except ImportError: # Py269from cgi import escape707172__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}73__all__ = ['tqdm_notebook', 'tnrange']747576class tqdm_notebook(tqdm):77"""78Experimental IPython/Jupyter Notebook widget using tqdm!79"""8081@staticmethod82def status_printer(_, total=None, desc=None):83"""84Manage the printing of an IPython/Jupyter Notebook progress bar widget.85"""86# Fallback to text bar if there's no total87# DEPRECATED: replaced with an 'info' style bar88# if not total:89# return super(tqdm_notebook, tqdm_notebook).status_printer(file)9091# fp = file9293# Prepare IPython progress bar94if total:95pbar = IntProgress(min=0, max=total)96else: # No total? Show info style bar with no progress tqdm status97pbar = IntProgress(min=0, max=1)98pbar.value = 199pbar.bar_style = 'info'100if desc:101pbar.description = desc102# Prepare status text103ptext = HTML()104# Only way to place text to the right of the bar is to use a container105container = HBox(children=[pbar, ptext])106display(container)107108def print_status(s='', close=False, bar_style=None):109# Note: contrary to native tqdm, s='' does NOT clear bar110# goal is to keep all infos if error happens so user knows111# at which iteration the loop failed.112113# Clear previous output (really necessary?)114# clear_output(wait=1)115116# Get current iteration value from format_meter string117if total:118n = None119if s:120npos = s.find(r'/|/') # cause we use bar_format=r'{n}|...'121# Check that n can be found in s (else n > total)122if npos >= 0:123n = int(s[:npos]) # get n from string124s = s[npos + 3:] # remove from string125126# Update bar with current n value127if n is not None:128pbar.value = n129130# Print stats131if s: # never clear the bar (signal: s='')132s = s.replace('||', '') # remove inesthetical pipes133s = escape(s) # html escape special characters (like '?')134ptext.value = s135136# Change bar style137if bar_style:138# Hack-ish way to avoid the danger bar_style being overriden by139# success because the bar gets closed after the error...140if not (pbar.bar_style == 'danger' and bar_style == 'success'):141pbar.bar_style = bar_style142143# Special signal to close the bar144if close and pbar.bar_style != 'danger': # hide only if no error145container.visible = False146147return print_status148149@classmethod150def write(cls, s, file=sys.stdout, end="\n"):151"""152Print a message via tqdm_notebook (just an alias for print)153"""154# Just an alias for print because overlap is impossible with ipywidgets155file.write(s)156file.write(end)157158def __init__(self, *args, **kwargs):159# Setup default output160if kwargs.get('file', sys.stderr) is sys.stderr:161kwargs['file'] = sys.stdout # avoid the red block in IPython162163# Remove the bar from the printed string, only print stats164if not kwargs.get('bar_format', None):165kwargs['bar_format'] = r'{n}/|/{l_bar}{r_bar}'166167# Initialize parent class + avoid printing by using gui=True168kwargs['gui'] = True169super(tqdm_notebook, self).__init__(*args, **kwargs)170if self.disable or not kwargs['gui']:171return172173# Delete first pbar generated from super() (wrong total and text)174# DEPRECATED by using gui=True175# self.sp('', close=True)176# Replace with IPython progress bar display (with correct total)177self.sp = self.status_printer(self.fp, self.total, self.desc)178self.desc = None # trick to place description before the bar179180# Print initial bar state181if not self.disable:182self.sp(self.__repr__()) # same as self.refresh without clearing183184def __iter__(self, *args, **kwargs):185try:186for obj in super(tqdm_notebook, self).__iter__(*args, **kwargs):187# return super(tqdm...) will not catch exception188yield obj189# NB: except ... [ as ...] breaks IPython async KeyboardInterrupt190except:191self.sp(bar_style='danger')192raise193194def update(self, *args, **kwargs):195try:196super(tqdm_notebook, self).update(*args, **kwargs)197except Exception as exc:198# cannot catch KeyboardInterrupt when using manual tqdm199# as the interrupt will most likely happen on another statement200self.sp(bar_style='danger')201raise exc202203def close(self, *args, **kwargs):204super(tqdm_notebook, self).close(*args, **kwargs)205# Try to detect if there was an error or KeyboardInterrupt206# in manual mode: if n < total, things probably got wrong207if self.total and self.n < self.total:208self.sp(bar_style='danger')209else:210if self.leave:211self.sp(bar_style='success')212else:213self.sp(close=True)214215def moveto(*args, **kwargs):216# void -> avoid extraneous `\n` in IPython output cell217return218219220def tnrange(*args, **kwargs):221"""222A shortcut for tqdm_notebook(xrange(*args), **kwargs).223On Python3+ range is used instead of xrange.224"""225return tqdm_notebook(_range(*args), **kwargs)226227228