|
| 1 | +# |
| 2 | +# Copyright (c) 2021 IBM Corp. |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | + |
| 16 | +# |
| 17 | +# misc.py |
| 18 | +# |
| 19 | +# Part of text_extensions_for_pandas |
| 20 | +# |
| 21 | +# Home for various functions too limited in scope or size to justify a separate module |
| 22 | +# |
| 23 | + |
| 24 | +import pandas as pd |
| 25 | +import time |
| 26 | +from typing import * |
| 27 | + |
| 28 | +def run_with_progress_bar(num_items: int, fn: Callable, item_type: str = "doc") \ |
| 29 | + -> List[pd.DataFrame]: |
| 30 | + """ |
| 31 | + Display a progress bar while iterating over a list of dataframes. |
| 32 | +
|
| 33 | + :param num_items: Number of items to iterate over |
| 34 | + :param fn: A function that accepts a single integer argument -- let's |
| 35 | + call it `i` -- and performs processing for document `i` and returns |
| 36 | + a `pd.DataFrame` of results |
| 37 | + :param item_type: Human-readable name for the items that the calling |
| 38 | + code is iterating over |
| 39 | +
|
| 40 | + """ |
| 41 | + # Imports inline to avoid creating a hard dependency on ipywidgets/IPython |
| 42 | + # for programs that don't call this funciton. |
| 43 | + # noinspection PyPackageRequirements |
| 44 | + import ipywidgets |
| 45 | + # noinspection PyPackageRequirements |
| 46 | + from IPython.display import display |
| 47 | + |
| 48 | + _UPDATE_SEC = 0.1 |
| 49 | + result = [] # Type: List[pd.DataFrame] |
| 50 | + last_update = time.time() |
| 51 | + progress_bar = ipywidgets.IntProgress(0, 0, num_items, |
| 52 | + description="Starting...", |
| 53 | + layout=ipywidgets.Layout(width="100%"), |
| 54 | + style={"description_width": "12%"}) |
| 55 | + display(progress_bar) |
| 56 | + for i in range(num_items): |
| 57 | + result.append(fn(i)) |
| 58 | + now = time.time() |
| 59 | + if i == num_items - 1 or now - last_update >= _UPDATE_SEC: |
| 60 | + progress_bar.value = i + 1 |
| 61 | + progress_bar.description = f"{i + 1}/{num_items} {item_type}s" |
| 62 | + last_update = now |
| 63 | + progress_bar.bar_style = "success" |
| 64 | + return result |
0 commit comments