Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gradio Block() can't detect imported library like numpy in jupyter notebook #10587

Open
1 task done
kelvinhammond opened this issue Feb 13, 2025 · 4 comments
Open
1 task done
Labels
bug Something isn't working docs/website Related to documentation or website

Comments

@kelvinhammond
Copy link

Describe the bug

Exact issue described here is still valid but I cannot reopen this ticket #3625

Gradio fails to pull imports on reload

Have you searched existing issues? 🔎

  • I have searched and found no existing issues

Reproduction

import gradio as gr

%%blocks
# Anything in under gr.NO_RELOAD won't be reloaded when the block is re-run (afaik)
if gr.NO_RELOAD:
    import numpy as np
    from transformers import pipeline
    transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")

def transcribe(stream, new_chunk):
    sr, y = new_chunk
    
    # Convert to mono if stereo
    if y.ndim > 1:
        y = y.mean(axis=1)
        
    y = y.astype(np.float32)
    y /= np.max(np.abs(y))

    if stream is not None:
        stream = np.concatenate([stream, y])
    else:
        stream = y

    return stream, transcriber({"sampling_rate": sr, "raw": stream})["text"]

waveform_options = gr.WaveformOptions(
    waveform_color="#01C6FF",
    waveform_progress_color="#0066B4",
    skip_length=2,
    show_controls=False,
)

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            state = gr.State()
            audio = gr.Audio(
                sources=["microphone", "upload"],
                show_download_button=True,
                waveform_options=waveform_options,
                streaming=True,
            )
            with gr.Row():
                clear_btn = gr.ClearButton()
                submit_btn = gr.Button("Submit", variant="primary")
        output = gr.Textbox(label="Output")

    submit_btn.click(
        fn=transcribe,
        inputs=[state, audio],
        outputs=[state, output],
        api_name="transcribe")

    gr.on(
        triggers=[audio.stream],
        fn=transcribe,
        inputs=[state, audio],
        outputs=[state, output],
    )

Screenshot

No response

Logs

Traceback (most recent call last):
  File "/opt/conda/lib/python3.12/site-packages/gradio/queueing.py", line 625, in process_events
    response = await route_utils.call_process_api(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/gradio/route_utils.py", line 322, in call_process_api
    output = await app.get_blocks().process_api(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/gradio/blocks.py", line 2098, in process_api
    result = await self.call_function(
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/gradio/blocks.py", line 1645, in call_function
    prediction = await anyio.to_thread.run_sync(  # type: ignore
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/anyio/to_thread.py", line 56, in run_sync
    return await get_async_backend().run_sync_in_worker_thread(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 2461, in run_sync_in_worker_thread
    return await future
           ^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 962, in run
    result = context.run(func, *args)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.12/site-packages/gradio/utils.py", line 883, in wrapper
    response = f(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^
  File "<string>", line 16, in transcribe
NameError: name 'np' is not defined

System Info

Gradio Environment Information:
------------------------------
Operating System: Linux
gradio version: 5.16.0
gradio_client version: 1.7.0

------------------------------------------------
gradio dependencies in your environment:

aiofiles: 23.2.1
anyio: 4.8.0
audioop-lts is not installed.
fastapi: 0.115.8
ffmpy: 0.5.0
gradio-client==1.7.0 is not installed.
httpx: 0.28.1
huggingface-hub: 0.28.1
jinja2: 3.1.5
markupsafe: 2.1.5
numpy: 2.1.3
orjson: 3.10.15
packaging: 24.2
pandas: 2.2.3
pillow: 11.1.0
pydantic: 2.10.6
pydub: 0.25.1
python-multipart: 0.0.20
pyyaml: 6.0.2
ruff: 0.9.6
safehttpx: 0.1.6
semantic-version: 2.10.0
starlette: 0.45.3
tomlkit: 0.13.2
typer: 0.15.1
typing-extensions: 4.12.2
urllib3: 2.3.0
uvicorn: 0.34.0
authlib; extra == 'oauth' is not installed.
itsdangerous; extra == 'oauth' is not installed.


gradio_client dependencies in your environment:

fsspec: 2024.9.0
httpx: 0.28.1
huggingface-hub: 0.28.1
packaging: 24.2
typing-extensions: 4.12.2
websockets: 14.2

Severity

Blocking usage of gradio

@kelvinhammond kelvinhammond added the bug Something isn't working label Feb 13, 2025
@kelvinhammond kelvinhammond changed the title Gradio Block() can't detect imported library like numpy Gradio Block() can't detect imported library like numpy in jupyter notebook Feb 13, 2025
@freddyaboulton
Copy link
Collaborator

Hi @kelvinhammond - You can place the code inside NO_RELOAD in a separate notebook cell. The NO_RELOAD was designed more for file/script use cases

@kelvinhammond
Copy link
Author

Thank you.

It seems the transcribe function must also be in it's own cell but the block is re-executable so this should work for now.

The docs for this should probably mention this as a caveat. https://www.gradio.app/guides/developing-faster-with-reload-mode#jupyter-notebook-magic

@freddyaboulton
Copy link
Collaborator

Would you like to open a PR?

@kelvinhammond
Copy link
Author

Maybe, not too familiar with gradio yet so I wouldn't be comfortable updating its documentation just yet.

@abidlabs abidlabs added the docs/website Related to documentation or website label Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working docs/website Related to documentation or website
Projects
None yet
Development

No branches or pull requests

3 participants