dotBlood / app.py
kedimestan's picture
Update app.py
b1a8097 verified
raw
history blame
2.86 kB
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
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, polygon_points=None):
if df is None or x_col is None or y_col is None:
return None
fig = go.Figure()
# Ana scatter plot
fig.add_trace(go.Scatter(
x=df[x_col],
y=df[y_col],
mode='markers',
name='Data Points',
marker=dict(color='blue')
))
# Polygon çizgileri
if polygon_points and len(polygon_points) >= 2:
fig.add_trace(go.Scatter(
x=[p[0] for p in polygon_points],
y=[p[1] for p in polygon_points],
mode='lines+markers',
line=dict(color='red', width=2),
marker=dict(color='red', size=8),
name='Polygon'
))
fig.update_layout(
title=f"{x_col} vs {y_col}",
dragmode='drawclosedpath',
showlegend=False
)
return fig
def handle_click(click_data, df, x_col, y_col, polygon_points):
if not click_data or not df.empty:
return [], pd.DataFrame()
# Tıklanan noktayı al
point = (click_data['points'][0]['x'], click_data['points'][0]['y'])
new_points = polygon_points + [point]
# Polygon tamamlandıysa içinde kalan noktaları bul
if len(new_points) >= 3 and new_points[0] == new_points[-1]:
polygon = Polygon(new_points)
mask = df.apply(lambda row: polygon.contains(Point(row[x_col], row[y_col])), axis=1)
return [], df[mask]
return new_points, pd.DataFrame()
with gr.Blocks() as demo:
gr.Markdown("## Interactive Polygon Selection Tool")
df_state = gr.State(pd.DataFrame())
polygon_state = gr.State([])
with gr.Row():
csv_upload = gr.File(label="CSV Yükle", file_types=[".csv"])
x_col = gr.Dropdown(label="X Sütunu")
y_col = gr.Dropdown(label="Y Sütunu")
plot = gr.Plot(label="Scatter Plot ve Polygon")
results = gr.DataFrame(label="Seçilen Veriler")
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, polygon_state],
outputs=plot
)
y_col.change(
create_plot,
inputs=[df_state, x_col, y_col, polygon_state],
outputs=plot
)
plot.select(
handle_click,
inputs=[df_state, x_col, y_col, polygon_state],
outputs=[polygon_state, results]
)
demo.launch()