File size: 1,478 Bytes
5add17c
 
 
 
 
 
 
 
 
 
 
 
f433297
5add17c
 
 
 
 
f433297
fc737eb
f433297
fc737eb
 
 
 
 
f433297
 
fc737eb
f433297
 
fc737eb
f433297
5add17c
 
f433297
5add17c
fc737eb
5add17c
fc737eb
5add17c
 
 
 
 
 
 
 
 
 
fc737eb
5add17c
f433297
 
5add17c
 
f433297
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import gradio as gr
import matplotlib.pyplot as plt
import sys
import io
import numpy as np
from PIL import Image

def run_code(code):
    try:
        old_stdout = sys.stdout
        sys.stdout = io.StringIO()

        local_env = {'plt': plt, 'np': np}
        exec(code, {}, local_env)

        output = sys.stdout.getvalue()
        sys.stdout = old_stdout
        
        if 'plt' in code:
            buf = io.BytesIO()
            plt.draw()
            plt.savefig(buf, format='png')
            buf.seek(0)
            img = Image.open(buf)
            img_array = np.array(img)
            plt.close()

            if img_array.sum() > 0:
                return img_array
            else:
                return create_image("Empty plot")

        return create_image("No valid matplotlib plot found")

    except Exception as e:
        return create_image(f"Error: {str(e)}")

def create_image(message):
    fig, ax = plt.subplots()
    ax.text(0.5, 0.5, message, fontsize=20, ha='center', va='center')
    ax.axis('off')
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    img = Image.open(buf)
    plt.close()
    return np.array(img)

interface = gr.Interface(
    fn=run_code, 
    inputs=gr.Code(language="python", label="Enter Python Code"), 
    outputs=gr.Image(type="numpy", label="Output"), 
    title="Matplotlib Plot Generator",
    description="Enter Python code that uses matplotlib to generate plots."
)

interface.launch()