Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567891011121314151617181920212210 unmodified lines3334353637381 unmodified line40414243444546474849505152535455565758596061626364656667686970717273747576777879806 unmodified lines878889909192939495969798993 unmodified linesimport importlibimport ioimport contextlibfrom pygments import highlightfrom pygments.lexers import PythonLexerfrom pygments.formatters import HtmlFormatterimport matplotlib.pyplot as pltimport numpy as npimport pandas as pd# Function to install packages dynamicallydef install_package(package):subprocess.check_call([sys.executable, "-m", "pip", "install", package])# Function to execute user code with output capturing and visualization supportdef execute_code(code, libraries):# Install librariesfor library in libraries.splitlines():if library.strip():10 unmodified lines'plt': plt,'np': np,'pd': pd,}exec(code, exec_globals)1 unmodified lineif plt.get_fignums():plt.savefig('plot.png')plt.close()return output.getvalue(), error_output.getvalue(), 'plot.png'else:return output.getvalue(), error_output.getvalue(), Noneexcept Exception as e:return "", str(e), None# Function to highlight Python codedef highlight_code(code):return highlight(code, PythonLexer(), HtmlFormatter(style="monokai"))# Define the Gradio interfacewith gr.Blocks(css=".gradio-container {background-color: #f0f0f0;}") as demo:gr.Markdown("# Advanced Python Code Executor")with gr.Tabs():with gr.TabItem("Code Execution"):with gr.Row():with gr.Column(scale=2):code_input = gr.Code(label="Python Code", language="python", lines=10)libraries_input = gr.TextArea(label="Libraries (one per line)", placeholder="e.g.\nrequests\nscipy", lines=3)execute_button = gr.Button("Run Code", variant="primary")with gr.Column(scale=1):output = gr.Textbox(label="Standard Output", lines=10)error_output = gr.Textbox(label="Error Output", lines=5)plot_output = gr.Image(label="Plot Output")with gr.TabItem("Code Highlighting"):code_to_highlight = gr.Code(label="Enter Python code to highlight", language="python", lines=10)highlight_button = gr.Button("Highlight Code")highlighted_code = gr.HTML(label="Highlighted Code")execute_button.click(fn=execute_code,inputs=[code_input, libraries_input],outputs=[output, error_output, plot_output])highlight_button.click(6 unmodified lines## Features:- Execute Python code with custom library imports- Capture and display standard output and error messages separately- Support for data visualization with matplotlib- Code highlighting for better readability- Tab-based interface for different functionalities## Tips:- Use `plt` for matplotlib, `np` for numpy, and `pd` for pandas (pre-imported)- Your plot will automatically be displayed if you use `plt.plot()` or similar functions""")# Launch the interface3 unmodified lines456789101112131415161718192021222324252610 unmodified lines37383940414243441 unmodified line4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371386 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681693 unmodified linesimport importlibimport ioimport contextlibimport tracebackfrom pygments import highlightfrom pygments.lexers import PythonLexerfrom pygments.formatters import HtmlFormatterimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as snsimport plotly.express as pximport black# Function to install packages dynamicallydef install_package(package):subprocess.check_call([sys.executable, "-m", "pip", "install", package])# Function to execute user code with output capturing and visualization supportdef execute_code(code, libraries, timeout):# Install librariesfor library in libraries.splitlines():if library.strip():10 unmodified lines'plt': plt,'np': np,'pd': pd,'sns': sns,'px': px,}exec(code, exec_globals)1 unmodified lineif plt.get_fignums():plt.savefig('plot.png')plt.close()return output.getvalue(), error_output.getvalue(), 'plot.png', Noneelif 'fig' in exec_globals and isinstance(exec_globals['fig'], px.Figure):exec_globals['fig'].write_image('plot.png')return output.getvalue(), error_output.getvalue(), 'plot.png', Noneelse:return output.getvalue(), error_output.getvalue(), None, Noneexcept Exception as e:return "", traceback.format_exc(), None, None# Function to highlight Python codedef highlight_code(code):return highlight(code, PythonLexer(), HtmlFormatter(style="monokai"))# Function to format code using Blackdef format_code(code):try:formatted_code = black.format_str(code, mode=black.FileMode())return formatted_code, "Code formatted successfully!"except Exception as e:return code, f"Formatting error: {str(e)}"# Function to generate sample codedef generate_sample_code(sample_type):samples = {"Basic": "print('Hello, World!')\n\nfor i in range(5):\n print(i)","Numpy": "import numpy as np\n\narr = np.array([1, 2, 3, 4, 5])\nprint(arr.mean())\nprint(arr.std())","Pandas": "import pandas as pd\n\ndf = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})\nprint(df.describe())","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')","Seaborn": "import seaborn as sns\n\ntips = sns.load_dataset('tips')\nsns.scatterplot(x='total_bill', y='tip', data=tips)","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()"}return samples.get(sample_type, "")# Define the Gradio interfacewith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# Advanced Python Code Executor and Formatter")with gr.Tabs():with gr.TabItem("Code Execution"):with gr.Row():with gr.Column(scale=2):code_input = gr.Code(label="Python Code", language="python", lines=15)with gr.Row():libraries_input = gr.TextArea(label="Libraries (one per line)", placeholder="e.g.\nrequests\nscipy", lines=2)timeout_input = gr.Number(label="Timeout (seconds)", value=30, minimum=1, maximum=300)with gr.Row():execute_button = gr.Button("Run Code", variant="primary")clear_button = gr.Button("Clear", variant="secondary")sample_dropdown = gr.Dropdown(choices=["Basic", "Numpy", "Pandas", "Matplotlib", "Seaborn", "Plotly"], label="Load Sample Code")with gr.Column(scale=1):output = gr.Textbox(label="Standard Output", lines=10)error_output = gr.Textbox(label="Error Output", lines=5)plot_output = gr.Image(label="Plot Output")file_output = gr.File(label="Generated Files")with gr.TabItem("Code Formatting"):code_to_format = gr.Code(label="Enter Python code to format", language="python", lines=15)format_button = gr.Button("Format Code")formatted_code = gr.Code(label="Formatted Code", language="python", lines=15)format_message = gr.Textbox(label="Formatting Message")with gr.TabItem("Code Highlighting"):code_to_highlight = gr.Code(label="Enter Python code to highlight", language="python", lines=15)highlight_button = gr.Button("Highlight Code")highlighted_code = gr.HTML(label="Highlighted Code")execute_button.click(fn=execute_code,inputs=[code_input, libraries_input, timeout_input],outputs=[output, error_output, plot_output, file_output])clear_button.click(lambda: ("", "", "", None, None),outputs=[code_input, output, error_output, plot_output, file_output])sample_dropdown.change(fn=generate_sample_code,inputs=[sample_dropdown],outputs=[code_input])format_button.click(fn=format_code,inputs=[code_to_format],outputs=[formatted_code, format_message])highlight_button.click(6 unmodified lines## Features:- Execute Python code with custom library imports- Capture and display standard output and error messages separately- Support for data visualization with matplotlib, seaborn, and plotly- Code formatting using Black- Code highlighting for better readability- Sample code generator for quick starts- Timeout setting for code execution- Clear button to reset inputs and outputs## Pre-imported Libraries:- `plt` for matplotlib- `np` for numpy- `pd` for pandas- `sns` for seaborn- `px` for plotly express## Tips:- Use the sample code dropdown for quick examples- Your plot will automatically be displayed if you use plotting functions- Adjust the timeout if your code needs more execution time- Use the formatting tab to clean up your code structure""")# Launch the interface
app.py+86-16