kedimestan commited on
Commit
e760057
·
verified ·
1 Parent(s): b13bccc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -48
app.py CHANGED
@@ -1,76 +1,122 @@
1
  import gradio as gr
2
  import pandas as pd
3
- from vega_datasets import data
 
4
 
5
- def update_dropdowns(csv_file):
 
 
 
 
 
 
 
6
  if csv_file is None:
7
- return gr.Dropdown(choices=[]), gr.Dropdown(choices=[])
8
  df = pd.read_csv(csv_file.name)
9
  numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
10
  return gr.Dropdown(choices=numeric_cols), gr.Dropdown(choices=numeric_cols)
11
 
12
- def plot_selection(selection, df):
13
- if selection is None or df is None:
14
- return pd.DataFrame()
15
- return df.iloc[[i["index"] for i in selection]]
16
-
17
- def create_scatter_plot(csv_file, x_col, y_col):
18
  if csv_file is None or x_col is None or y_col is None:
19
- return None, None
 
 
 
20
 
21
- df = pd.read_csv(csv_file.name)
22
- plot = gr.ScatterPlot(
23
- value=df,
24
- x=x_col,
25
  y=y_col,
26
- title="Custom CSV Scatter Plot",
27
- x_title=x_col,
28
- y_title=y_col,
29
- tooltip=df.columns.tolist(),
30
- color_legend_title="Values",
31
- interactive=True,
32
- brush_radius=5 # Lasso/polygon seçim için
 
 
33
  )
34
- return plot, df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  with gr.Blocks() as app:
37
- gr.Markdown("## 📊 Custom CSV Scatter Plot with Selection")
38
 
39
  with gr.Row():
40
- csv_upload = gr.UploadButton(label="Upload CSV", file_types=[".csv"])
41
- x_axis = gr.Dropdown(label="X Axis Column")
42
- y_axis = gr.Dropdown(label="Y Axis Column")
43
 
44
  with gr.Row():
45
- plot = gr.ScatterPlot(interactive=True, brush_radius=5)
46
- selected_data = gr.DataFrame(label="Selected Points")
 
 
47
 
48
- df_store = gr.State()
49
-
50
- # CSV yüklendiğinde dropdown'ları güncelle
51
  csv_upload.upload(
52
- fn=update_dropdowns,
53
  inputs=csv_upload,
54
- outputs=[x_axis, y_axis]
55
  )
56
-
57
- # Eksenler seçildiğinde grafiği oluştur
58
- x_axis.change(
59
- fn=create_scatter_plot,
60
- inputs=[csv_upload, x_axis, y_axis],
61
- outputs=[plot, df_store]
62
  )
63
- y_axis.change(
64
- fn=create_scatter_plot,
65
- inputs=[csv_upload, x_axis, y_axis],
66
- outputs=[plot, df_store]
 
67
  )
68
-
69
- # Seçim yapıldığında verileri güncelle
70
  plot.select(
71
- fn=plot_selection,
72
- inputs=df_store,
73
- outputs=selected_data
74
  )
75
 
76
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import pandas as pd
3
+ import plotly.express as px
4
+ from sklearn.datasets import make_blobs
5
 
6
+ def create_dataset():
7
+ # Örnek veri oluştur
8
+ data, _ = make_blobs(n_samples=300, centers=3, n_features=2, random_state=42)
9
+ df = pd.DataFrame(data, columns=['X', 'Y'])
10
+ df['Category'] = ['A', 'B', 'C'] * 100
11
+ return df
12
+
13
+ def update_columns(csv_file):
14
  if csv_file is None:
15
+ return [gr.Dropdown(choices=[])] * 2
16
  df = pd.read_csv(csv_file.name)
17
  numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
18
  return gr.Dropdown(choices=numeric_cols), gr.Dropdown(choices=numeric_cols)
19
 
20
+ def create_plot(csv_file, x_col, y_col):
 
 
 
 
 
21
  if csv_file is None or x_col is None or y_col is None:
22
+ df = create_dataset()
23
+ x_col, y_col = 'X', 'Y'
24
+ else:
25
+ df = pd.read_csv(csv_file.name)
26
 
27
+ fig = px.scatter(
28
+ df,
29
+ x=x_col,
 
30
  y=y_col,
31
+ color='Category' if 'Category' in df.columns else None,
32
+ title="Interactive Scatter Plot with Polygon Selection",
33
+ hover_data=df.columns.tolist()
34
+ )
35
+
36
+ fig.update_layout(
37
+ dragmode='drawclosedpath', # Polygon çizim modu
38
+ newshape=dict(line_color='cyan'), # Çizim rengi
39
+ margin=dict(l=20, r=20, b=20, t=40)
40
  )
41
+
42
+ config = {
43
+ 'modeBarButtonsToAdd': [
44
+ 'drawclosedpath',
45
+ 'eraseshape'
46
+ ]
47
+ }
48
+ return fig, df
49
+
50
+ def get_selected_points(plot_data, df):
51
+ if plot_data is None or 'range' in plot_data:
52
+ return pd.DataFrame()
53
+
54
+ selected_points = []
55
+ for shape in plot_data.get('shapes', []):
56
+ if shape['type'] == 'path':
57
+ x_path = shape['path'].split('L')
58
+ polygon_points = [tuple(map(float, point.split(','))) for point in x_path]
59
+
60
+ # Polygon içinde kalan noktaları bul
61
+ for idx, row in df.iterrows():
62
+ if is_point_in_polygon((row['X'], row['Y']), polygon_points):
63
+ selected_points.append(idx)
64
+
65
+ return df.iloc[selected_points] if selected_points else pd.DataFrame()
66
+
67
+ def is_point_in_polygon(point, polygon):
68
+ # Ray casting algoritması ile nokta-polygon çakışma kontrolü
69
+ x, y = point
70
+ inside = False
71
+ n = len(polygon)
72
+
73
+ for i in range(n):
74
+ j = (i + 1) % n
75
+ xi, yi = polygon[i]
76
+ xj, yj = polygon[j]
77
+
78
+ intersect = ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
79
+ if intersect:
80
+ inside = not inside
81
+
82
+ return inside
83
 
84
  with gr.Blocks() as app:
85
+ gr.Markdown("## 🔷 Polygon ile Veri Seçimi")
86
 
87
  with gr.Row():
88
+ csv_upload = gr.UploadButton(label="CSV Yükle", file_types=[".csv"])
89
+ x_dropdown = gr.Dropdown(label="X Ekseni")
90
+ y_dropdown = gr.Dropdown(label="Y Ekseni")
91
 
92
  with gr.Row():
93
+ plot = gr.Plot(label="Scatter Plot")
94
+ selected_table = gr.DataFrame(label="Seçilen Veriler")
95
+
96
+ df_state = gr.State()
97
 
 
 
 
98
  csv_upload.upload(
99
+ fn=update_columns,
100
  inputs=csv_upload,
101
+ outputs=[x_dropdown, y_dropdown]
102
  )
103
+
104
+ x_dropdown.change(
105
+ fn=create_plot,
106
+ inputs=[csv_upload, x_dropdown, y_dropdown],
107
+ outputs=[plot, df_state]
 
108
  )
109
+
110
+ y_dropdown.change(
111
+ fn=create_plot,
112
+ inputs=[csv_upload, x_dropdown, y_dropdown],
113
+ outputs=[plot, df_state]
114
  )
115
+
 
116
  plot.select(
117
+ fn=get_selected_points,
118
+ inputs=df_state,
119
+ outputs=selected_table
120
  )
121
 
122
  if __name__ == "__main__":