gradio-app / gradio

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!
http://www.gradio.app
Apache License 2.0
33.98k stars 2.58k forks source link

Gradio Block() can't detect imported library like numpy and matplotlib on kaggle #3625

Closed ahsanu123 closed 3 weeks ago

ahsanu123 commented 1 year ago

Describe the bug

hey, recently i started learn gradio on kaggle.com, when i was trying to learn plot with Block, i start with example from plot documentation (https://gradio.app/docs/#plot), i copy paste the code to my kaggle as shown below

(this also not working on colab)

%%blocks

def markPort(port):
    if port == '':
        return

    return f"port: {port}"

def plot_forecast(final_year, companies, noise, show_legend, point_style):
    start_year = 2020
    x = np.arange(start_year, final_year + 1)
    year_count = x.shape[0]
    plt_format = ({"cross": "X", "line": "-", "circle": "o--"})[point_style]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    for i, company in enumerate(companies):
        series = np.arange(0, year_count, dtype=float)
        series = series**2 * (i + 1)
        series += np.random.rand(year_count) * noise
        ax.plot(x, series, plt_format)
    if show_legend:
        plt.legend(companies)
    return fig

gr.Markdown("# MoMos - Motor Monitoring System Dashboard")
bl = gr.Blocks()
with bl:

    with gr.Tab("Setting"):
        with gr.Column():
            gr.Markdown("### Port: ")
            portRadio = gr.Radio(['com5', 'com6', 'com7', 'com8', 'com9'], label="Choose")
            port = gr.Textbox(show_label=False, max_lines=1, placeholder="Choose or insert")
            displayPort = gr.Markdown()

            portRadio.change(markPort, portRadio, displayPort)
            port.submit(markPort, port, displayPort)

    with gr.Tab("Display"):
        with gr.Column():
            gr.Markdown("### display plot Here!!")
            year = gr.Radio([2025, 2030, 2035, 2040], label="Project to:")
            group = gr.CheckboxGroup(["Google", "Microsoft", "Gradio"], label="Company Selection")
            noise = gr.Slider(1, 100, label="Noise Level")
            showLegend = gr.Checkbox(label="Show Legend")
            style = gr.Dropdown(["cross", "line", "circle"], label="Style")

            showPlot = gr.Button("Plot")

            plotPlace = gr.Plot(label="forecast")

            showPlot.click(plot_forecast,inputs=[year,group,noise,showLegend,style],outputs=plotPlace)

i already import all library like numpy, matplotlib.pyplot etc image

when i run this code, gradio is run as expected, but when i click plot button the error is showing up, as shown below image image

as far i know error is say that numpy is not imported, is i miss something to run plot on platform like kaggle?

Is there an existing issue for this?

Reproduction

run this code in kaggle


import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

import gradio as gr

%%blocks

def markPort(port):
    if port == '':
        return

    return f"port: {port}"

def plot_forecast(final_year, companies, noise, show_legend, point_style):
    start_year = 2020
    x = np.arange(start_year, final_year + 1)
    year_count = x.shape[0]
    plt_format = ({"cross": "X", "line": "-", "circle": "o--"})[point_style]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    for i, company in enumerate(companies):
        series = np.arange(0, year_count, dtype=float)
        series = series**2 * (i + 1)
        series += np.random.rand(year_count) * noise
        ax.plot(x, series, plt_format)
    if show_legend:
        plt.legend(companies)
    return fig

gr.Markdown("# MoMos - Motor Monitoring System Dashboard")
bl = gr.Blocks()
with bl:

    with gr.Tab("Setting"):
        with gr.Column():
            gr.Markdown("### Port: ")
            portRadio = gr.Radio(['com5', 'com6', 'com7', 'com8', 'com9'], label="Choose")
            port = gr.Textbox(show_label=False, max_lines=1, placeholder="Choose or insert")
            displayPort = gr.Markdown()

            portRadio.change(markPort, portRadio, displayPort)
            port.submit(markPort, port, displayPort)

    with gr.Tab("Display"):
        with gr.Column():
            gr.Markdown("### display plot Here!!")
            year = gr.Radio([2025, 2030, 2035, 2040], label="Project to:")
            group = gr.CheckboxGroup(["Google", "Microsoft", "Gradio"], label="Company Selection")
            noise = gr.Slider(1, 100, label="Noise Level")
            showLegend = gr.Checkbox(label="Show Legend")
            style = gr.Dropdown(["cross", "line", "circle"], label="Style")

            showPlot = gr.Button("Plot")

            plotPlace = gr.Plot(label="forecast")

            showPlot.click(plot_forecast,inputs=[year,group,noise,showLegend,style],outputs=plotPlace)

then click plot button image

Screenshot

No response

Logs

image

System Info

'3.23.0'

Severity

annoying

abidlabs commented 1 year ago

Hi @ahsanu123 can you try putting the imports under the %%blocks magic? So like this:

%%blocks

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

import gradio as gr

def markPort(port):
    if port == '':
        return

...

and see if that works?

ahsanu123 commented 1 year ago

@abidlabs thanks for reply, i already try to put import after %%block but no improvment, still same here is my kaggle: https://www.kaggle.com/code/caasperart/learnfft-spectogram

but, if iam not use magic %%block, code is work as it

Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/site-packages/gradio/routes.py", line 401, in run_predict
    event_data=event_data,
  File "/opt/conda/lib/python3.7/site-packages/gradio/blocks.py", line 1076, in process_api
    fn_index, inputs, iterator, request, event_id, event_data
  File "/opt/conda/lib/python3.7/site-packages/gradio/blocks.py", line 885, in call_function
    fn, *processed_input, limiter=self.limiter
  File "/opt/conda/lib/python3.7/site-packages/anyio/to_thread.py", line 32, in run_sync
    func, *args, cancellable=cancellable, limiter=limiter
  File "/opt/conda/lib/python3.7/site-packages/anyio/_backends/_asyncio.py", line 937, in run_sync_in_worker_thread
    return await future
  File "/opt/conda/lib/python3.7/site-packages/anyio/_backends/_asyncio.py", line 867, in run
    result = context.run(func, *args)
  File "<string>", line 16, in plot_forecast
NameError: name 'np' is not defined
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/site-packages/gradio/routes.py", line 401, in run_predict
    event_data=event_data,
  File "/opt/conda/lib/python3.7/site-packages/gradio/blocks.py", line 1076, in process_api
    fn_index, inputs, iterator, request, event_id, event_data
  File "/opt/conda/lib/python3.7/site-packages/gradio/blocks.py", line 885, in call_function
    fn, *processed_input, limiter=self.limiter
  File "/opt/conda/lib/python3.7/site-packages/anyio/to_thread.py", line 32, in run_sync
    func, *args, cancellable=cancellable, limiter=limiter
  File "/opt/conda/lib/python3.7/site-packages/anyio/_backends/_asyncio.py", line 937, in run_sync_in_worker_thread
    return await future
  File "/opt/conda/lib/python3.7/site-packages/anyio/_backends/_asyncio.py", line 867, in run
    result = context.run(func, *args)
  File "<string>", line 16, in plot_forecast
NameError: name 'np' is not defined
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/site-packages/gradio/routes.py", line 401, in run_predict
    event_data=event_data,
  File "/opt/conda/lib/python3.7/site-packages/gradio/blocks.py", line 1076, in process_api
    fn_index, inputs, iterator, request, event_id, event_data
  File "/opt/conda/lib/python3.7/site-packages/gradio/blocks.py", line 885, in call_function
    fn, *processed_input, limiter=self.limiter
  File "/opt/conda/lib/python3.7/site-packages/anyio/to_thread.py", line 32, in run_sync
    func, *args, cancellable=cancellable, limiter=limiter
  File "/opt/conda/lib/python3.7/site-packages/anyio/_backends/_asyncio.py", line 937, in run_sync_in_worker_thread
    return await future
  File "/opt/conda/lib/python3.7/site-packages/anyio/_backends/_asyncio.py", line 867, in run
    result = context.run(func, *args)
  File "<string>", line 16, in plot_forecast
NameError: name 'np' is not defined
abidlabs commented 1 month ago

Hi, apologies for the late follow up. We haven't had a chance to look into this issue, but the Gradio codebase has changed quite significantly since this issue was created. Could you let us know if this is still an issue in the latest version of Gradio (pip install --upgrade gradio)? Thanks!

ahsanu123 commented 3 weeks ago

close this, because project already complete.

thanks.