Spaces:
Runtime error
Runtime error
File size: 2,297 Bytes
c6379ae 9be415c 9239ab3 c6379ae 9239ab3 f305b38 9239ab3 f305b38 9239ab3 f305b38 9239ab3 ee16303 9239ab3 ee16303 9239ab3 ee16303 9239ab3 ee16303 9239ab3 ee16303 9239ab3 f305b38 |
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
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() |