Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,6 @@ import re
|
|
| 4 |
import tempfile
|
| 5 |
from datetime import datetime, timedelta
|
| 6 |
from dateutil import tz
|
| 7 |
-
import time
|
| 8 |
import logging
|
| 9 |
|
| 10 |
import gradio as gr
|
|
@@ -17,11 +16,15 @@ from matplotlib import cm
|
|
| 17 |
import branca.colormap as bcm
|
| 18 |
import folium.plugins as plugins
|
| 19 |
from matplotlib.patches import Wedge, Rectangle, FancyArrowPatch
|
| 20 |
-
from matplotlib.path import Path as mpath
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# 設置日誌
|
| 27 |
logging.basicConfig(level=logging.DEBUG)
|
|
@@ -42,14 +45,19 @@ 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 |
# -----------------------------
|
|
@@ -60,11 +68,13 @@ def make_demo_dataframe(last_time=None) -> tuple[pd.DataFrame, datetime]:
|
|
| 60 |
last_time = datetime.now(tz=TAIPEI) - timedelta(minutes=60)
|
| 61 |
else:
|
| 62 |
last_time = last_time + timedelta(minutes=1) # 模擬每分鐘新增數據
|
|
|
|
| 63 |
times = [last_time + timedelta(minutes=i) for i in range(61)]
|
| 64 |
amp = np.random.rand(len(times))
|
| 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}")
|
|
@@ -74,12 +84,27 @@ 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 其一)")
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
df = df.rename(columns={time_col: "time"})
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return df.sort_values("time").reset_index(drop=True)
|
| 84 |
|
| 85 |
def load_csv(file: gr.File | None) -> pd.DataFrame:
|
|
@@ -97,7 +122,7 @@ def load_drive_csv(sheet_or_file_url: str) -> pd.DataFrame:
|
|
| 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 連結")
|
|
@@ -110,21 +135,47 @@ def load_data(source: str, file: gr.File | None = None, sheet_url: str = "", las
|
|
| 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 |
-
|
|
|
|
|
|
|
| 118 |
if end_time:
|
| 119 |
-
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
]
|
| 129 |
if len(series_columns) > 1:
|
| 130 |
targets = [Target(expr=f"{series_columns[1]}", legendFormat=series_columns[1])]
|
|
@@ -133,12 +184,37 @@ def build_grafanalib_dashboard(series_columns: list[str], dual_axis: bool, rolli
|
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
panels.extend([
|
| 138 |
-
Graph(
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
])
|
| 141 |
-
return Dashboard(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
# -----------------------------
|
| 144 |
# Matplotlib helpers
|
|
@@ -155,8 +231,12 @@ def _style_time_axis(ax):
|
|
| 155 |
|
| 156 |
def _normalize_times(series: pd.Series) -> pd.Series:
|
| 157 |
s = series.copy()
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
return s
|
| 161 |
|
| 162 |
def render_line(df, col):
|
|
@@ -172,11 +252,21 @@ def render_line(df, col):
|
|
| 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())
|
| 176 |
fig, ax = plt.subplots(figsize=(6, 3))
|
| 177 |
-
width
|
| 178 |
-
ax.bar(x, df[second_col], width=width, align="center", label=second_col)
|
| 179 |
title = f"{second_col} (bar)"
|
|
|
|
| 180 |
if dual_axis:
|
| 181 |
ax2 = ax.twinx()
|
| 182 |
ax2.plot(times, df[first_col], linewidth=1.6, label=f"{first_col} (line)")
|
|
@@ -186,6 +276,7 @@ def render_bar_or_dual(df, second_col, first_col, dual_axis):
|
|
| 186 |
ax.legend(h1 + h2, l1 + l2, loc="upper left")
|
| 187 |
else:
|
| 188 |
ax.legend(loc="upper left")
|
|
|
|
| 189 |
ax.set_title(title, fontsize=12, pad=8)
|
| 190 |
_style_time_axis(ax)
|
| 191 |
fig.tight_layout()
|
|
@@ -206,7 +297,7 @@ def render_rolling(df, col, window=5):
|
|
| 206 |
return fig, df
|
| 207 |
|
| 208 |
# -----------------------------
|
| 209 |
-
#
|
| 210 |
# -----------------------------
|
| 211 |
def degree_range(n):
|
| 212 |
start = np.linspace(0, 180, n + 1, endpoint=True)[0:-1]
|
|
@@ -219,28 +310,43 @@ def rot_text(ang):
|
|
| 219 |
return rotation
|
| 220 |
|
| 221 |
def render_gauge(df, col):
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 233 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)),
|
|
|
|
|
|
|
| 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}",
|
|
|
|
| 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)),
|
| 240 |
-
|
|
|
|
|
|
|
| 241 |
ax.set_frame_on(False)
|
| 242 |
-
ax.
|
| 243 |
-
ax.
|
| 244 |
ax.axis('equal')
|
| 245 |
plt.tight_layout()
|
| 246 |
return fig
|
|
@@ -252,31 +358,56 @@ 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",
|
|
|
|
| 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 |
-
|
|
|
|
| 261 |
cmap = getattr(cm, cmap_name)
|
| 262 |
-
colormap = bcm.LinearColormap(
|
|
|
|
|
|
|
| 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 =
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
return m._repr_html_()
|
| 274 |
|
| 275 |
# -----------------------------
|
| 276 |
# Detail helpers
|
| 277 |
# -----------------------------
|
| 278 |
def make_point_choices(df: pd.DataFrame) -> list[str]:
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
def pick_detail(df: pd.DataFrame, choice: str) -> pd.DataFrame:
|
| 282 |
if not choice:
|
|
@@ -290,48 +421,94 @@ def pick_detail(df: pd.DataFrame, choice: str) -> pd.DataFrame:
|
|
| 290 |
# -----------------------------
|
| 291 |
# Main pipeline with dynamic update
|
| 292 |
# -----------------------------
|
| 293 |
-
def pipeline(source, file, sheet_url, series_choice, dual_axis, rolling_window,
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
except Exception as e:
|
| 321 |
logger.error(f"Pipeline error: {str(e)}")
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
|
@@ -340,6 +517,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 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)
|
|
@@ -347,11 +525,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 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,86 +545,140 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 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="資料預覽"
|
|
|
|
| 375 |
with gr.Tab("點位詳情"):
|
| 376 |
gr.Markdown("### 點位詳情")
|
| 377 |
point_selector = gr.Dropdown(label="選擇點位", choices=[], value=None)
|
| 378 |
-
detail_view = gr.Dataframe(label="選取點詳細資料"
|
| 379 |
|
|
|
|
| 380 |
def probe_columns(source, file, preset_url, start_time, end_time):
|
| 381 |
sheet_url = preset_url if source == "drive" else ""
|
| 382 |
try:
|
| 383 |
df, _ = load_data(source, file, sheet_url)
|
| 384 |
df = filter_data(df, start_time, end_time)
|
| 385 |
-
numeric_cols = [c for c in df.columns
|
| 386 |
-
|
|
|
|
| 387 |
except Exception as e:
|
| 388 |
-
return gr.
|
| 389 |
|
| 390 |
-
source_radio.change(
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
|
|
|
|
| 396 |
demo.load(
|
| 397 |
-
fn=lambda: pipeline("drive", None, DRIVE_PRESETS[0], [], False, "5",
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
)
|
| 400 |
|
|
|
|
| 401 |
run_btn.click(
|
| 402 |
fn=pipeline,
|
| 403 |
-
inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd,
|
| 404 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
)
|
| 406 |
|
| 407 |
update_btn.click(
|
| 408 |
fn=pipeline,
|
| 409 |
-
inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd,
|
| 410 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
)
|
| 412 |
|
| 413 |
-
|
| 414 |
-
logger.debug(f"Setting auto update interval to {interval} seconds")
|
| 415 |
-
return gr.update(value=interval)
|
| 416 |
-
|
| 417 |
-
interval.change(
|
| 418 |
-
fn=start_auto_update,
|
| 419 |
-
inputs=[interval],
|
| 420 |
-
outputs=[interval]
|
| 421 |
-
)
|
| 422 |
-
|
| 423 |
-
demo.js = """
|
| 424 |
-
function startAutoUpdate() {
|
| 425 |
-
let intervalValue = parseInt(document.querySelector('input[type="range"]').value) * 1000;
|
| 426 |
-
function update() {
|
| 427 |
-
setTimeout(() => {
|
| 428 |
-
document.querySelector('button[aria-label="手動更新數據"]').click();
|
| 429 |
-
update();
|
| 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(
|
| 443 |
fn=update_detail,
|
| 444 |
inputs=[df_view, point_selector],
|
| 445 |
outputs=[detail_view]
|
| 446 |
)
|
| 447 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
if __name__ == "__main__":
|
| 449 |
-
|
|
|
|
|
|
| 4 |
import tempfile
|
| 5 |
from datetime import datetime, timedelta
|
| 6 |
from dateutil import tz
|
|
|
|
| 7 |
import logging
|
| 8 |
|
| 9 |
import gradio as gr
|
|
|
|
| 16 |
import branca.colormap as bcm
|
| 17 |
import folium.plugins as plugins
|
| 18 |
from matplotlib.patches import Wedge, Rectangle, FancyArrowPatch
|
|
|
|
| 19 |
|
| 20 |
+
# -------- grafanalib(可選;若未安裝則降級) --------
|
| 21 |
+
try:
|
| 22 |
+
from grafanalib.core import (
|
| 23 |
+
Dashboard, Graph, Row, Target, YAxis, YAxes, Time, BarGauge
|
| 24 |
+
)
|
| 25 |
+
GRAFANA_AVAILABLE = True
|
| 26 |
+
except Exception:
|
| 27 |
+
GRAFANA_AVAILABLE = False
|
| 28 |
|
| 29 |
# 設置日誌
|
| 30 |
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
| 45 |
if not isinstance(url, str) or not url.strip():
|
| 46 |
raise ValueError("請提供有效的 Google 連結")
|
| 47 |
url = url.strip()
|
| 48 |
+
|
| 49 |
+
# Google Sheets
|
| 50 |
m = re.search(r"https://docs\.google\.com/spreadsheets/d/([a-zA-Z0-9-_]+)", url)
|
| 51 |
if m:
|
| 52 |
sheet_id = m.group(1)
|
| 53 |
return f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv"
|
| 54 |
+
|
| 55 |
+
# Google Drive File
|
| 56 |
m = re.search(r"https://drive\.google\.com/file/d/([a-zA-Z0-9-_]+)/", url)
|
| 57 |
if m:
|
| 58 |
file_id = m.group(1)
|
| 59 |
return f"https://drive.google.com/uc?export=download&id={file_id}"
|
| 60 |
+
|
| 61 |
return url
|
| 62 |
|
| 63 |
# -----------------------------
|
|
|
|
| 68 |
last_time = datetime.now(tz=TAIPEI) - timedelta(minutes=60)
|
| 69 |
else:
|
| 70 |
last_time = last_time + timedelta(minutes=1) # 模擬每分鐘新增數據
|
| 71 |
+
|
| 72 |
times = [last_time + timedelta(minutes=i) for i in range(61)]
|
| 73 |
amp = np.random.rand(len(times))
|
| 74 |
cnt = np.random.randint(0, 11, size=len(times))
|
| 75 |
lats = np.random.uniform(21.8, 25.3, size=len(times))
|
| 76 |
lons = np.random.uniform(120.0, 122.0, size=len(times))
|
| 77 |
+
|
| 78 |
df = pd.DataFrame({"time": times, "amplitude": amp, "count": cnt, "lat": lats, "lon": lons})
|
| 79 |
df["pid"] = np.arange(len(df))
|
| 80 |
logger.debug(f"Generated new data with last_time: {last_time}")
|
|
|
|
| 84 |
time_col = next((c for c in ["time", "timestamp", "datetime", "date"] if c in df.columns), None)
|
| 85 |
if time_col is None:
|
| 86 |
raise ValueError("資料需包含時間欄位(time/timestamp/datetime/date 其一)")
|
| 87 |
+
|
| 88 |
+
df[time_col] = pd.to_datetime(df[time_col], errors="coerce")
|
| 89 |
+
if df[time_col].isna().all():
|
| 90 |
+
raise ValueError("時間欄位解析失敗,請確認格式")
|
| 91 |
+
|
| 92 |
df = df.rename(columns={time_col: "time"})
|
| 93 |
+
|
| 94 |
+
# 若為 naive → 設定為台北時區;若已有時區 → 轉為台北
|
| 95 |
+
try:
|
| 96 |
+
if df["time"].dt.tz is None:
|
| 97 |
+
df["time"] = df["time"].dt.tz_localize(TAIPEI)
|
| 98 |
+
else:
|
| 99 |
+
df["time"] = df["time"].dt.tz_convert(TAIPEI)
|
| 100 |
+
except Exception:
|
| 101 |
+
# 逐列處理(防止混合型資料)
|
| 102 |
+
def _to_tpe(t):
|
| 103 |
+
if t.tzinfo is None:
|
| 104 |
+
return t.tz_localize(TAIPEI)
|
| 105 |
+
return t.tz_convert(TAIPEI)
|
| 106 |
+
df["time"] = df["time"].apply(_to_tpe)
|
| 107 |
+
|
| 108 |
return df.sort_values("time").reset_index(drop=True)
|
| 109 |
|
| 110 |
def load_csv(file: gr.File | None) -> pd.DataFrame:
|
|
|
|
| 122 |
except Exception as e:
|
| 123 |
raise ValueError(f"Google 連結載入失敗:{str(e)}")
|
| 124 |
|
| 125 |
+
def load_data(source: str, file: gr.File | None = None, sheet_url: str = "", last_time=None) -> tuple[pd.DataFrame, datetime | None]:
|
| 126 |
if source == "drive":
|
| 127 |
if not sheet_url:
|
| 128 |
raise ValueError("請選擇 Google 連結")
|
|
|
|
| 135 |
return make_demo_dataframe(last_time)
|
| 136 |
|
| 137 |
# -----------------------------
|
| 138 |
+
# 資料過濾(時區安全)
|
| 139 |
# -----------------------------
|
| 140 |
+
def _to_taipei(dt_like):
|
| 141 |
+
ts = pd.to_datetime(dt_like, errors="coerce")
|
| 142 |
+
if pd.isna(ts):
|
| 143 |
+
return None
|
| 144 |
+
if ts.tzinfo is None:
|
| 145 |
+
return ts.tz_localize(TAIPEI)
|
| 146 |
+
return ts.tz_convert(TAIPEI)
|
| 147 |
+
|
| 148 |
def filter_data(df: pd.DataFrame, start_time: str, end_time: str) -> pd.DataFrame:
|
| 149 |
if start_time:
|
| 150 |
+
st = _to_taipei(start_time)
|
| 151 |
+
if st is not None:
|
| 152 |
+
df = df[df["time"] >= st]
|
| 153 |
if end_time:
|
| 154 |
+
et = _to_taipei(end_time)
|
| 155 |
+
if et is not None:
|
| 156 |
+
df = df[df["time"] <= et]
|
| 157 |
return df
|
| 158 |
|
| 159 |
# -----------------------------
|
| 160 |
+
# grafanalib JSON builder(可降級)
|
| 161 |
# -----------------------------
|
| 162 |
def build_grafanalib_dashboard(series_columns: list[str], dual_axis: bool, rolling_window: int) -> dict:
|
| 163 |
+
if not GRAFANA_AVAILABLE:
|
| 164 |
+
return {
|
| 165 |
+
"error": "grafanalib 未安裝。如需啟用,請在 requirements.txt 加入:grafanalib",
|
| 166 |
+
"series": series_columns,
|
| 167 |
+
"dual_axis": bool(dual_axis),
|
| 168 |
+
"rolling_window": int(rolling_window),
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
panels = [
|
| 172 |
+
Graph(
|
| 173 |
+
title=f"{series_columns[0]}",
|
| 174 |
+
dataSource="(example)",
|
| 175 |
+
targets=[Target(expr=f"{series_columns[0]}", legendFormat=series_columns[0])],
|
| 176 |
+
lines=True, bars=False, points=False,
|
| 177 |
+
yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short"))
|
| 178 |
+
),
|
| 179 |
]
|
| 180 |
if len(series_columns) > 1:
|
| 181 |
targets = [Target(expr=f"{series_columns[1]}", legendFormat=series_columns[1])]
|
|
|
|
| 184 |
targets.append(Target(expr=f"{series_columns[0]}", legendFormat=f"{series_columns[0]} (line)"))
|
| 185 |
lines, bars = True, True
|
| 186 |
title = f"{series_columns[1]} (bar) + {series_columns[0]} (line)"
|
| 187 |
+
panels.append(
|
| 188 |
+
Graph(
|
| 189 |
+
title=title,
|
| 190 |
+
dataSource="(example)",
|
| 191 |
+
targets=targets,
|
| 192 |
+
lines=lines, bars=bars, points=False,
|
| 193 |
+
yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short"))
|
| 194 |
+
)
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
panels.extend([
|
| 198 |
+
Graph(
|
| 199 |
+
title=f"{series_columns[0]} rolling({rolling_window})",
|
| 200 |
+
dataSource="(example)",
|
| 201 |
+
targets=[Target(expr=f"{series_columns[0]}_rolling{rolling_window}",
|
| 202 |
+
legendFormat=f"{series_columns[0]}_rolling{rolling_window}")],
|
| 203 |
+
lines=True, bars=False, points=False,
|
| 204 |
+
yAxes=YAxes(left=YAxis(format="short"), right=YAxis(format="short"))
|
| 205 |
+
),
|
| 206 |
+
BarGauge(
|
| 207 |
+
title=f"Latest {series_columns[0]}",
|
| 208 |
+
dataSource="(example)",
|
| 209 |
+
targets=[Target(expr=f"last({series_columns[0]})", legendFormat=series_columns[0])]
|
| 210 |
+
),
|
| 211 |
])
|
| 212 |
+
return Dashboard(
|
| 213 |
+
title="Grafana-like Demo (grafanalib + Gradio)",
|
| 214 |
+
rows=[Row(panels=panels)],
|
| 215 |
+
timezone="browser",
|
| 216 |
+
time=Time("now-1h", "now")
|
| 217 |
+
).to_json_data()
|
| 218 |
|
| 219 |
# -----------------------------
|
| 220 |
# Matplotlib helpers
|
|
|
|
| 231 |
|
| 232 |
def _normalize_times(series: pd.Series) -> pd.Series:
|
| 233 |
s = series.copy()
|
| 234 |
+
try:
|
| 235 |
+
if s.dt.tz is not None:
|
| 236 |
+
s = s.dt.tz_convert("UTC").dt.tz_localize(None)
|
| 237 |
+
except Exception:
|
| 238 |
+
# 若混合/特殊情形,轉為 datetime 再去除 tz
|
| 239 |
+
s = pd.to_datetime(s, errors="coerce").dt.tz_convert("UTC").dt.tz_localize(None)
|
| 240 |
return s
|
| 241 |
|
| 242 |
def render_line(df, col):
|
|
|
|
| 252 |
|
| 253 |
def render_bar_or_dual(df, second_col, first_col, dual_axis):
|
| 254 |
times = _normalize_times(df["time"])
|
| 255 |
+
|
| 256 |
+
# 計算推薦的柱寬(用中位時間差;安全 fallback)
|
| 257 |
+
if len(times) >= 2:
|
| 258 |
+
delta_sec = pd.to_timedelta(times.diff(), errors="coerce").dt.total_seconds().median()
|
| 259 |
+
if pd.isna(delta_sec) or delta_sec <= 0:
|
| 260 |
+
delta_sec = 60.0
|
| 261 |
+
else:
|
| 262 |
+
delta_sec = 60.0
|
| 263 |
+
width_days = max(10.0, float(delta_sec) * 0.8) / 86400.0 # Matplotlib 的日期單位 = 天
|
| 264 |
+
|
| 265 |
x = mdates.date2num(times.dt.to_pydatetime().tolist())
|
| 266 |
fig, ax = plt.subplots(figsize=(6, 3))
|
| 267 |
+
ax.bar(x, df[second_col], width=width_days, align="center", label=second_col)
|
|
|
|
| 268 |
title = f"{second_col} (bar)"
|
| 269 |
+
|
| 270 |
if dual_axis:
|
| 271 |
ax2 = ax.twinx()
|
| 272 |
ax2.plot(times, df[first_col], linewidth=1.6, label=f"{first_col} (line)")
|
|
|
|
| 276 |
ax.legend(h1 + h2, l1 + l2, loc="upper left")
|
| 277 |
else:
|
| 278 |
ax.legend(loc="upper left")
|
| 279 |
+
|
| 280 |
ax.set_title(title, fontsize=12, pad=8)
|
| 281 |
_style_time_axis(ax)
|
| 282 |
fig.tight_layout()
|
|
|
|
| 297 |
return fig, df
|
| 298 |
|
| 299 |
# -----------------------------
|
| 300 |
+
# Gauge 渲染
|
| 301 |
# -----------------------------
|
| 302 |
def degree_range(n):
|
| 303 |
start = np.linspace(0, 180, n + 1, endpoint=True)[0:-1]
|
|
|
|
| 310 |
return rotation
|
| 311 |
|
| 312 |
def render_gauge(df, col):
|
| 313 |
+
if df.empty:
|
| 314 |
+
value = 0.0
|
| 315 |
+
min_val, max_val = 0.0, 1.0
|
| 316 |
+
else:
|
| 317 |
+
value = float(df[col].iloc[-1])
|
| 318 |
+
min_val, max_val = float(df[col].min()), float(df[col].max())
|
| 319 |
+
|
| 320 |
+
normalized = (value - min_val) / (max_val - min_val + 1e-9) if max_val > min_val else 0.0
|
| 321 |
labels = ['LOW', 'MEDIUM', 'HIGH']
|
| 322 |
N = len(labels)
|
| 323 |
colors = ['#007A00', '#FFCC00', '#ED1C24']
|
| 324 |
arrow = 1 if normalized < 0.33 else 2 if normalized < 0.66 else 3
|
| 325 |
+
|
| 326 |
fig, ax = plt.subplots(figsize=(5, 3.5))
|
| 327 |
ang_range, mid_points = degree_range(N)
|
| 328 |
labels = labels[::-1]
|
| 329 |
+
|
| 330 |
+
patches = [Wedge((0., 0.), .4, *ang, facecolor='w', lw=2) for ang in ang_range] + \
|
| 331 |
+
[Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5) for ang, c in zip(ang_range, colors)]
|
| 332 |
+
for p in patches:
|
| 333 |
+
ax.add_patch(p)
|
| 334 |
+
|
| 335 |
for mid, lab in zip(mid_points, labels):
|
| 336 |
+
ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)),
|
| 337 |
+
lab, ha='center', va='center', fontsize=12, fontweight='bold', rotation=rot_text(mid))
|
| 338 |
+
|
| 339 |
ax.add_patch(Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2))
|
| 340 |
+
ax.text(0, -0.05, f"Latest {col}: {value:.2f}", ha='center', va='center', fontsize=12, fontweight='bold')
|
| 341 |
+
|
| 342 |
pos = mid_points[abs(arrow - N)]
|
| 343 |
+
ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)),
|
| 344 |
+
width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k')
|
| 345 |
+
ax.add_patch(FancyArrowPatch((0, 0), (0.01 * np.cos(np.radians(pos)), 0.01 * np.sin(np.radians(pos))),
|
| 346 |
+
mutation_scale=10, fc='k', ec='k'))
|
| 347 |
ax.set_frame_on(False)
|
| 348 |
+
ax.set_xticks([])
|
| 349 |
+
ax.set_yticks([])
|
| 350 |
ax.axis('equal')
|
| 351 |
plt.tight_layout()
|
| 352 |
return fig
|
|
|
|
| 358 |
rgba = cmap(value)
|
| 359 |
return "#{:02x}{:02x}{:02x}".format(int(rgba[0]*255), int(rgba[1]*255), int(rgba[2]*255))
|
| 360 |
|
| 361 |
+
def render_map_folium(df: pd.DataFrame, value_col: str = "amplitude", size_col: str = "count",
|
| 362 |
+
cmap_name: str = "viridis", tiles: str = "OpenStreetMap", show_heatmap: bool = False) -> str:
|
| 363 |
if df.empty:
|
| 364 |
return "<p>無資料可顯示地圖</p>"
|
| 365 |
+
|
| 366 |
center_lat, center_lon = df["lat"].mean(), df["lon"].mean()
|
| 367 |
m = folium.Map(location=[center_lat, center_lon], zoom_start=7, tiles=tiles)
|
| 368 |
+
|
| 369 |
+
vmin, vmax = float(df[value_col].min()), float(df[value_col].max())
|
| 370 |
cmap = getattr(cm, cmap_name)
|
| 371 |
+
colormap = bcm.LinearColormap(
|
| 372 |
+
[_to_hex_color(i, cmap) for i in np.linspace(0, 1, 128)], vmin=vmin, vmax=vmax
|
| 373 |
+
)
|
| 374 |
colormap.caption = f"{value_col} (color scale)"
|
| 375 |
colormap.add_to(m)
|
| 376 |
+
|
| 377 |
if show_heatmap:
|
| 378 |
heat_data = [[row["lat"], row["lon"], row[value_col]] for _, row in df.iterrows()]
|
| 379 |
plugins.HeatMap(heat_data, radius=15, blur=10).add_to(m)
|
| 380 |
else:
|
| 381 |
for _, row in df.iterrows():
|
| 382 |
+
norm_val = (row[value_col] - vmin) / (vmax - vmin + 1e-9) if vmax > vmin else 0.0
|
| 383 |
+
popup_html = (
|
| 384 |
+
f"<b>#ID:</b> {int(row['pid'])}"
|
| 385 |
+
f"<br><b>time:</b> {pd.to_datetime(row['time']).strftime('%Y-%m-%d %H:%M:%S')}"
|
| 386 |
+
f"<br><b>{value_col}:</b> {row[value_col]:.4f}"
|
| 387 |
+
f"<br><b>{size_col}:</b> {int(row[size_col]) if size_col in row else ''}"
|
| 388 |
+
f"<br><b>lat/lon:</b> {row['lat']:.5f}, {row['lon']:.5f}"
|
| 389 |
+
)
|
| 390 |
+
folium.CircleMarker(
|
| 391 |
+
location=[row["lat"], row["lon"]],
|
| 392 |
+
radius=(int(row[size_col]) if size_col in row else 3) + 3,
|
| 393 |
+
color="black", weight=1, fill=True, fill_opacity=0.7,
|
| 394 |
+
fill_color=_to_hex_color(norm_val, cmap),
|
| 395 |
+
popup=folium.Popup(popup_html, max_width=300)
|
| 396 |
+
).add_to(m)
|
| 397 |
return m._repr_html_()
|
| 398 |
|
| 399 |
# -----------------------------
|
| 400 |
# Detail helpers
|
| 401 |
# -----------------------------
|
| 402 |
def make_point_choices(df: pd.DataFrame) -> list[str]:
|
| 403 |
+
choices = []
|
| 404 |
+
for _, r in df.iterrows():
|
| 405 |
+
amp = r.get('amplitude', np.nan)
|
| 406 |
+
cnt = r.get('count', np.nan)
|
| 407 |
+
amp_str = f"{amp:.3f}" if pd.notna(amp) else "NA"
|
| 408 |
+
cnt_str = f"{int(cnt)}" if pd.notna(cnt) else "NA"
|
| 409 |
+
choices.append(f"#{int(r['pid'])} | {pd.to_datetime(r['time']).strftime('%H:%M:%S')} | amp={amp_str} cnt={cnt_str}")
|
| 410 |
+
return choices
|
| 411 |
|
| 412 |
def pick_detail(df: pd.DataFrame, choice: str) -> pd.DataFrame:
|
| 413 |
if not choice:
|
|
|
|
| 421 |
# -----------------------------
|
| 422 |
# Main pipeline with dynamic update
|
| 423 |
# -----------------------------
|
| 424 |
+
def pipeline(source, file, sheet_url, series_choice, dual_axis, rolling_window,
|
| 425 |
+
cmap_choice, tiles_choice, start_time, end_time, show_heatmap, last_time=None):
|
| 426 |
+
|
| 427 |
try:
|
| 428 |
df, new_last_time = load_data(source, file, sheet_url, last_time)
|
| 429 |
df = filter_data(df, start_time, end_time)
|
| 430 |
+
|
| 431 |
+
# 數值欄位辨識
|
| 432 |
+
numeric_cols = [c for c in df.columns
|
| 433 |
+
if c not in ["time", "lat", "lon", "pid"] and pd.api.types.is_numeric_dtype(df[c])]
|
| 434 |
+
|
| 435 |
chosen = [c for c in (series_choice or numeric_cols[:2]) if c in numeric_cols] or numeric_cols[:2] or []
|
| 436 |
if not chosen:
|
| 437 |
raise ValueError("無有效數值欄位可視覺化")
|
| 438 |
+
|
| 439 |
+
# grafanalib JSON
|
| 440 |
dash_json = build_grafanalib_dashboard(chosen, bool(dual_axis), int(rolling_window))
|
| 441 |
dash_json_str = json.dumps(dash_json, ensure_ascii=False, indent=2, default=str)
|
| 442 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w", encoding="utf-8") as f:
|
| 443 |
f.write(dash_json_str)
|
| 444 |
json_path = f.name
|
| 445 |
+
|
| 446 |
+
# 視覺化
|
| 447 |
fig1 = render_line(df, chosen[0])
|
| 448 |
fig2 = render_bar_or_dual(df, chosen[1], chosen[0], bool(dual_axis)) if len(chosen) > 1 else plt.figure()
|
| 449 |
fig3, df_with_roll = render_rolling(df.copy(), chosen[0], int(rolling_window))
|
| 450 |
fig4 = render_gauge(df, chosen[0])
|
| 451 |
+
|
| 452 |
+
# 地圖
|
| 453 |
+
size_col = chosen[1] if len(chosen) > 1 else ("count" if "count" in df.columns else chosen[0])
|
| 454 |
+
map_html = render_map_folium(df, value_col=chosen[0], size_col=size_col,
|
| 455 |
+
cmap_name=cmap_choice, tiles=tiles_choice, show_heatmap=bool(show_heatmap))
|
| 456 |
+
|
| 457 |
+
# 點位詳情
|
| 458 |
point_choices = [] if show_heatmap else make_point_choices(df)
|
| 459 |
+
default_choice = point_choices[0] if point_choices else None
|
| 460 |
+
detail_df = pick_detail(df, default_choice) if default_choice else pd.DataFrame()
|
| 461 |
+
|
| 462 |
+
# 產一份 demo csv 供下載
|
| 463 |
demo_df = make_demo_dataframe()[0]
|
| 464 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", encoding="utf-8") as f:
|
| 465 |
demo_df.to_csv(f, index=False)
|
| 466 |
demo_csv_path = f.name
|
| 467 |
+
|
| 468 |
logger.debug(f"Pipeline executed with new_last_time: {new_last_time}")
|
| 469 |
+
|
| 470 |
+
return (
|
| 471 |
+
fig1, fig2, fig3, fig4, # 4 plots
|
| 472 |
+
map_html, # map (HTML)
|
| 473 |
+
dash_json_str, json_path, # JSON string & file
|
| 474 |
+
df_with_roll, demo_csv_path, # dataframe & demo csv
|
| 475 |
+
gr.update(choices=point_choices, value=default_choice), # point selector
|
| 476 |
+
detail_df, # detail view
|
| 477 |
+
"", # error message
|
| 478 |
+
new_last_time # state
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
except Exception as e:
|
| 482 |
logger.error(f"Pipeline error: {str(e)}")
|
| 483 |
+
# 發生錯誤時回傳空/預設
|
| 484 |
+
return (
|
| 485 |
+
None, None, None, None,
|
| 486 |
+
"<p>錯誤:無資料顯示</p>",
|
| 487 |
+
"", None,
|
| 488 |
+
pd.DataFrame(), None,
|
| 489 |
+
gr.update(choices=[], value=None),
|
| 490 |
+
pd.DataFrame(),
|
| 491 |
+
str(e),
|
| 492 |
+
last_time
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
def regenerate_demo(series_choice, dual_axis, rolling_window, cmap_choice, tiles_choice,
|
| 496 |
+
current_choice, start_time, end_time, show_heatmap, last_time):
|
| 497 |
+
return pipeline("demo", None, "", series_choice, dual_axis, rolling_window,
|
| 498 |
+
cmap_choice, tiles_choice, start_time, end_time, show_heatmap, last_time)
|
| 499 |
|
| 500 |
def update_detail(df: pd.DataFrame, choice: str):
|
| 501 |
return pick_detail(df, choice)
|
| 502 |
|
| 503 |
# -----------------------------
|
| 504 |
+
# UI
|
| 505 |
# -----------------------------
|
| 506 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 507 |
gr.Markdown("## 動態時間序列 - Grafana-like Demo + Folium Map")
|
| 508 |
+
|
| 509 |
+
# Persistent state for streaming demo time
|
| 510 |
+
last_time_state = gr.State(value=None)
|
| 511 |
+
|
| 512 |
with gr.Row():
|
| 513 |
with gr.Column(scale=1):
|
| 514 |
source_radio = gr.Radio(["upload", "drive", "demo"], label="資料來源", value="demo")
|
|
|
|
| 517 |
with gr.Row():
|
| 518 |
start_time_in = gr.Textbox(label="開始時間", placeholder="2023-01-01 00:00:00")
|
| 519 |
end_time_in = gr.Textbox(label="結束時間", placeholder="2023-12-31 23:59:59")
|
| 520 |
+
|
| 521 |
with gr.Column(scale=1):
|
| 522 |
series_multiselect = gr.CheckboxGroup(label="數值欄位", choices=[])
|
| 523 |
dual_axis_chk = gr.Checkbox(label="第二面板雙軸", value=False)
|
|
|
|
| 525 |
cmap_dd = gr.Dropdown(label="地圖配色", choices=["viridis", "plasma", "inferno", "magma", "cividis", "coolwarm"], value="viridis")
|
| 526 |
tiles_dd = gr.Dropdown(label="地圖底圖", choices=["OpenStreetMap", "Stamen Terrain", "Stamen Toner", "CartoDB positron", "CartoDB dark_matter"], value="OpenStreetMap")
|
| 527 |
heatmap_chk = gr.Checkbox(label="顯示熱圖", value=False)
|
| 528 |
+
|
| 529 |
with gr.Row():
|
| 530 |
run_btn = gr.Button("產生 Dashboard", scale=1)
|
| 531 |
+
update_btn = gr.Button("手動更新數據", scale=1, elem_id="update_btn")
|
| 532 |
+
interval = gr.Slider(5, 60, value=10, step=5, label="自動更新間隔 (秒)", elem_id="interval_slider")
|
| 533 |
+
|
| 534 |
error_msg = gr.Markdown(value="", label="錯誤訊息", visible=True)
|
| 535 |
+
|
| 536 |
with gr.Tabs():
|
| 537 |
with gr.Tab("圖表"):
|
| 538 |
with gr.Row():
|
|
|
|
| 545 |
plot3 = gr.Plot(label="3:Rolling Mean")
|
| 546 |
with gr.Column(scale=1):
|
| 547 |
plot4 = gr.Plot(label="4:Gauge")
|
| 548 |
+
|
| 549 |
with gr.Tab("地圖"):
|
| 550 |
map_out = gr.HTML(label="5:Geo Map")
|
| 551 |
+
|
| 552 |
with gr.Tab("JSON & 檔案"):
|
| 553 |
json_box = gr.Code(label="grafanalib Dashboard JSON", language="json")
|
| 554 |
json_file = gr.File(label="下載 dashboard.json")
|
| 555 |
demo_csv_file = gr.File(label="下載示範資料 demo.csv")
|
| 556 |
+
|
| 557 |
with gr.Tab("資料預覽"):
|
| 558 |
+
df_view = gr.Dataframe(label="資料預覽")
|
| 559 |
+
|
| 560 |
with gr.Tab("點位詳情"):
|
| 561 |
gr.Markdown("### 點位詳情")
|
| 562 |
point_selector = gr.Dropdown(label="選擇點位", choices=[], value=None)
|
| 563 |
+
detail_view = gr.Dataframe(label="選取點詳細資料")
|
| 564 |
|
| 565 |
+
# 探測欄位(不回傳新元件,而是更新其 choices/value)
|
| 566 |
def probe_columns(source, file, preset_url, start_time, end_time):
|
| 567 |
sheet_url = preset_url if source == "drive" else ""
|
| 568 |
try:
|
| 569 |
df, _ = load_data(source, file, sheet_url)
|
| 570 |
df = filter_data(df, start_time, end_time)
|
| 571 |
+
numeric_cols = [c for c in df.columns
|
| 572 |
+
if c not in ["time", "lat", "lon", "pid"] and pd.api.types.is_numeric_dtype(df[c])]
|
| 573 |
+
return gr.update(choices=numeric_cols, value=numeric_cols[:2]), df, ""
|
| 574 |
except Exception as e:
|
| 575 |
+
return gr.update(choices=[], value=[]), pd.DataFrame(), str(e)
|
| 576 |
|
| 577 |
+
source_radio.change(
|
| 578 |
+
probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in],
|
| 579 |
+
[series_multiselect, df_view, error_msg]
|
| 580 |
+
)
|
| 581 |
+
file_in.change(
|
| 582 |
+
probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in],
|
| 583 |
+
[series_multiselect, df_view, error_msg]
|
| 584 |
+
)
|
| 585 |
+
preset_dd.change(
|
| 586 |
+
probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in],
|
| 587 |
+
[series_multiselect, df_view, error_msg]
|
| 588 |
+
)
|
| 589 |
+
start_time_in.change(
|
| 590 |
+
probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in],
|
| 591 |
+
[series_multiselect, df_view, error_msg]
|
| 592 |
+
)
|
| 593 |
+
end_time_in.change(
|
| 594 |
+
probe_columns, [source_radio, file_in, preset_dd, start_time_in, end_time_in],
|
| 595 |
+
[series_multiselect, df_view, error_msg]
|
| 596 |
+
)
|
| 597 |
|
| 598 |
+
# 初次載入:用 drive 範例
|
| 599 |
demo.load(
|
| 600 |
+
fn=lambda: pipeline("drive", None, DRIVE_PRESETS[0], [], False, "5",
|
| 601 |
+
"viridis", "OpenStreetMap", "", "", False, None),
|
| 602 |
+
outputs=[
|
| 603 |
+
plot1, plot2, plot3, plot4,
|
| 604 |
+
map_out,
|
| 605 |
+
json_box, json_file,
|
| 606 |
+
df_view, demo_csv_file,
|
| 607 |
+
point_selector, detail_view,
|
| 608 |
+
error_msg,
|
| 609 |
+
last_time_state
|
| 610 |
+
]
|
| 611 |
)
|
| 612 |
|
| 613 |
+
# 執行 / 更新(使用同一個 last_time_state)
|
| 614 |
run_btn.click(
|
| 615 |
fn=pipeline,
|
| 616 |
+
inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd,
|
| 617 |
+
cmap_dd, tiles_dd, start_time_in, end_time_in, heatmap_chk, last_time_state],
|
| 618 |
+
outputs=[plot1, plot2, plot3, plot4,
|
| 619 |
+
map_out, json_box, json_file,
|
| 620 |
+
df_view, demo_csv_file,
|
| 621 |
+
point_selector, detail_view,
|
| 622 |
+
error_msg,
|
| 623 |
+
last_time_state]
|
| 624 |
)
|
| 625 |
|
| 626 |
update_btn.click(
|
| 627 |
fn=pipeline,
|
| 628 |
+
inputs=[source_radio, file_in, preset_dd, series_multiselect, dual_axis_chk, rolling_dd,
|
| 629 |
+
cmap_dd, tiles_dd, start_time_in, end_time_in, heatmap_chk, last_time_state],
|
| 630 |
+
outputs=[plot1, plot2, plot3, plot4,
|
| 631 |
+
map_out, json_box, json_file,
|
| 632 |
+
df_view, demo_csv_file,
|
| 633 |
+
point_selector, detail_view,
|
| 634 |
+
error_msg,
|
| 635 |
+
last_time_state]
|
| 636 |
)
|
| 637 |
|
| 638 |
+
# 點位詳情
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
point_selector.change(
|
| 640 |
fn=update_detail,
|
| 641 |
inputs=[df_view, point_selector],
|
| 642 |
outputs=[detail_view]
|
| 643 |
)
|
| 644 |
|
| 645 |
+
# 自動更新(JS 以 elem_id 鎖定,避免 aria-label 變動)
|
| 646 |
+
gr.HTML("""
|
| 647 |
+
<script>
|
| 648 |
+
(function () {
|
| 649 |
+
function getSliderEl() {
|
| 650 |
+
const container = document.getElementById("interval_slider");
|
| 651 |
+
if (!container) return null;
|
| 652 |
+
return container.querySelector('input[type="range"]');
|
| 653 |
+
}
|
| 654 |
+
function getUpdateBtn() {
|
| 655 |
+
const container = document.getElementById("update_btn");
|
| 656 |
+
if (!container) return null;
|
| 657 |
+
// Gradio v4 內 Button 外層會包一層 div
|
| 658 |
+
return container.querySelector("button") || container;
|
| 659 |
+
}
|
| 660 |
+
let timer = null;
|
| 661 |
+
function schedule() {
|
| 662 |
+
const slider = getSliderEl();
|
| 663 |
+
const btn = getUpdateBtn();
|
| 664 |
+
if (!slider || !btn) {
|
| 665 |
+
setTimeout(schedule, 1000);
|
| 666 |
+
return;
|
| 667 |
+
}
|
| 668 |
+
const ms = parseInt(slider.value) * 1000;
|
| 669 |
+
if (timer) clearInterval(timer);
|
| 670 |
+
timer = setInterval(() => { btn.click(); }, ms);
|
| 671 |
+
slider.addEventListener("input", () => {
|
| 672 |
+
if (timer) clearInterval(timer);
|
| 673 |
+
const ms2 = parseInt(slider.value) * 1000;
|
| 674 |
+
timer = setInterval(() => { btn.click(); }, ms2);
|
| 675 |
+
});
|
| 676 |
+
}
|
| 677 |
+
schedule();
|
| 678 |
+
})();
|
| 679 |
+
</script>
|
| 680 |
+
""")
|
| 681 |
+
|
| 682 |
if __name__ == "__main__":
|
| 683 |
+
# 在 Hugging Face Spaces 上可省略 server_name/server_port,平台會自動注入
|
| 684 |
+
demo.launch()
|