Spaces:
Running
Running
Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+123
- requirements.txtAdded+6
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import gradio as grimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom io import StringIOimport sysimport contextlibfrom sklearn import datasets, metrics, model_selection, preprocessingimport warningswarnings.filterwarnings('ignore')
# Capture output helper@contextlib.contextmanagerdef capture_output(): new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
def execute_code(code: str): """ Execute the provided Python code and return the output """ # Initialize output components output_text = "" output_plot = None output_df = None # Create a namespace for code execution namespace = { 'np': np, 'pd': pd, 'plt': plt, 'sns': sns, 'datasets': datasets, 'metrics': metrics, 'model_selection': model_selection, 'preprocessing': preprocessing } try: # Capture print outputs with capture_output() as (out, err): # Execute the code exec(code, namespace) # Capture print statements output_text = out.getvalue() if err.getvalue(): output_text += "\nErrors:\n" + err.getvalue() # Check if there's a plot if plt.gcf().axes: output_plot = plt.gcf() plt.close() # Check for DataFrame output for var in namespace: if isinstance(namespace[var], pd.DataFrame): output_df = namespace[var] break except Exception as e: output_text = f"Error: {str(e)}" return output_text, output_plot, output_df
# Create the Gradio interfacewith gr.Blocks() as demo: gr.Markdown(""" # Python Data Science Code Executor Execute Python code with access to common data science libraries: - NumPy (np) - Pandas (pd) - Matplotlib (plt) - Seaborn (sns) - Scikit-learn (datasets, metrics, model_selection, preprocessing) """) with gr.Row(): with gr.Column(): code_input = gr.Code( label="Python Code", language="python", value="""# Example: Load and visualize iris datasetfrom sklearn.datasets import load_irisiris = load_iris()df = pd.DataFrame(iris.data, columns=iris.feature_names)df['target'] = iris.target
# Create a scatter plotplt.figure(figsize=(10, 6))plt.scatter(df['sepal length (cm)'], df['sepal width (cm)'], c=df['target'])plt.xlabel('Sepal Length (cm)')plt.ylabel('Sepal Width (cm)')plt.title('Iris Dataset - Sepal Length vs Width')
# Print first few rowsprint("First 5 rows of the dataset:")print(df.head())""" ) run_button = gr.Button("Execute Code", variant="primary") with gr.Column(): output_text = gr.Textbox(label="Output", lines=5) output_plot = gr.Plot(label="Plot Output") output_df = gr.Dataframe(label="DataFrame Output") # Handle code execution run_button.click( fn=execute_code, inputs=[code_input], outputs=[output_text, output_plot, output_df] )
# Launch the appif __name__ == "__main__": demo.launch()123456gradio>=4.0.0numpy>=1.24.0pandas>=2.0.0matplotlib>=3.7.0seaborn>=0.12.0scikit-learn>=1.2.0 app.pyAdded+123
requirements.txtAdded+6