Team Ai
Apppublic

unofficial-hf-plugins/matplotlib-graph-creation

sourceHugging Facewtfplupdated 2y agoView on Hugging Face
5likes
app.py57 linesDownload Raw Back to root
1import gradio as gr2import matplotlib.pyplot as plt3import sys4import io5import numpy as np6from PIL import Image7 8def run_code(code):9    try:10        old_stdout = sys.stdout11        sys.stdout = io.StringIO()12 13        local_env = {'plt': plt, 'np': np}14        exec(code, {}, local_env)15 16        output = sys.stdout.getvalue()17        sys.stdout = old_stdout18        19        if 'plt' in code:20            buf = io.BytesIO()21            plt.draw()22            plt.savefig(buf, format='png')23            buf.seek(0)24            img = Image.open(buf)25            img_array = np.array(img)26            plt.close()27 28            if img_array.sum() > 0:29                return img_array30            else:31                return create_image("Empty plot")32 33        return create_image("No valid matplotlib plot found")34 35    except Exception as e:36        return create_image(f"Error: {str(e)}")37 38def create_image(message):39    fig, ax = plt.subplots()40    ax.text(0.5, 0.5, message, fontsize=20, ha='center', va='center')41    ax.axis('off')42    buf = io.BytesIO()43    plt.savefig(buf, format='png')44    buf.seek(0)45    img = Image.open(buf)46    plt.close()47    return np.array(img)48 49interface = gr.Interface(50    fn=run_code, 51    inputs=gr.Code(language="python", label="Enter Python Code"), 52    outputs=gr.Image(type="numpy", label="Output"), 53    title="Matplotlib Plot Generator",54    description="Enter Python code that uses matplotlib to generate plots."55)56 57interface.launch()