Spaces:
Runtime error
Runtime error
import gradio as gr | |
import pandas as pd | |
import numpy as np | |
from shapely.geometry import Point, Polygon | |
def load_csv(file): | |
return pd.read_csv(file.name) | |
def update_dropdowns(df): | |
return gr.Dropdown(choices=df.columns.tolist()), gr.Dropdown(choices=df.columns.tolist()) | |
def create_plot(df, x_col, y_col): | |
if df is None or x_col is None or y_col is None: | |
return None | |
return gr.ScatterPlot.update( | |
value=pd.DataFrame({x_col: df[x_col], y_col: df[y_col]}), | |
x=x_col, | |
y=y_col, | |
title=f"{x_col} vs {y_col}", | |
interactive=True, | |
tooltip=[x_col, y_col] | |
) | |
def find_points_in_polygon(selected_data, df, x_col, y_col): | |
if not selected_data or not x_col or not y_col: | |
return pd.DataFrame() | |
# Extract polygon points from selection | |
polygon_points = [(point["x"], point["y"]) for point in selected_data["points"]] | |
# Create Shapely objects | |
polygon = Polygon(polygon_points) | |
points = [Point(row[x_col], row[y_col]) for _, row in df.iterrows()] | |
# Find points inside polygon | |
inside_indices = [i for i, point in enumerate(points) if polygon.contains(point)] | |
return df.iloc[inside_indices] | |
with gr.Blocks() as demo: | |
gr.Markdown("## CSV Data Explorer with Polygon Selection") | |
# Store DataFrame and polygon points | |
df_state = gr.State() | |
polygon_state = gr.State([]) | |
with gr.Row(): | |
csv_upload = gr.File(label="Upload CSV", file_types=[".csv"]) | |
x_col = gr.Dropdown(label="X Column") | |
y_col = gr.Dropdown(label="Y Column") | |
plot = gr.ScatterPlot(interactive=True, label="Scatter Plot") | |
results = gr.DataFrame(label="Points in Polygon") | |
# Event handlers | |
csv_upload.upload( | |
load_csv, | |
inputs=csv_upload, | |
outputs=df_state | |
).then( | |
update_dropdowns, | |
inputs=df_state, | |
outputs=[x_col, y_col] | |
) | |
x_col.change( | |
create_plot, | |
inputs=[df_state, x_col, y_col], | |
outputs=plot | |
) | |
y_col.change( | |
create_plot, | |
inputs=[df_state, x_col, y_col], | |
outputs=plot | |
) | |
plot.select( | |
find_points_in_polygon, | |
inputs=[df_state, x_col, y_col], | |
outputs=results | |
) | |
demo.launch() |