allenai / cached_path

A file utility for accessing both local and remote files through a unified interface.
https://cached-path.readthedocs.io/
Apache License 2.0
35 stars 12 forks source link

Use progress bar from Gradio #204

Closed fakerybakery closed 11 months ago

fakerybakery commented 11 months ago

Hi, great package. Gradio supports a custom progress bar TQDM-style. Is there any chance to support this?

Example:

import gradio as gr
from cached_path import cached_path
def update(url, progress=gr.Progress()):
    file = str(cached_path(url, progress=progress.tqdm))
    return file
with gr.Blocks() as demo:
    inp = gr.Textbox(label="Enter URL", info="Enter URL")
    out = gr.File(interactive=False)
    btn = gr.Button("Run")
    btn.click(fn=update, inputs=inp, outputs=out)

demo.launch()
epwalsh commented 11 months ago

Hey @fakerybakery this is definitely doable. We could provide an API for this, but in the meantime you would just need to create a thin wrapper around gr.Progress to pass it to cached_path. I think something like this would suffice:

from typing import Optional

class GrProgressWrapper:
    def __init__(self, gr_progress):
        self.completed = 0
        self.total = 0
        self.inner = gr_progress

    def add_task(self, description: str, total: int) -> int:
        del description
        self.total = total
        return 0  # returns a task_id, doesn't matter unless you're doing multiple downloads with the same bar

    def advance(self, task_id: int, n: int):
        del task_id  # not needed unless you're doing multiple downloads with the same bar
        self.completed += n
        self.inner((self.completed, self.total))

    def update(self, task_id: int, total: Optional[int] = None, completed: Optional[int] = None):
        del task_id  # not needed unless you're doing multiple downloads with the same bar
        if total is not None:
            self.total = total
        if completed is not None:
            self.completed = completed
        self.inner((self.completed, self.total))

I haven't tested this so let me know if you have issues.

fakerybakery commented 11 months ago

Thanks so much! I tried doing something like this previously but wasn't able to figure it out :) Should I close this issue now?

epwalsh commented 11 months ago

If that worked for you feel free to close :)