Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,19 +4,23 @@ import subprocess
|
|
4 |
import importlib
|
5 |
import io
|
6 |
import contextlib
|
|
|
7 |
from pygments import highlight
|
8 |
from pygments.lexers import PythonLexer
|
9 |
from pygments.formatters import HtmlFormatter
|
10 |
import matplotlib.pyplot as plt
|
11 |
import numpy as np
|
12 |
import pandas as pd
|
|
|
|
|
|
|
13 |
|
14 |
# Function to install packages dynamically
|
15 |
def install_package(package):
|
16 |
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
17 |
|
18 |
# Function to execute user code with output capturing and visualization support
|
19 |
-
def execute_code(code, libraries):
|
20 |
# Install libraries
|
21 |
for library in libraries.splitlines():
|
22 |
if library.strip():
|
@@ -33,6 +37,8 @@ def execute_code(code, libraries):
|
|
33 |
'plt': plt,
|
34 |
'np': np,
|
35 |
'pd': pd,
|
|
|
|
|
36 |
}
|
37 |
exec(code, exec_globals)
|
38 |
|
@@ -40,41 +46,93 @@ def execute_code(code, libraries):
|
|
40 |
if plt.get_fignums():
|
41 |
plt.savefig('plot.png')
|
42 |
plt.close()
|
43 |
-
return output.getvalue(), error_output.getvalue(), 'plot.png'
|
|
|
|
|
|
|
44 |
else:
|
45 |
-
return output.getvalue(), error_output.getvalue(), None
|
46 |
except Exception as e:
|
47 |
-
return "",
|
48 |
|
49 |
# Function to highlight Python code
|
50 |
def highlight_code(code):
|
51 |
return highlight(code, PythonLexer(), HtmlFormatter(style="monokai"))
|
52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
# Define the Gradio interface
|
54 |
-
with gr.Blocks(
|
55 |
-
gr.Markdown("# Advanced Python Code Executor")
|
56 |
|
57 |
with gr.Tabs():
|
58 |
with gr.TabItem("Code Execution"):
|
59 |
with gr.Row():
|
60 |
with gr.Column(scale=2):
|
61 |
-
code_input = gr.Code(label="Python Code", language="python", lines=
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
64 |
with gr.Column(scale=1):
|
65 |
output = gr.Textbox(label="Standard Output", lines=10)
|
66 |
error_output = gr.Textbox(label="Error Output", lines=5)
|
67 |
plot_output = gr.Image(label="Plot Output")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
with gr.TabItem("Code Highlighting"):
|
70 |
-
code_to_highlight = gr.Code(label="Enter Python code to highlight", language="python", lines=
|
71 |
highlight_button = gr.Button("Highlight Code")
|
72 |
highlighted_code = gr.HTML(label="Highlighted Code")
|
73 |
|
74 |
execute_button.click(
|
75 |
fn=execute_code,
|
76 |
-
inputs=[code_input, libraries_input],
|
77 |
-
outputs=[output, error_output, plot_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
)
|
79 |
|
80 |
highlight_button.click(
|
@@ -87,13 +145,25 @@ with gr.Blocks(css=".gradio-container {background-color: #f0f0f0;}") as demo:
|
|
87 |
## Features:
|
88 |
- Execute Python code with custom library imports
|
89 |
- Capture and display standard output and error messages separately
|
90 |
-
- Support for data visualization with matplotlib
|
|
|
91 |
- Code highlighting for better readability
|
92 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
## Tips:
|
95 |
-
- Use
|
96 |
-
- Your plot will automatically be displayed if you use
|
|
|
|
|
97 |
""")
|
98 |
|
99 |
# Launch the interface
|
|
|
4 |
import importlib
|
5 |
import io
|
6 |
import contextlib
|
7 |
+
import traceback
|
8 |
from pygments import highlight
|
9 |
from pygments.lexers import PythonLexer
|
10 |
from pygments.formatters import HtmlFormatter
|
11 |
import matplotlib.pyplot as plt
|
12 |
import numpy as np
|
13 |
import pandas as pd
|
14 |
+
import seaborn as sns
|
15 |
+
import plotly.express as px
|
16 |
+
import black
|
17 |
|
18 |
# Function to install packages dynamically
|
19 |
def install_package(package):
|
20 |
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
21 |
|
22 |
# Function to execute user code with output capturing and visualization support
|
23 |
+
def execute_code(code, libraries, timeout):
|
24 |
# Install libraries
|
25 |
for library in libraries.splitlines():
|
26 |
if library.strip():
|
|
|
37 |
'plt': plt,
|
38 |
'np': np,
|
39 |
'pd': pd,
|
40 |
+
'sns': sns,
|
41 |
+
'px': px,
|
42 |
}
|
43 |
exec(code, exec_globals)
|
44 |
|
|
|
46 |
if plt.get_fignums():
|
47 |
plt.savefig('plot.png')
|
48 |
plt.close()
|
49 |
+
return output.getvalue(), error_output.getvalue(), 'plot.png', None
|
50 |
+
elif 'fig' in exec_globals and isinstance(exec_globals['fig'], px.Figure):
|
51 |
+
exec_globals['fig'].write_image('plot.png')
|
52 |
+
return output.getvalue(), error_output.getvalue(), 'plot.png', None
|
53 |
else:
|
54 |
+
return output.getvalue(), error_output.getvalue(), None, None
|
55 |
except Exception as e:
|
56 |
+
return "", traceback.format_exc(), None, None
|
57 |
|
58 |
# Function to highlight Python code
|
59 |
def highlight_code(code):
|
60 |
return highlight(code, PythonLexer(), HtmlFormatter(style="monokai"))
|
61 |
|
62 |
+
# Function to format code using Black
|
63 |
+
def format_code(code):
|
64 |
+
try:
|
65 |
+
formatted_code = black.format_str(code, mode=black.FileMode())
|
66 |
+
return formatted_code, "Code formatted successfully!"
|
67 |
+
except Exception as e:
|
68 |
+
return code, f"Formatting error: {str(e)}"
|
69 |
+
|
70 |
+
# Function to generate sample code
|
71 |
+
def generate_sample_code(sample_type):
|
72 |
+
samples = {
|
73 |
+
"Basic": "print('Hello, World!')\n\nfor i in range(5):\n print(i)",
|
74 |
+
"Numpy": "import numpy as np\n\narr = np.array([1, 2, 3, 4, 5])\nprint(arr.mean())\nprint(arr.std())",
|
75 |
+
"Pandas": "import pandas as pd\n\ndf = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})\nprint(df.describe())",
|
76 |
+
"Matplotlib": "import matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4, 5]\ny = [2, 4, 6, 8, 10]\n\nplt.plot(x, y)\nplt.title('Simple Line Plot')\nplt.xlabel('X-axis')\nplt.ylabel('Y-axis')",
|
77 |
+
"Seaborn": "import seaborn as sns\n\ntips = sns.load_dataset('tips')\nsns.scatterplot(x='total_bill', y='tip', data=tips)",
|
78 |
+
"Plotly": "import plotly.express as px\n\ndf = px.data.gapminder().query('year == 2007')\nfig = px.scatter(df, x='gdpPercap', y='lifeExp', size='pop', color='continent', hover_name='country', log_x=True, size_max=60)\nfig.show()"
|
79 |
+
}
|
80 |
+
return samples.get(sample_type, "")
|
81 |
+
|
82 |
# Define the Gradio interface
|
83 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
84 |
+
gr.Markdown("# Advanced Python Code Executor and Formatter")
|
85 |
|
86 |
with gr.Tabs():
|
87 |
with gr.TabItem("Code Execution"):
|
88 |
with gr.Row():
|
89 |
with gr.Column(scale=2):
|
90 |
+
code_input = gr.Code(label="Python Code", language="python", lines=15)
|
91 |
+
with gr.Row():
|
92 |
+
libraries_input = gr.TextArea(label="Libraries (one per line)", placeholder="e.g.\nrequests\nscipy", lines=2)
|
93 |
+
timeout_input = gr.Number(label="Timeout (seconds)", value=30, minimum=1, maximum=300)
|
94 |
+
with gr.Row():
|
95 |
+
execute_button = gr.Button("Run Code", variant="primary")
|
96 |
+
clear_button = gr.Button("Clear", variant="secondary")
|
97 |
+
sample_dropdown = gr.Dropdown(choices=["Basic", "Numpy", "Pandas", "Matplotlib", "Seaborn", "Plotly"], label="Load Sample Code")
|
98 |
with gr.Column(scale=1):
|
99 |
output = gr.Textbox(label="Standard Output", lines=10)
|
100 |
error_output = gr.Textbox(label="Error Output", lines=5)
|
101 |
plot_output = gr.Image(label="Plot Output")
|
102 |
+
file_output = gr.File(label="Generated Files")
|
103 |
+
|
104 |
+
with gr.TabItem("Code Formatting"):
|
105 |
+
code_to_format = gr.Code(label="Enter Python code to format", language="python", lines=15)
|
106 |
+
format_button = gr.Button("Format Code")
|
107 |
+
formatted_code = gr.Code(label="Formatted Code", language="python", lines=15)
|
108 |
+
format_message = gr.Textbox(label="Formatting Message")
|
109 |
|
110 |
with gr.TabItem("Code Highlighting"):
|
111 |
+
code_to_highlight = gr.Code(label="Enter Python code to highlight", language="python", lines=15)
|
112 |
highlight_button = gr.Button("Highlight Code")
|
113 |
highlighted_code = gr.HTML(label="Highlighted Code")
|
114 |
|
115 |
execute_button.click(
|
116 |
fn=execute_code,
|
117 |
+
inputs=[code_input, libraries_input, timeout_input],
|
118 |
+
outputs=[output, error_output, plot_output, file_output]
|
119 |
+
)
|
120 |
+
|
121 |
+
clear_button.click(
|
122 |
+
lambda: ("", "", "", None, None),
|
123 |
+
outputs=[code_input, output, error_output, plot_output, file_output]
|
124 |
+
)
|
125 |
+
|
126 |
+
sample_dropdown.change(
|
127 |
+
fn=generate_sample_code,
|
128 |
+
inputs=[sample_dropdown],
|
129 |
+
outputs=[code_input]
|
130 |
+
)
|
131 |
+
|
132 |
+
format_button.click(
|
133 |
+
fn=format_code,
|
134 |
+
inputs=[code_to_format],
|
135 |
+
outputs=[formatted_code, format_message]
|
136 |
)
|
137 |
|
138 |
highlight_button.click(
|
|
|
145 |
## Features:
|
146 |
- Execute Python code with custom library imports
|
147 |
- Capture and display standard output and error messages separately
|
148 |
+
- Support for data visualization with matplotlib, seaborn, and plotly
|
149 |
+
- Code formatting using Black
|
150 |
- Code highlighting for better readability
|
151 |
+
- Sample code generator for quick starts
|
152 |
+
- Timeout setting for code execution
|
153 |
+
- Clear button to reset inputs and outputs
|
154 |
+
|
155 |
+
## Pre-imported Libraries:
|
156 |
+
- `plt` for matplotlib
|
157 |
+
- `np` for numpy
|
158 |
+
- `pd` for pandas
|
159 |
+
- `sns` for seaborn
|
160 |
+
- `px` for plotly express
|
161 |
|
162 |
## Tips:
|
163 |
+
- Use the sample code dropdown for quick examples
|
164 |
+
- Your plot will automatically be displayed if you use plotting functions
|
165 |
+
- Adjust the timeout if your code needs more execution time
|
166 |
+
- Use the formatting tab to clean up your code structure
|
167 |
""")
|
168 |
|
169 |
# Launch the interface
|