cwadayi commited on
Commit
2b88ac2
·
verified ·
1 Parent(s): 8c252e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -295
app.py CHANGED
@@ -5,6 +5,7 @@ import tempfile
5
  from datetime import datetime, timedelta
6
  from dateutil import tz
7
  import time
 
8
 
9
  import gradio as gr
10
  import pandas as pd
@@ -22,6 +23,10 @@ from grafanalib.core import (
22
  Dashboard, Graph, Row, Target, YAxis, YAxes, Time, BarGauge
23
  )
24
 
 
 
 
 
25
  TAIPEI = tz.gettz("Asia/Taipei")
26
 
27
  # -----------------------------
@@ -34,36 +39,23 @@ DRIVE_PRESETS = [
34
  ]
35
 
36
  def normalize_drive_url(url: str) -> str:
37
- """
38
- 接受 Google Drive / Google Sheets 各式分享連結,回傳可直接給 pandas 讀取 CSV 的 URL。
39
- - Sheets: .../spreadsheets/d/<ID>/edit → .../export?format=csv
40
- - Drive File: .../file/d/<ID>/view → https://drive.google.com/uc?export=download&id=<ID>
41
- """
42
  if not isinstance(url, str) or not url.strip():
43
  raise ValueError("請提供有效的 Google 連結")
44
-
45
  url = url.strip()
46
-
47
- # Sheets
48
  m = re.search(r"https://docs\.google\.com/spreadsheets/d/([a-zA-Z0-9-_]+)", url)
49
  if m:
50
  sheet_id = m.group(1)
51
  return f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv"
52
-
53
- # Drive file
54
  m = re.search(r"https://drive\.google\.com/file/d/([a-zA-Z0-9-_]+)/", url)
55
  if m:
56
  file_id = m.group(1)
57
  return f"https://drive.google.com/uc?export=download&id={file_id}"
58
-
59
  return url
60
 
61
-
62
  # -----------------------------
63
  # Demo / Data loading with dynamic update
64
  # -----------------------------
65
  def make_demo_dataframe(last_time=None) -> tuple[pd.DataFrame, datetime]:
66
- """隨機示範資料:含經緯度 + pid,模擬實時更新"""
67
  if last_time is None:
68
  last_time = datetime.now(tz=TAIPEI) - timedelta(minutes=60)
69
  else:
@@ -73,19 +65,12 @@ def make_demo_dataframe(last_time=None) -> tuple[pd.DataFrame, datetime]:
73
  cnt = np.random.randint(0, 11, size=len(times))
74
  lats = np.random.uniform(21.8, 25.3, size=len(times))
75
  lons = np.random.uniform(120.0, 122.0, size=len(times))
76
- df = pd.DataFrame({
77
- "time": times,
78
- "amplitude": amp,
79
- "count": cnt,
80
- "lat": lats,
81
- "lon": lons
82
- })
83
  df["pid"] = np.arange(len(df))
 
84
  return df, last_time
85
 
86
-
87
  def _finalize_time(df: pd.DataFrame) -> pd.DataFrame:
88
- """確保 time 欄位有時區、排序"""
89
  time_col = next((c for c in ["time", "timestamp", "datetime", "date"] if c in df.columns), None)
90
  if time_col is None:
91
  raise ValueError("資料需包含時間欄位(time/timestamp/datetime/date 其一)")
@@ -97,83 +82,50 @@ def _finalize_time(df: pd.DataFrame) -> pd.DataFrame:
97
  df["time"] = df["time"].dt.tz_convert(TAIPEI)
98
  return df.sort_values("time").reset_index(drop=True)
99
 
100
-
101
  def load_csv(file: gr.File | None) -> pd.DataFrame:
102
- """讀上傳 CSV"""
103
  try:
104
  df = pd.read_csv(file.name)
105
- df = _finalize_time(df)
106
- # 若無 lat/lon,補隨機(避免地圖空白)
107
- if "lat" not in df.columns or "lon" not in df.columns:
108
- n = len(df)
109
- df["lat"] = np.random.uniform(21.8, 25.3, size=n)
110
- df["lon"] = np.random.uniform(120.0, 122.0, size=n)
111
- if "pid" not in df.columns:
112
- df["pid"] = np.arange(len(df))
113
- return df
114
  except Exception as e:
115
  raise ValueError(f"CSV 載入失敗:{str(e)}")
116
 
117
-
118
  def load_drive_csv(sheet_or_file_url: str) -> pd.DataFrame:
119
- """從 Google Sheets 或 Google Drive File 讀 CSV"""
120
  try:
121
  url = normalize_drive_url(sheet_or_file_url)
122
  df = pd.read_csv(url)
123
- df = _finalize_time(df)
124
- if "lat" not in df.columns or "lon" not in df.columns:
125
- n = len(df)
126
- df["lat"] = np.random.uniform(21.8, 25.3, size=n)
127
- df["lon"] = np.random.uniform(120.0, 122.0, size=n)
128
- if "pid" not in df.columns:
129
- df["pid"] = np.arange(len(df))
130
- return df
131
  except Exception as e:
132
  raise ValueError(f"Google 連結載入失敗:{str(e)}")
133
 
134
-
135
  def load_data(source: str, file: gr.File | None = None, sheet_url: str = "", last_time=None) -> tuple[pd.DataFrame, datetime]:
136
- """依來源載入資料:demo / upload / drive,支援動態更新"""
137
  if source == "drive":
138
  if not sheet_url:
139
  raise ValueError("請選擇 Google 連結")
140
- df = load_drive_csv(sheet_url)
141
- return df, None
142
  elif source == "upload":
143
  if file is None:
144
  raise ValueError("請上傳 CSV 檔")
145
- df = load_csv(file)
146
- return df, None
147
  else:
148
  return make_demo_dataframe(last_time)
149
 
150
-
151
  # -----------------------------
152
  # 新功能:資料過濾
153
  # -----------------------------
154
  def filter_data(df: pd.DataFrame, start_time: str, end_time: str) -> pd.DataFrame:
155
- """根據時間範圍過濾資料"""
156
  if start_time:
157
  df = df[df["time"] >= pd.to_datetime(start_time).tz_localize(TAIPEI)]
158
  if end_time:
159
  df = df[df["time"] <= pd.to_datetime(end_time).tz_localize(TAIPEI)]
160
  return df
161
 
162
-
163
  # -----------------------------
164
- # grafanalib JSON builder (新增 BarGauge)
165
  # -----------------------------
166
  def build_grafanalib_dashboard(series_columns: list[str], dual_axis: bool, rolling_window: int) -> dict:
167
- panels = []
168
- panels.append(
169
- Graph(
170
- title=f"{series_columns[0]}",
171
- dataSource="(example)",
172
- targets=[Target(expr=f"{series_columns[0]}", legendFormat=series_columns[0])],
173
- lines=True, bars=False, points=False,
174
- yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short")),
175
- )
176
- )
177
  if len(series_columns) > 1:
178
  targets = [Target(expr=f"{series_columns[1]}", legendFormat=series_columns[1])]
179
  lines, bars, title = False, True, f"{series_columns[1]} (bar)"
@@ -181,40 +133,12 @@ def build_grafanalib_dashboard(series_columns: list[str], dual_axis: bool, rolli
181
  targets.append(Target(expr=f"{series_columns[0]}", legendFormat=f"{series_columns[0]} (line)"))
182
  lines, bars = True, True
183
  title = f"{series_columns[1]} (bar) + {series_columns[0]} (line)"
184
- panels.append(
185
- Graph(
186
- title=title,
187
- dataSource="(example)",
188
- targets=targets,
189
- lines=lines, bars=bars, points=False,
190
- yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short")),
191
- )
192
- )
193
- panels.append(
194
- Graph(
195
- title=f"{series_columns[0]} rolling({rolling_window})",
196
- dataSource="(example)",
197
- targets=[Target(expr=f"{series_columns[0]}_rolling{rolling_window}",
198
- legendFormat=f"{series_columns[0]}_rolling{rolling_window}")],
199
- lines=True, bars=False, points=False,
200
- yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short")),
201
- )
202
- )
203
- # 新增 BarGauge 面板,顯示最新值
204
- panels.append(
205
- BarGauge(
206
- title=f"Latest {series_columns[0]}",
207
- dataSource="(example)",
208
- targets=[Target(expr=f"last({series_columns[0]})", legendFormat=series_columns[0])],
209
- )
210
- )
211
- return Dashboard(
212
- title="Grafana-like Demo (grafanalib + Gradio)",
213
- rows=[Row(panels=panels)],
214
- timezone="browser",
215
- time=Time("now-1h", "now"),
216
- ).to_json_data()
217
-
218
 
219
  # -----------------------------
220
  # Matplotlib helpers
@@ -229,14 +153,12 @@ def _style_time_axis(ax):
229
  ax.grid(True, which="major", alpha=0.25)
230
  plt.margins(x=0.02, y=0.05)
231
 
232
-
233
  def _normalize_times(series: pd.Series) -> pd.Series:
234
  s = series.copy()
235
  if getattr(s.dt, "tz", None) is not None:
236
  s = s.dt.tz_convert("UTC").dt.tz_localize(None)
237
  return s
238
 
239
-
240
  def render_line(df, col):
241
  times = _normalize_times(df["time"])
242
  fig, ax = plt.subplots(figsize=(6, 3))
@@ -248,7 +170,6 @@ def render_line(df, col):
248
  fig.tight_layout()
249
  return fig
250
 
251
-
252
  def render_bar_or_dual(df, second_col, first_col, dual_axis):
253
  times = _normalize_times(df["time"])
254
  x = mdates.date2num(times.dt.to_pydatetime().tolist())
@@ -270,7 +191,6 @@ def render_bar_or_dual(df, second_col, first_col, dual_axis):
270
  fig.tight_layout()
271
  return fig
272
 
273
-
274
  def render_rolling(df, col, window=5):
275
  times = _normalize_times(df["time"])
276
  roll_col = f"{col}_rolling{window}"
@@ -285,9 +205,8 @@ def render_rolling(df, col, window=5):
285
  fig.tight_layout()
286
  return fig, df
287
 
288
-
289
  # -----------------------------
290
- # 新增 Gauge 渲染 (使用 Matplotlib patches)
291
  # -----------------------------
292
  def degree_range(n):
293
  start = np.linspace(0, 180, n + 1, endpoint=True)[0:-1]
@@ -295,59 +214,30 @@ def degree_range(n):
295
  mid_points = start + ((end - start) / 2.)
296
  return np.c_[start, end], mid_points
297
 
298
-
299
  def rot_text(ang):
300
  rotation = np.degrees(np.radians(ang) * np.pi / np.pi - np.radians(90))
301
  return rotation
302
 
303
-
304
  def render_gauge(df, col):
305
  value = df[col].iloc[-1] if not df.empty else 0
306
  min_val, max_val = df[col].min(), df[col].max()
307
  normalized = (value - min_val) / (max_val - min_val + 1e-9) if max_val > min_val else 0
308
-
309
  labels = ['LOW', 'MEDIUM', 'HIGH']
310
  N = len(labels)
311
- colors = ['#007A00', '#FFCC00', '#ED1C24'] # Green, Yellow, Red
312
-
313
- if normalized < 0.33:
314
- arrow = 1
315
- elif normalized < 0.66:
316
- arrow = 2
317
- else:
318
- arrow = 3
319
-
320
  fig, ax = plt.subplots(figsize=(5, 3.5))
321
-
322
  ang_range, mid_points = degree_range(N)
323
-
324
  labels = labels[::-1]
325
-
326
- patches = []
327
- for ang, c in zip(ang_range, colors):
328
- patches.append(Wedge((0., 0.), .4, *ang, facecolor='w', lw=2))
329
- patches.append(Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5))
330
-
331
  [ax.add_patch(p) for p in patches]
332
-
333
  for mid, lab in zip(mid_points, labels):
334
- ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)), lab,
335
- horizontalalignment='center', verticalalignment='center', fontsize=12,
336
- fontweight='bold', rotation=rot_text(mid))
337
-
338
- r = Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2)
339
- ax.add_patch(r)
340
-
341
- ax.text(0, -0.05, f"Latest {col}: {value:.2f}", horizontalalignment='center',
342
- verticalalignment='center', fontsize=12, fontweight='bold')
343
-
344
  pos = mid_points[abs(arrow - N)]
345
- ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)),
346
- width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k')
347
-
348
- ax.add_patch(FancyArrowPatch((0, 0), (0.01 * np.cos(np.radians(pos)), 0.01 * np.sin(np.radians(pos))),
349
- mutation_scale=10, fc='k', ec='k'))
350
-
351
  ax.set_frame_on(False)
352
  ax.axes.set_xticks([])
353
  ax.axes.set_yticks([])
@@ -355,195 +245,113 @@ def render_gauge(df, col):
355
  plt.tight_layout()
356
  return fig
357
 
358
-
359
  # -----------------------------
360
- # Folium helpers (map + legend + heatmap)
361
  # -----------------------------
362
  def _to_hex_color(value: float, cmap=cm.viridis) -> str:
363
  rgba = cmap(value)
364
  return "#{:02x}{:02x}{:02x}".format(int(rgba[0]*255), int(rgba[1]*255), int(rgba[2]*255))
365
 
366
-
367
- def render_map_folium(
368
- df: pd.DataFrame,
369
- value_col: str = "amplitude",
370
- size_col: str = "count",
371
- cmap_name: str = "viridis",
372
- tiles: str = "OpenStreetMap",
373
- show_heatmap: bool = False
374
- ) -> str:
375
  if df.empty:
376
  return "<p>無資料可顯示地圖</p>"
377
  center_lat, center_lon = df["lat"].mean(), df["lon"].mean()
378
  m = folium.Map(location=[center_lat, center_lon], zoom_start=7, tiles=tiles)
379
-
380
  vmin, vmax = df[value_col].min(), df[value_col].max()
381
  cmap = getattr(cm, cmap_name)
382
-
383
- colormap = bcm.LinearColormap(
384
- [_to_hex_color(i, cmap) for i in np.linspace(0, 1, 256)],
385
- vmin=vmin, vmax=vmax
386
- )
387
  colormap.caption = f"{value_col} (color scale)"
388
  colormap.add_to(m)
389
-
390
  if show_heatmap:
391
- # 添加熱圖層
392
  heat_data = [[row["lat"], row["lon"], row[value_col]] for _, row in df.iterrows()]
393
  plugins.HeatMap(heat_data, radius=15, blur=10).add_to(m)
394
  else:
395
- # 原有 CircleMarker
396
  for _, row in df.iterrows():
397
  norm_val = (row[value_col] - vmin) / (vmax - vmin + 1e-9)
398
- popup_html = (
399
- f"<b>#ID:</b> {int(row['pid'])}<br>"
400
- f"<b>time:</b> {pd.to_datetime(row['time']).strftime('%Y-%m-%d %H:%M:%S')}<br>"
401
- f"<b>{value_col}:</b> {row[value_col]:.4f}<br>"
402
- f"<b>{size_col}:</b> {row[size_col]}<br>"
403
- f"<b>lat/lon:</b> {row['lat']:.5f}, {row['lon']:.5f}"
404
- )
405
- folium.CircleMarker(
406
- location=[row["lat"], row["lon"]],
407
- radius=row[size_col] + 3,
408
- color="black",
409
- weight=1,
410
- fill=True,
411
- fill_opacity=0.7,
412
- fill_color=_to_hex_color(norm_val, cmap),
413
- popup=folium.Popup(popup_html, max_width=300),
414
- ).add_to(m)
415
-
416
  return m._repr_html_()
417
 
418
-
419
  # -----------------------------
420
  # Detail helpers
421
  # -----------------------------
422
  def make_point_choices(df: pd.DataFrame) -> list[str]:
423
- labels = []
424
- for _, r in df.iterrows():
425
- t = pd.to_datetime(r["time"]).strftime("%H:%M:%S")
426
- labels.append(f"#{int(r['pid'])} | {t} | amp={r.get('amplitude', 0):.3f} cnt={int(r.get('count', 0))}")
427
- return labels
428
-
429
 
430
  def pick_detail(df: pd.DataFrame, choice: str) -> pd.DataFrame:
431
  if not choice:
432
  return pd.DataFrame()
433
  try:
434
- pid_str = choice.split("|")[0].strip().lstrip("#")
435
- pid = int(pid_str)
436
- row = df[df["pid"] == pid]
437
- return row.reset_index(drop=True)
438
  except Exception:
439
  return pd.DataFrame()
440
 
441
-
442
  # -----------------------------
443
  # Main pipeline with dynamic update
444
  # -----------------------------
445
  def pipeline(source, file, sheet_url, series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice, start_time, end_time, show_heatmap, last_time=None):
446
  try:
447
  df, new_last_time = load_data(source, file, sheet_url, last_time)
448
- df = filter_data(df, start_time, end_time) # 新增過濾
449
  numeric_cols = [c for c in df.columns if c not in ["time", "lat", "lon", "pid"] and pd.api.types.is_numeric_dtype(df[c])]
450
- chosen = [c for c in (series_choice or numeric_cols[:2]) if c in numeric_cols]
451
- if not chosen:
452
- chosen = numeric_cols[:2]
453
  if not chosen:
454
  raise ValueError("無有效數值欄位可視覺化")
455
-
456
  dash_json = build_grafanalib_dashboard(chosen, bool(dual_axis), int(rolling_window))
457
  dash_json_str = json.dumps(dash_json, ensure_ascii=False, indent=2, default=str)
458
  with tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w", encoding="utf-8") as f:
459
  f.write(dash_json_str)
460
  json_path = f.name
461
-
462
  fig1 = render_line(df, chosen[0])
463
  fig2 = render_bar_or_dual(df, chosen[1], chosen[0], bool(dual_axis)) if len(chosen) > 1 else plt.figure()
464
  fig3, df_with_roll = render_rolling(df.copy(), chosen[0], int(rolling_window))
465
  fig4 = render_gauge(df, chosen[0])
466
-
467
- map_html = render_map_folium(df, value_col=chosen[0], size_col=chosen[1] if len(chosen) > 1 else "count",
468
- cmap_name=cmap_choice, tiles=tiles_choice, show_heatmap=bool(show_heatmap))
469
-
470
  point_choices = [] if show_heatmap else make_point_choices(df)
471
  default_choice = point_choices[0] if point_choices else ""
472
  detail_df = pick_detail(df, default_choice)
473
-
474
- demo_df = make_demo_dataframe()[0] # 只取 DataFrame 部分
475
  with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", encoding="utf-8") as f:
476
  demo_df.to_csv(f, index=False)
477
  demo_csv_path = f.name
478
-
479
- return (
480
- fig1, fig2, plot3, plot4, map_out,
481
- dash_json_str, json_path, df_with_roll,
482
- demo_csv_file,
483
- gr.Dropdown(choices=point_choices, value=default_choice),
484
- detail_df,
485
- "", # 錯誤訊息清空
486
- new_last_time
487
- )
488
  except Exception as e:
489
- return (
490
- None, None, None, None, "<p>錯誤:無資料顯示</p>",
491
- "", None, pd.DataFrame(),
492
- None,
493
- gr.Dropdown(choices=[], value=None),
494
- pd.DataFrame(),
495
- str(e),
496
- last_time
497
- )
498
-
499
 
500
  def regenerate_demo(series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice, current_choice, start_time, end_time, show_heatmap, last_time):
501
  return pipeline("demo", None, "", series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice, start_time, end_time, show_heatmap, last_time)
502
 
503
-
504
  def update_detail(df: pd.DataFrame, choice: str):
505
  return pick_detail(df, choice)
506
 
507
-
508
  # -----------------------------
509
- # UI 優化:添加動態更新按鈕和間隔更新
510
  # -----------------------------
511
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
512
- gr.Markdown("## 動態時間序列 - Grafana-like Demo + Folium Map(支援 Google Drive / Sheets,新增熱圖與 Gauge)")
513
-
514
  with gr.Row():
515
  with gr.Column(scale=1):
516
  source_radio = gr.Radio(["upload", "drive", "demo"], label="資料來源", value="demo")
517
- file_in = gr.File(label="上傳 CSV(選 upload 時使用)", file_types=[".csv"])
518
- preset_dd = gr.Dropdown(
519
- label="Google 預設來源(3 個連結)",
520
- choices=DRIVE_PRESETS,
521
- value=DRIVE_PRESETS[0]
522
- )
523
  with gr.Row():
524
- start_time_in = gr.Textbox(label="開始時間 (YYYY-MM-DD HH:MM:SS)", placeholder="2023-01-01 00:00:00")
525
- end_time_in = gr.Textbox(label="結束時間 (YYYY-MM-DD HH:MM:SS)", placeholder="2023-12-31 23:59:59")
526
-
527
  with gr.Column(scale=1):
528
  series_multiselect = gr.CheckboxGroup(label="數值欄位", choices=[])
529
- dual_axis_chk = gr.Checkbox(label="第二面板啟用雙軸", value=False)
530
  rolling_dd = gr.Dropdown(label="Rolling window", choices=["3", "5", "10", "20"], value="5")
531
- cmap_dd = gr.Dropdown(label="地圖配色 (colormap)",
532
- choices=["viridis", "plasma", "inferno", "magma", "cividis", "coolwarm"],
533
- value="viridis")
534
- tiles_dd = gr.Dropdown(label="地圖底圖 (tiles)",
535
- choices=["OpenStreetMap", "Stamen Terrain", "Stamen Toner",
536
- "CartoDB positron", "CartoDB dark_matter"],
537
- value="OpenStreetMap")
538
- heatmap_chk = gr.Checkbox(label="顯示熱圖 (Heatmap)", value=False)
539
-
540
  with gr.Row():
541
  run_btn = gr.Button("產生 Dashboard", scale=1)
542
  update_btn = gr.Button("手動更新數據", scale=1)
543
  interval = gr.Slider(5, 60, value=10, step=5, label="自動更新間隔 (秒)")
544
-
545
  error_msg = gr.Markdown(value="", label="錯誤訊息", visible=True)
546
-
547
  with gr.Tabs():
548
  with gr.Tab("圖表"):
549
  with gr.Row():
@@ -556,24 +364,19 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
556
  plot3 = gr.Plot(label="3:Rolling Mean")
557
  with gr.Column(scale=1):
558
  plot4 = gr.Plot(label="4:Gauge")
559
-
560
  with gr.Tab("地圖"):
561
- map_out = gr.HTML(label="5:Geo Map (Interactive + Legend + Heatmap)")
562
-
563
  with gr.Tab("JSON & 檔案"):
564
  json_box = gr.Code(label="grafanalib Dashboard JSON", language="json")
565
  json_file = gr.File(label="下載 dashboard.json")
566
  demo_csv_file = gr.File(label="下載示範資料 demo.csv")
567
-
568
  with gr.Tab("資料預覽"):
569
- df_view = gr.Dataframe(label="資料預覽(含 rolling)", wrap=True)
570
-
571
  with gr.Tab("點位詳情"):
572
- gr.Markdown("### 🔎 點位詳情(對應地圖彈窗中的 #ID,熱圖模式下不可用)")
573
- point_selector = gr.Dropdown(label="選擇點位(#ID | 時間 | 值)", choices=[], value=None)
574
  detail_view = gr.Dataframe(label="選取點詳細資料", wrap=True)
575
 
576
- # 探勘欄位並更新 UI
577
  def probe_columns(source, file, preset_url, start_time, end_time):
578
  sheet_url = preset_url if source == "drive" else ""
579
  try:
@@ -584,54 +387,31 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
584
  except Exception as e:
585
  return gr.CheckboxGroup(choices=[]), pd.DataFrame(), str(e)
586
 
587
- source_radio.change(probe_columns, inputs=[source_radio, file_in, preset_dd, start_time_in, end_time_in], outputs=[series_multiselect, df_view, error_msg])
588
- file_in.change(probe_columns, inputs=[source_radio, file_in, preset_dd, start_time_in, end_time_in], outputs=[series_multiselect, df_view, error_msg])
589
- preset_dd.change(probe_columns, inputs=[source_radio, file_in, preset_dd, start_time_in, end_time_in], outputs=[series_multiselect, df_view, error_msg])
590
- start_time_in.change(probe_columns, inputs=[source_radio, file_in, preset_dd, start_time_in, end_time_in], outputs=[series_multiselect, df_view, error_msg])
591
- end_time_in.change(probe_columns, inputs=[source_radio, file_in, preset_dd, start_time_in, end_time_in], outputs=[series_multiselect, df_view, error_msg])
592
 
593
- # 初次載入
594
  demo.load(
595
  fn=lambda: pipeline("drive", None, DRIVE_PRESETS[0], [], False, "5", "viridis", "OpenStreetMap", "", "", False),
596
- outputs=[
597
- plot1, plot2, plot3, plot4, map_out,
598
- json_box, json_file, df_view,
599
- demo_csv_file,
600
- point_selector, detail_view,
601
- error_msg,
602
- gr.State(value=None)
603
- ]
604
  )
605
 
606
- # 產生 / 重新產生 / 動態更新
607
  run_btn.click(
608
  fn=pipeline,
609
  inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd, cmap_dd, tiles_dd, start_time_in, end_time_in, heatmap_chk, gr.State(value=None)],
610
- outputs=[
611
- plot1, plot2, plot3, plot4, map_out,
612
- json_box, json_file, df_view,
613
- demo_csv_file,
614
- point_selector, detail_view,
615
- error_msg,
616
- gr.State()
617
- ]
618
  )
619
 
620
  update_btn.click(
621
  fn=pipeline,
622
  inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd, cmap_dd, tiles_dd, start_time_in, end_time_in, heatmap_chk, gr.State()],
623
- outputs=[
624
- plot1, plot2, plot3, plot4, map_out,
625
- json_box, json_file, df_view,
626
- demo_csv_file,
627
- point_selector, detail_view,
628
- error_msg,
629
- gr.State()
630
- ]
631
  )
632
 
633
- # 自動更新邏輯
634
  def start_auto_update(interval):
 
635
  return gr.update(value=interval)
636
 
637
  interval.change(
@@ -650,13 +430,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
650
  }, intervalValue);
651
  }
652
  update();
 
 
 
 
 
653
  }
654
  startAutoUpdate();
655
- document.querySelector('input[type="range"]').addEventListener('input', function() {
656
- let newInterval = parseInt(this.value) * 1000;
657
- clearTimeout(window.updateTimeout);
658
- startAutoUpdate();
659
- });
660
  """
661
 
662
  point_selector.change(
@@ -666,4 +446,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
666
  )
667
 
668
  if __name__ == "__main__":
669
- demo.launch(server_name="0.0.0.0", server_port=7860) # 方便部署,綁定所有 IP
 
5
  from datetime import datetime, timedelta
6
  from dateutil import tz
7
  import time
8
+ import logging
9
 
10
  import gradio as gr
11
  import pandas as pd
 
23
  Dashboard, Graph, Row, Target, YAxis, YAxes, Time, BarGauge
24
  )
25
 
26
+ # 設置日誌
27
+ logging.basicConfig(level=logging.DEBUG)
28
+ logger = logging.getLogger(__name__)
29
+
30
  TAIPEI = tz.gettz("Asia/Taipei")
31
 
32
  # -----------------------------
 
39
  ]
40
 
41
  def normalize_drive_url(url: str) -> str:
 
 
 
 
 
42
  if not isinstance(url, str) or not url.strip():
43
  raise ValueError("請提供有效的 Google 連結")
 
44
  url = url.strip()
 
 
45
  m = re.search(r"https://docs\.google\.com/spreadsheets/d/([a-zA-Z0-9-_]+)", url)
46
  if m:
47
  sheet_id = m.group(1)
48
  return f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv"
 
 
49
  m = re.search(r"https://drive\.google\.com/file/d/([a-zA-Z0-9-_]+)/", url)
50
  if m:
51
  file_id = m.group(1)
52
  return f"https://drive.google.com/uc?export=download&id={file_id}"
 
53
  return url
54
 
 
55
  # -----------------------------
56
  # Demo / Data loading with dynamic update
57
  # -----------------------------
58
  def make_demo_dataframe(last_time=None) -> tuple[pd.DataFrame, datetime]:
 
59
  if last_time is None:
60
  last_time = datetime.now(tz=TAIPEI) - timedelta(minutes=60)
61
  else:
 
65
  cnt = np.random.randint(0, 11, size=len(times))
66
  lats = np.random.uniform(21.8, 25.3, size=len(times))
67
  lons = np.random.uniform(120.0, 122.0, size=len(times))
68
+ df = pd.DataFrame({"time": times, "amplitude": amp, "count": cnt, "lat": lats, "lon": lons})
 
 
 
 
 
 
69
  df["pid"] = np.arange(len(df))
70
+ logger.debug(f"Generated new data with last_time: {last_time}")
71
  return df, last_time
72
 
 
73
  def _finalize_time(df: pd.DataFrame) -> pd.DataFrame:
 
74
  time_col = next((c for c in ["time", "timestamp", "datetime", "date"] if c in df.columns), None)
75
  if time_col is None:
76
  raise ValueError("資料需包含時間欄位(time/timestamp/datetime/date 其一)")
 
82
  df["time"] = df["time"].dt.tz_convert(TAIPEI)
83
  return df.sort_values("time").reset_index(drop=True)
84
 
 
85
  def load_csv(file: gr.File | None) -> pd.DataFrame:
 
86
  try:
87
  df = pd.read_csv(file.name)
88
+ return _finalize_time(df)
 
 
 
 
 
 
 
 
89
  except Exception as e:
90
  raise ValueError(f"CSV 載入失敗:{str(e)}")
91
 
 
92
  def load_drive_csv(sheet_or_file_url: str) -> pd.DataFrame:
 
93
  try:
94
  url = normalize_drive_url(sheet_or_file_url)
95
  df = pd.read_csv(url)
96
+ return _finalize_time(df)
 
 
 
 
 
 
 
97
  except Exception as e:
98
  raise ValueError(f"Google 連結載入失敗:{str(e)}")
99
 
 
100
  def load_data(source: str, file: gr.File | None = None, sheet_url: str = "", last_time=None) -> tuple[pd.DataFrame, datetime]:
 
101
  if source == "drive":
102
  if not sheet_url:
103
  raise ValueError("請選擇 Google 連結")
104
+ return load_drive_csv(sheet_url), None
 
105
  elif source == "upload":
106
  if file is None:
107
  raise ValueError("請上傳 CSV 檔")
108
+ return load_csv(file), None
 
109
  else:
110
  return make_demo_dataframe(last_time)
111
 
 
112
  # -----------------------------
113
  # 新功能:資料過濾
114
  # -----------------------------
115
  def filter_data(df: pd.DataFrame, start_time: str, end_time: str) -> pd.DataFrame:
 
116
  if start_time:
117
  df = df[df["time"] >= pd.to_datetime(start_time).tz_localize(TAIPEI)]
118
  if end_time:
119
  df = df[df["time"] <= pd.to_datetime(end_time).tz_localize(TAIPEI)]
120
  return df
121
 
 
122
  # -----------------------------
123
+ # grafanalib JSON builder
124
  # -----------------------------
125
  def build_grafanalib_dashboard(series_columns: list[str], dual_axis: bool, rolling_window: int) -> dict:
126
+ panels = [
127
+ Graph(title=f"{series_columns[0]}", dataSource="(example)", targets=[Target(expr=f"{series_columns[0]}", legendFormat=series_columns[0])], lines=True, bars=False, points=False, yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short"))),
128
+ ]
 
 
 
 
 
 
 
129
  if len(series_columns) > 1:
130
  targets = [Target(expr=f"{series_columns[1]}", legendFormat=series_columns[1])]
131
  lines, bars, title = False, True, f"{series_columns[1]} (bar)"
 
133
  targets.append(Target(expr=f"{series_columns[0]}", legendFormat=f"{series_columns[0]} (line)"))
134
  lines, bars = True, True
135
  title = f"{series_columns[1]} (bar) + {series_columns[0]} (line)"
136
+ panels.append(Graph(title=title, dataSource="(example)", targets=targets, lines=lines, bars=bars, points=False, yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short"))))
137
+ panels.extend([
138
+ Graph(title=f"{series_columns[0]} rolling({rolling_window})", dataSource="(example)", targets=[Target(expr=f"{series_columns[0]}_rolling{rolling_window}", legendFormat=f"{series_columns[0]}_rolling{rolling_window}")], lines=True, bars=False, points=False, yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short"))),
139
+ BarGauge(title=f"Latest {series_columns[0]}", dataSource="(example)", targets=[Target(expr=f"last({series_columns[0]})", legendFormat=series_columns[0])]),
140
+ ])
141
+ return Dashboard(title="Grafana-like Demo (grafanalib + Gradio)", rows=[Row(panels=panels)], timezone="browser", time=Time("now-1h", "now")).to_json_data()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  # -----------------------------
144
  # Matplotlib helpers
 
153
  ax.grid(True, which="major", alpha=0.25)
154
  plt.margins(x=0.02, y=0.05)
155
 
 
156
  def _normalize_times(series: pd.Series) -> pd.Series:
157
  s = series.copy()
158
  if getattr(s.dt, "tz", None) is not None:
159
  s = s.dt.tz_convert("UTC").dt.tz_localize(None)
160
  return s
161
 
 
162
  def render_line(df, col):
163
  times = _normalize_times(df["time"])
164
  fig, ax = plt.subplots(figsize=(6, 3))
 
170
  fig.tight_layout()
171
  return fig
172
 
 
173
  def render_bar_or_dual(df, second_col, first_col, dual_axis):
174
  times = _normalize_times(df["time"])
175
  x = mdates.date2num(times.dt.to_pydatetime().tolist())
 
191
  fig.tight_layout()
192
  return fig
193
 
 
194
  def render_rolling(df, col, window=5):
195
  times = _normalize_times(df["time"])
196
  roll_col = f"{col}_rolling{window}"
 
205
  fig.tight_layout()
206
  return fig, df
207
 
 
208
  # -----------------------------
209
+ # 新增 Gauge 渲染
210
  # -----------------------------
211
  def degree_range(n):
212
  start = np.linspace(0, 180, n + 1, endpoint=True)[0:-1]
 
214
  mid_points = start + ((end - start) / 2.)
215
  return np.c_[start, end], mid_points
216
 
 
217
  def rot_text(ang):
218
  rotation = np.degrees(np.radians(ang) * np.pi / np.pi - np.radians(90))
219
  return rotation
220
 
 
221
  def render_gauge(df, col):
222
  value = df[col].iloc[-1] if not df.empty else 0
223
  min_val, max_val = df[col].min(), df[col].max()
224
  normalized = (value - min_val) / (max_val - min_val + 1e-9) if max_val > min_val else 0
 
225
  labels = ['LOW', 'MEDIUM', 'HIGH']
226
  N = len(labels)
227
+ colors = ['#007A00', '#FFCC00', '#ED1C24']
228
+ arrow = 1 if normalized < 0.33 else 2 if normalized < 0.66 else 3
 
 
 
 
 
 
 
229
  fig, ax = plt.subplots(figsize=(5, 3.5))
 
230
  ang_range, mid_points = degree_range(N)
 
231
  labels = labels[::-1]
232
+ patches = [Wedge((0., 0.), .4, *ang, facecolor='w', lw=2) for ang in ang_range] + [Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5) for ang, c in zip(ang_range, colors)]
 
 
 
 
 
233
  [ax.add_patch(p) for p in patches]
 
234
  for mid, lab in zip(mid_points, labels):
235
+ ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)), lab, horizontalalignment='center', verticalalignment='center', fontsize=12, fontweight='bold', rotation=rot_text(mid))
236
+ ax.add_patch(Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2))
237
+ ax.text(0, -0.05, f"Latest {col}: {value:.2f}", horizontalalignment='center', verticalalignment='center', fontsize=12, fontweight='bold')
 
 
 
 
 
 
 
238
  pos = mid_points[abs(arrow - N)]
239
+ ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)), width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k')
240
+ ax.add_patch(FancyArrowPatch((0, 0), (0.01 * np.cos(np.radians(pos)), 0.01 * np.sin(np.radians(pos))), mutation_scale=10, fc='k', ec='k'))
 
 
 
 
241
  ax.set_frame_on(False)
242
  ax.axes.set_xticks([])
243
  ax.axes.set_yticks([])
 
245
  plt.tight_layout()
246
  return fig
247
 
 
248
  # -----------------------------
249
+ # Folium helpers
250
  # -----------------------------
251
  def _to_hex_color(value: float, cmap=cm.viridis) -> str:
252
  rgba = cmap(value)
253
  return "#{:02x}{:02x}{:02x}".format(int(rgba[0]*255), int(rgba[1]*255), int(rgba[2]*255))
254
 
255
+ def render_map_folium(df: pd.DataFrame, value_col: str = "amplitude", size_col: str = "count", cmap_name: str = "viridis", tiles: str = "OpenStreetMap", show_heatmap: bool = False) -> str:
 
 
 
 
 
 
 
 
256
  if df.empty:
257
  return "<p>無資料可顯示地圖</p>"
258
  center_lat, center_lon = df["lat"].mean(), df["lon"].mean()
259
  m = folium.Map(location=[center_lat, center_lon], zoom_start=7, tiles=tiles)
 
260
  vmin, vmax = df[value_col].min(), df[value_col].max()
261
  cmap = getattr(cm, cmap_name)
262
+ colormap = bcm.LinearColormap([_to_hex_color(i, cmap) for i in np.linspace(0, 1, 256)], vmin=vmin, vmax=vmax)
 
 
 
 
263
  colormap.caption = f"{value_col} (color scale)"
264
  colormap.add_to(m)
 
265
  if show_heatmap:
 
266
  heat_data = [[row["lat"], row["lon"], row[value_col]] for _, row in df.iterrows()]
267
  plugins.HeatMap(heat_data, radius=15, blur=10).add_to(m)
268
  else:
 
269
  for _, row in df.iterrows():
270
  norm_val = (row[value_col] - vmin) / (vmax - vmin + 1e-9)
271
+ popup_html = f"<b>#ID:</b> {int(row['pid'])}<br><b>time:</b> {pd.to_datetime(row['time']).strftime('%Y-%m-%d %H:%M:%S')}<br><b>{value_col}:</b> {row[value_col]:.4f}<br><b>{size_col}:</b> {row[size_col]}<br><b>lat/lon:</b> {row['lat']:.5f}, {row['lon']:.5f}"
272
+ folium.CircleMarker(location=[row["lat"], row["lon"]], radius=row[size_col] + 3, color="black", weight=1, fill=True, fill_opacity=0.7, fill_color=_to_hex_color(norm_val, cmap), popup=folium.Popup(popup_html, max_width=300)).add_to(m)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  return m._repr_html_()
274
 
 
275
  # -----------------------------
276
  # Detail helpers
277
  # -----------------------------
278
  def make_point_choices(df: pd.DataFrame) -> list[str]:
279
+ return [f"#{int(r['pid'])} | {pd.to_datetime(r['time']).strftime('%H:%M:%S')} | amp={r.get('amplitude', 0):.3f} cnt={int(r.get('count', 0))}" for _, r in df.iterrows()]
 
 
 
 
 
280
 
281
  def pick_detail(df: pd.DataFrame, choice: str) -> pd.DataFrame:
282
  if not choice:
283
  return pd.DataFrame()
284
  try:
285
+ pid = int(choice.split("|")[0].strip().lstrip("#"))
286
+ return df[df["pid"] == pid].reset_index(drop=True)
 
 
287
  except Exception:
288
  return pd.DataFrame()
289
 
 
290
  # -----------------------------
291
  # Main pipeline with dynamic update
292
  # -----------------------------
293
  def pipeline(source, file, sheet_url, series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice, start_time, end_time, show_heatmap, last_time=None):
294
  try:
295
  df, new_last_time = load_data(source, file, sheet_url, last_time)
296
+ df = filter_data(df, start_time, end_time)
297
  numeric_cols = [c for c in df.columns if c not in ["time", "lat", "lon", "pid"] and pd.api.types.is_numeric_dtype(df[c])]
298
+ chosen = [c for c in (series_choice or numeric_cols[:2]) if c in numeric_cols] or numeric_cols[:2] or []
 
 
299
  if not chosen:
300
  raise ValueError("無有效數值欄位可視覺化")
 
301
  dash_json = build_grafanalib_dashboard(chosen, bool(dual_axis), int(rolling_window))
302
  dash_json_str = json.dumps(dash_json, ensure_ascii=False, indent=2, default=str)
303
  with tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w", encoding="utf-8") as f:
304
  f.write(dash_json_str)
305
  json_path = f.name
 
306
  fig1 = render_line(df, chosen[0])
307
  fig2 = render_bar_or_dual(df, chosen[1], chosen[0], bool(dual_axis)) if len(chosen) > 1 else plt.figure()
308
  fig3, df_with_roll = render_rolling(df.copy(), chosen[0], int(rolling_window))
309
  fig4 = render_gauge(df, chosen[0])
310
+ map_html = render_map_folium(df, value_col=chosen[0], size_col=chosen[1] if len(chosen) > 1 else "count", cmap_name=cmap_choice, tiles=tiles_choice, show_heatmap=bool(show_heatmap))
 
 
 
311
  point_choices = [] if show_heatmap else make_point_choices(df)
312
  default_choice = point_choices[0] if point_choices else ""
313
  detail_df = pick_detail(df, default_choice)
314
+ demo_df = make_demo_dataframe()[0]
 
315
  with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", encoding="utf-8") as f:
316
  demo_df.to_csv(f, index=False)
317
  demo_csv_path = f.name
318
+ logger.debug(f"Pipeline executed with new_last_time: {new_last_time}")
319
+ return fig1, fig2, fig3, fig4, map_html, dash_json_str, json_path, df_with_roll, demo_csv_path, gr.Dropdown(choices=point_choices, value=default_choice), detail_df, "", new_last_time
 
 
 
 
 
 
 
 
320
  except Exception as e:
321
+ logger.error(f"Pipeline error: {str(e)}")
322
+ return None, None, None, None, "<p>錯誤:無資料顯示</p>", "", None, pd.DataFrame(), None, gr.Dropdown(choices=[], value=None), pd.DataFrame(), str(e), last_time
 
 
 
 
 
 
 
 
323
 
324
  def regenerate_demo(series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice, current_choice, start_time, end_time, show_heatmap, last_time):
325
  return pipeline("demo", None, "", series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice, start_time, end_time, show_heatmap, last_time)
326
 
 
327
  def update_detail(df: pd.DataFrame, choice: str):
328
  return pick_detail(df, choice)
329
 
 
330
  # -----------------------------
331
+ # UI 優化
332
  # -----------------------------
333
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
334
+ gr.Markdown("## 動態時間序列 - Grafana-like Demo + Folium Map")
 
335
  with gr.Row():
336
  with gr.Column(scale=1):
337
  source_radio = gr.Radio(["upload", "drive", "demo"], label="資料來源", value="demo")
338
+ file_in = gr.File(label="上傳 CSV", file_types=[".csv"])
339
+ preset_dd = gr.Dropdown(label="Google 預設來源", choices=DRIVE_PRESETS, value=DRIVE_PRESETS[0])
 
 
 
 
340
  with gr.Row():
341
+ start_time_in = gr.Textbox(label="開始時間", placeholder="2023-01-01 00:00:00")
342
+ end_time_in = gr.Textbox(label="結束時間", placeholder="2023-12-31 23:59:59")
 
343
  with gr.Column(scale=1):
344
  series_multiselect = gr.CheckboxGroup(label="數值欄位", choices=[])
345
+ dual_axis_chk = gr.Checkbox(label="第二面板雙軸", value=False)
346
  rolling_dd = gr.Dropdown(label="Rolling window", choices=["3", "5", "10", "20"], value="5")
347
+ cmap_dd = gr.Dropdown(label="地圖配色", choices=["viridis", "plasma", "inferno", "magma", "cividis", "coolwarm"], value="viridis")
348
+ tiles_dd = gr.Dropdown(label="地圖底圖", choices=["OpenStreetMap", "Stamen Terrain", "Stamen Toner", "CartoDB positron", "CartoDB dark_matter"], value="OpenStreetMap")
349
+ heatmap_chk = gr.Checkbox(label="顯示熱圖", value=False)
 
 
 
 
 
 
350
  with gr.Row():
351
  run_btn = gr.Button("產生 Dashboard", scale=1)
352
  update_btn = gr.Button("手動更新數據", scale=1)
353
  interval = gr.Slider(5, 60, value=10, step=5, label="自動更新間隔 (秒)")
 
354
  error_msg = gr.Markdown(value="", label="錯誤訊息", visible=True)
 
355
  with gr.Tabs():
356
  with gr.Tab("圖表"):
357
  with gr.Row():
 
364
  plot3 = gr.Plot(label="3:Rolling Mean")
365
  with gr.Column(scale=1):
366
  plot4 = gr.Plot(label="4:Gauge")
 
367
  with gr.Tab("地圖"):
368
+ map_out = gr.HTML(label="5:Geo Map")
 
369
  with gr.Tab("JSON & 檔案"):
370
  json_box = gr.Code(label="grafanalib Dashboard JSON", language="json")
371
  json_file = gr.File(label="下載 dashboard.json")
372
  demo_csv_file = gr.File(label="下載示範資料 demo.csv")
 
373
  with gr.Tab("資料預覽"):
374
+ df_view = gr.Dataframe(label="資料預覽", wrap=True)
 
375
  with gr.Tab("點位詳情"):
376
+ gr.Markdown("### 點位詳情")
377
+ point_selector = gr.Dropdown(label="選擇點位", choices=[], value=None)
378
  detail_view = gr.Dataframe(label="選取點詳細資料", wrap=True)
379
 
 
380
  def probe_columns(source, file, preset_url, start_time, end_time):
381
  sheet_url = preset_url if source == "drive" else ""
382
  try:
 
387
  except Exception as e:
388
  return gr.CheckboxGroup(choices=[]), pd.DataFrame(), str(e)
389
 
390
+ source_radio.change(probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in], [series_multiselect, df_view, error_msg])
391
+ file_in.change(probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in], [series_multiselect, df_view, error_msg])
392
+ preset_dd.change(probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in], [series_multiselect, df_view, error_msg])
393
+ start_time_in.change(probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in], [series_multiselect, df_view, error_msg])
394
+ end_time_in.change(probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in], [series_multiselect, df_view, error_msg])
395
 
 
396
  demo.load(
397
  fn=lambda: pipeline("drive", None, DRIVE_PRESETS[0], [], False, "5", "viridis", "OpenStreetMap", "", "", False),
398
+ outputs=[plot1, plot2, plot3, plot4, map_out, json_box, json_file, df_view, demo_csv_file, point_selector, detail_view, error_msg, gr.State(value=None)]
 
 
 
 
 
 
 
399
  )
400
 
 
401
  run_btn.click(
402
  fn=pipeline,
403
  inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd, cmap_dd, tiles_dd, start_time_in, end_time_in, heatmap_chk, gr.State(value=None)],
404
+ outputs=[plot1, plot2, plot3, plot4, map_out, json_box, json_file, df_view, demo_csv_file, point_selector, detail_view, error_msg, gr.State()]
 
 
 
 
 
 
 
405
  )
406
 
407
  update_btn.click(
408
  fn=pipeline,
409
  inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd, cmap_dd, tiles_dd, start_time_in, end_time_in, heatmap_chk, gr.State()],
410
+ outputs=[plot1, plot2, plot3, plot4, map_out, json_box, json_file, df_view, demo_csv_file, point_selector, detail_view, error_msg, gr.State()]
 
 
 
 
 
 
 
411
  )
412
 
 
413
  def start_auto_update(interval):
414
+ logger.debug(f"Setting auto update interval to {interval} seconds")
415
  return gr.update(value=interval)
416
 
417
  interval.change(
 
430
  }, intervalValue);
431
  }
432
  update();
433
+ document.querySelector('input[type="range"]').addEventListener('input', function() {
434
+ intervalValue = parseInt(this.value) * 1000;
435
+ clearTimeout(window.updateTimeout);
436
+ update();
437
+ });
438
  }
439
  startAutoUpdate();
 
 
 
 
 
440
  """
441
 
442
  point_selector.change(
 
446
  )
447
 
448
  if __name__ == "__main__":
449
+ demo.launch(server_name="0.0.0.0", server_port=7860)