YeCanming commited on
Commit
d70d84b
·
1 Parent(s): f2c0e49

feat: format

Browse files
.streamlit/config.toml CHANGED
@@ -1,17 +1,17 @@
1
  [theme]
2
- base = "light"
3
  baseFontSize = 15
4
- primaryColor = "#FF5F7E"
5
- backgroundColor = "#F9FAFB"
6
- secondaryBackgroundColor = "#F0F4F8"
7
- textColor = "#1F2937"
8
- linkColor = "#2563EB"
9
- borderColor = "#D1D5DB"
10
  showWidgetBorder = false
11
  baseRadius = "0.3rem"
12
- font = "Poppins"
13
 
14
  [theme.sidebar]
15
- backgroundColor = "#FFFFFF"
16
- secondaryBackgroundColor = "#F3F4F6"
17
- borderColor = "#D1D5DB"
 
1
  [theme]
2
+ base = "dark"
3
  baseFontSize = 15
4
+ primaryColor = "#6EA8FE"
5
+ backgroundColor = "#0D1117"
6
+ secondaryBackgroundColor = "#1A1F2B"
7
+ textColor = "#D1D5DB"
8
+ linkColor = "#B8C0FF"
9
+ borderColor = "#2E3440"
10
  showWidgetBorder = false
11
  baseRadius = "0.3rem"
12
+ font = "JetBrains Mono"
13
 
14
  [theme.sidebar]
15
+ backgroundColor = "#0A0A0A"
16
+ secondaryBackgroundColor = "#1A1A1A"
17
+ borderColor = "#2E3440"
.streamlit/theme.toml CHANGED
@@ -1,2 +1,2 @@
1
- theme_name = "花明 (Flowers Bright) 🌸"
2
- theme_poem = "🌸「浅色但不苍白,明亮而不过曝,柔和中有力量」"
 
1
+ theme_name = "柳暗 (Willows Dark) 🌒"
2
+ theme_poem = "🌒「深而不死黑,蓝而不夺目,静而不沉闷」柳影婆娑之下,代码悄然生长。"
src/data_loader.py CHANGED
@@ -4,19 +4,21 @@ from typing import Dict, List, Any
4
  import pandas as pd
5
  import tomli
6
  import streamlit as st
7
- from functools import lru_cache # For non-Streamlit specific caching if needed
8
 
9
  # Assuming utils.py is in the same directory
10
- from utils import DATA_ROOT_PATH # Used for ensuring directory exists
11
 
12
  # --- Cache Clearing Functions ---
13
  # These are more specific cache clearing functions that can be called by model methods.
14
 
 
15
  def clear_study_cache():
16
  """Clears all study discovery cache."""
17
  discover_studies_cached.clear()
18
  st.toast("所有 Study 发现缓存已清除。")
19
 
 
20
  def clear_trial_cache():
21
  """Clears all trial-related data loading caches."""
22
  # This is a bit broad. Ideally, clear caches for specific trials/studies.
@@ -25,8 +27,9 @@ def clear_trial_cache():
25
  discover_trials_from_path.clear()
26
  st.toast("所有 Trial 数据加载缓存已清除。")
27
 
 
28
  def clear_specific_trial_metric_cache(trial_path: Path):
29
- load_all_metrics_for_trial_path.clear() # This clears the whole cache for this func
30
  # For more granular control with @st.cache_data, you'd typically rely on Streamlit's
31
  # automatic cache invalidation based on input args, or rerun.
32
  # If using lru_cache, you could do: load_all_metrics_for_trial_path.cache_clear()
@@ -39,6 +42,7 @@ def clear_specific_trial_input_vars_cache(trial_path: Path):
39
  load_input_variables_from_path.clear()
40
  st.toast(f"Trial '{trial_path.name}' 的参数缓存已清除 (函数级别)。")
41
 
 
42
  def clear_specific_study_trial_discovery_cache(study_path: Path):
43
  discover_trials_from_path.clear()
44
  st.toast(f"Study '{study_path.name}' 的 Trial 发现缓存已清除 (函数级别)。")
@@ -46,6 +50,7 @@ def clear_specific_study_trial_discovery_cache(study_path: Path):
46
 
47
  # --- Data Discovery and Loading Functions (Cached) ---
48
 
 
49
  def ensure_data_directory_exists(data_path: Path = DATA_ROOT_PATH):
50
  """Ensures the root data directory exists."""
51
  if not data_path.exists():
@@ -60,8 +65,12 @@ def ensure_data_directory_exists(data_path: Path = DATA_ROOT_PATH):
60
  st.stop()
61
 
62
 
63
- @st.cache_data(ttl=3600) # Cache for 1 hour, or adjust as needed
64
- def discover_studies_cached(_data_root: Path) -> Dict[str, Any]: # Return type hint as Any to avoid circular dep with data_models.Study
 
 
 
 
65
  """
66
  Scans the data_root for study directories and returns a dictionary
67
  mapping study names to Study objects (or just their paths initially).
@@ -71,7 +80,9 @@ def discover_studies_cached(_data_root: Path) -> Dict[str, Any]: # Return type h
71
  # this function can return simpler structures like Dict[str, Path]
72
  # and the main app or model can instantiate Study objects.
73
  # For this iteration, we'll import Study here for convenience, assuming careful structure.
74
- from data_models import Study # Local import to help with potential circularity if models grow complex
 
 
75
 
76
  if not _data_root.is_dir():
77
  return {}
@@ -128,7 +139,7 @@ def _load_single_metric_toml(_toml_file_path: Path) -> pd.DataFrame:
128
  return pd.DataFrame()
129
 
130
 
131
- @st.cache_data(ttl=300) # Cache metric data for 5 minutes
132
  def load_all_metrics_for_trial_path(_trial_path: Path) -> Dict[str, pd.DataFrame]:
133
  """
134
  Loads all metrics from all tracks in a trial.
@@ -150,19 +161,23 @@ def load_all_metrics_for_trial_path(_trial_path: Path) -> Dict[str, pd.DataFrame
150
 
151
  id_vars = ["global_step"]
152
  value_vars = [col for col in df_track.columns if col not in id_vars]
153
-
154
  if not value_vars:
155
  continue
156
-
157
  # Process each metric column individually to build up the combined DataFrame
158
  for metric_col_name in value_vars:
159
  try:
160
  # Create a DataFrame for the current metric and track
161
  current_metric_df = df_track[["global_step", metric_col_name]].copy()
162
- current_metric_df.rename(columns={metric_col_name: "value"}, inplace=True)
 
 
163
  current_metric_df["track"] = track_name
164
- current_metric_df['value'] = pd.to_numeric(current_metric_df['value'], errors='coerce')
165
- current_metric_df.dropna(subset=['value'], inplace=True)
 
 
166
 
167
  if current_metric_df.empty:
168
  continue
@@ -173,16 +188,20 @@ def load_all_metrics_for_trial_path(_trial_path: Path) -> Dict[str, pd.DataFrame
173
  else:
174
  all_metrics_data_combined[metric_col_name] = pd.concat(
175
  [all_metrics_data_combined[metric_col_name], current_metric_df],
176
- ignore_index=True
177
  )
178
  except Exception as e:
179
- print(f"Error processing metric '{metric_col_name}' from file '{toml_file.name}': {e}")
 
 
180
  continue
181
-
182
  # Sort data by global_step for proper line plotting
183
  for metric_name in all_metrics_data_combined:
184
- all_metrics_data_combined[metric_name] = all_metrics_data_combined[metric_name].sort_values(
185
- by=["track", "global_step"]
186
- ).reset_index(drop=True)
 
 
187
 
188
- return all_metrics_data_combined
 
4
  import pandas as pd
5
  import tomli
6
  import streamlit as st
7
+ from functools import lru_cache # For non-Streamlit specific caching if needed
8
 
9
  # Assuming utils.py is in the same directory
10
+ from utils import DATA_ROOT_PATH # Used for ensuring directory exists
11
 
12
  # --- Cache Clearing Functions ---
13
  # These are more specific cache clearing functions that can be called by model methods.
14
 
15
+
16
  def clear_study_cache():
17
  """Clears all study discovery cache."""
18
  discover_studies_cached.clear()
19
  st.toast("所有 Study 发现缓存已清除。")
20
 
21
+
22
  def clear_trial_cache():
23
  """Clears all trial-related data loading caches."""
24
  # This is a bit broad. Ideally, clear caches for specific trials/studies.
 
27
  discover_trials_from_path.clear()
28
  st.toast("所有 Trial 数据加载缓存已清除。")
29
 
30
+
31
  def clear_specific_trial_metric_cache(trial_path: Path):
32
+ load_all_metrics_for_trial_path.clear() # This clears the whole cache for this func
33
  # For more granular control with @st.cache_data, you'd typically rely on Streamlit's
34
  # automatic cache invalidation based on input args, or rerun.
35
  # If using lru_cache, you could do: load_all_metrics_for_trial_path.cache_clear()
 
42
  load_input_variables_from_path.clear()
43
  st.toast(f"Trial '{trial_path.name}' 的参数缓存已清除 (函数级别)。")
44
 
45
+
46
  def clear_specific_study_trial_discovery_cache(study_path: Path):
47
  discover_trials_from_path.clear()
48
  st.toast(f"Study '{study_path.name}' 的 Trial 发现缓存已清除 (函数级别)。")
 
50
 
51
  # --- Data Discovery and Loading Functions (Cached) ---
52
 
53
+
54
  def ensure_data_directory_exists(data_path: Path = DATA_ROOT_PATH):
55
  """Ensures the root data directory exists."""
56
  if not data_path.exists():
 
65
  st.stop()
66
 
67
 
68
+ @st.cache_data(ttl=3600) # Cache for 1 hour, or adjust as needed
69
+ def discover_studies_cached(
70
+ _data_root: Path,
71
+ ) -> Dict[
72
+ str, Any
73
+ ]: # Return type hint as Any to avoid circular dep with data_models.Study
74
  """
75
  Scans the data_root for study directories and returns a dictionary
76
  mapping study names to Study objects (or just their paths initially).
 
80
  # this function can return simpler structures like Dict[str, Path]
81
  # and the main app or model can instantiate Study objects.
82
  # For this iteration, we'll import Study here for convenience, assuming careful structure.
83
+ from data_models import (
84
+ Study,
85
+ ) # Local import to help with potential circularity if models grow complex
86
 
87
  if not _data_root.is_dir():
88
  return {}
 
139
  return pd.DataFrame()
140
 
141
 
142
+ @st.cache_data(ttl=300) # Cache metric data for 5 minutes
143
  def load_all_metrics_for_trial_path(_trial_path: Path) -> Dict[str, pd.DataFrame]:
144
  """
145
  Loads all metrics from all tracks in a trial.
 
161
 
162
  id_vars = ["global_step"]
163
  value_vars = [col for col in df_track.columns if col not in id_vars]
164
+
165
  if not value_vars:
166
  continue
167
+
168
  # Process each metric column individually to build up the combined DataFrame
169
  for metric_col_name in value_vars:
170
  try:
171
  # Create a DataFrame for the current metric and track
172
  current_metric_df = df_track[["global_step", metric_col_name]].copy()
173
+ current_metric_df.rename(
174
+ columns={metric_col_name: "value"}, inplace=True
175
+ )
176
  current_metric_df["track"] = track_name
177
+ current_metric_df["value"] = pd.to_numeric(
178
+ current_metric_df["value"], errors="coerce"
179
+ )
180
+ current_metric_df.dropna(subset=["value"], inplace=True)
181
 
182
  if current_metric_df.empty:
183
  continue
 
188
  else:
189
  all_metrics_data_combined[metric_col_name] = pd.concat(
190
  [all_metrics_data_combined[metric_col_name], current_metric_df],
191
+ ignore_index=True,
192
  )
193
  except Exception as e:
194
+ print(
195
+ f"Error processing metric '{metric_col_name}' from file '{toml_file.name}': {e}"
196
+ )
197
  continue
198
+
199
  # Sort data by global_step for proper line plotting
200
  for metric_name in all_metrics_data_combined:
201
+ all_metrics_data_combined[metric_name] = (
202
+ all_metrics_data_combined[metric_name]
203
+ .sort_values(by=["track", "global_step"])
204
+ .reset_index(drop=True)
205
+ )
206
 
207
+ return all_metrics_data_combined
src/data_models.py CHANGED
@@ -3,7 +3,7 @@ from dataclasses import dataclass, field
3
  from pathlib import Path
4
  from typing import Dict, List, Optional, Any
5
  import pandas as pd
6
- import streamlit as st # For caching
7
 
8
  # Import from data_loader, assuming it's in the same directory
9
  # We'll define these functions in data_loader.py
@@ -22,7 +22,7 @@ from data_loader import (
22
  clear_study_cache as clear_study_loader_cache,
23
  clear_specific_trial_metric_cache,
24
  clear_specific_trial_input_vars_cache,
25
- clear_specific_study_trial_discovery_cache
26
  )
27
 
28
 
@@ -30,9 +30,11 @@ from data_loader import (
30
  class Trial:
31
  name: str
32
  path: Path
33
- study_name: str # To know its parent study
34
  input_variables: Dict[str, Any] = field(default_factory=dict, repr=False)
35
- metrics_data: Dict[str, pd.DataFrame] = field(default_factory=dict, repr=False) # Key: metric_name, Value: DataFrame with global_step, value, track
 
 
36
 
37
  def __post_init__(self):
38
  # Automatically load data if needed, but prefer explicit calls from UI for clarity
@@ -43,13 +45,13 @@ class Trial:
43
 
44
  def load_input_variables_cached(self):
45
  """Loads or retrieves cached input variables."""
46
- if not self.input_variables: # Load only if not already populated
47
  self.input_variables = load_input_variables_from_path(self.path)
48
  return self.input_variables
49
 
50
  def load_metrics_cached(self):
51
  """Loads or retrieves cached metrics data."""
52
- if not self.metrics_data: # Load only if not already populated
53
  self.metrics_data = load_all_metrics_for_trial_path(self.path)
54
  return self.metrics_data
55
 
@@ -76,10 +78,14 @@ class Study:
76
 
77
  def discover_trials_cached(self):
78
  """Discovers or retrieves cached trials for this study."""
79
- if not self.trials: # Discover only if not already populated
80
- trial_paths = discover_trials_from_path(self.path) # This loader function should be cached
 
 
81
  for trial_name, trial_path in trial_paths.items():
82
- self.trials[trial_name] = Trial(name=trial_name, path=trial_path, study_name=self.name)
 
 
83
  return self.trials
84
 
85
  def get_trial(self, trial_name: str) -> Optional[Trial]:
@@ -89,6 +95,6 @@ class Study:
89
  """Clears cached data for this study and its trials."""
90
  clear_specific_study_trial_discovery_cache(self.path)
91
  for trial in self.trials.values():
92
- trial.clear_cache() # Clear cache for each trial within the study
93
- self.trials = {} # Reset trials dictionary
94
- st.success(f"Study '{self.name}' 及其 Trials 的缓存已清除。")
 
3
  from pathlib import Path
4
  from typing import Dict, List, Optional, Any
5
  import pandas as pd
6
+ import streamlit as st # For caching
7
 
8
  # Import from data_loader, assuming it's in the same directory
9
  # We'll define these functions in data_loader.py
 
22
  clear_study_cache as clear_study_loader_cache,
23
  clear_specific_trial_metric_cache,
24
  clear_specific_trial_input_vars_cache,
25
+ clear_specific_study_trial_discovery_cache,
26
  )
27
 
28
 
 
30
  class Trial:
31
  name: str
32
  path: Path
33
+ study_name: str # To know its parent study
34
  input_variables: Dict[str, Any] = field(default_factory=dict, repr=False)
35
+ metrics_data: Dict[str, pd.DataFrame] = field(
36
+ default_factory=dict, repr=False
37
+ ) # Key: metric_name, Value: DataFrame with global_step, value, track
38
 
39
  def __post_init__(self):
40
  # Automatically load data if needed, but prefer explicit calls from UI for clarity
 
45
 
46
  def load_input_variables_cached(self):
47
  """Loads or retrieves cached input variables."""
48
+ if not self.input_variables: # Load only if not already populated
49
  self.input_variables = load_input_variables_from_path(self.path)
50
  return self.input_variables
51
 
52
  def load_metrics_cached(self):
53
  """Loads or retrieves cached metrics data."""
54
+ if not self.metrics_data: # Load only if not already populated
55
  self.metrics_data = load_all_metrics_for_trial_path(self.path)
56
  return self.metrics_data
57
 
 
78
 
79
  def discover_trials_cached(self):
80
  """Discovers or retrieves cached trials for this study."""
81
+ if not self.trials: # Discover only if not already populated
82
+ trial_paths = discover_trials_from_path(
83
+ self.path
84
+ ) # This loader function should be cached
85
  for trial_name, trial_path in trial_paths.items():
86
+ self.trials[trial_name] = Trial(
87
+ name=trial_name, path=trial_path, study_name=self.name
88
+ )
89
  return self.trials
90
 
91
  def get_trial(self, trial_name: str) -> Optional[Trial]:
 
95
  """Clears cached data for this study and its trials."""
96
  clear_specific_study_trial_discovery_cache(self.path)
97
  for trial in self.trials.values():
98
+ trial.clear_cache() # Clear cache for each trial within the study
99
+ self.trials = {} # Reset trials dictionary
100
+ st.success(f"Study '{self.name}' 及其 Trials 的缓存已清除。")
src/streamlit_app.py CHANGED
@@ -1,6 +1,12 @@
1
  import streamlit as st
 
2
  # --- Page Configuration ---
3
- st.set_page_config(layout="wide", page_title="柳暗花明 (flowillower)", page_icon=":sunrise_over_mountains:", initial_sidebar_state="expanded")
 
 
 
 
 
4
 
5
  from pathlib import Path
6
  import plotly.graph_objects as go
@@ -15,7 +21,7 @@ st.logo("logo.png", icon_image="logo.png")
15
  # 导入重构后的模块
16
  try:
17
  from utils import DATA_ROOT_PATH, AppMode
18
- from data_models import Study, Trial # Study, Trial will be used
19
  from data_loader import discover_studies_cached, ensure_data_directory_exists
20
  from theme_selector import render_theme_selector # 新增:导入主题选择器
21
  except ImportError as e:
@@ -48,8 +54,6 @@ if "auto_play_needs_rerun" not in st.session_state:
48
  st.session_state.auto_play_needs_rerun = False
49
 
50
 
51
-
52
-
53
  # --- UI Rendering ---
54
 
55
  # --- Header ---
@@ -63,24 +67,30 @@ all_study_objects = discover_studies_cached(DATA_ROOT_PATH)
63
  study_names = list(all_study_objects.keys())
64
 
65
  if not study_names:
66
- st.warning(f"在 {DATA_ROOT_PATH} 未找到任何 Study。请确保您的数据结构正确或使用 flowillower API 开始记录实验。")
 
 
67
 
68
  if study_names:
69
  with header_cols[1]:
70
  if st.session_state.selected_study_name not in study_names:
71
- st.session_state.selected_study_name = study_names[0] if study_names else None
 
 
72
 
73
  selected_study_name_from_ui = st.selectbox(
74
  "选择 Study (Select Study)",
75
  study_names,
76
- index=study_names.index(st.session_state.selected_study_name) if st.session_state.selected_study_name in study_names else 0,
 
 
77
  label_visibility="collapsed",
78
- key="study_selector_main_ui"
79
  )
80
  if selected_study_name_from_ui != st.session_state.selected_study_name:
81
  st.session_state.selected_study_name = selected_study_name_from_ui
82
- st.session_state.selected_trial_name = None
83
- st.session_state.shared_selected_global_step = None # Study 变化时清除高亮
84
  st.rerun()
85
 
86
  with header_cols[2]:
@@ -90,9 +100,12 @@ else:
90
  with header_cols[1]:
91
  st.info("没有可用的 Study。")
92
 
93
- with header_cols[3]: st.button("➕", help="添加 (Add)", disabled=True)
94
- with header_cols[4]: st.button("⚙️", help="设置 (Settings)", disabled=True)
95
- with header_cols[5]: st.button("👤", help="用户 (User)", disabled=True)
 
 
 
96
  with header_cols[6]: # 新增:主题选择器列
97
  with st.container():
98
  # st.markdown("**主题**")
@@ -101,7 +114,10 @@ st.markdown("---")
101
 
102
  # --- Sidebar ---
103
  current_study: Study | None = None
104
- if st.session_state.selected_study_name and st.session_state.selected_study_name in all_study_objects:
 
 
 
105
  current_study = all_study_objects[st.session_state.selected_study_name]
106
  if not current_study.trials:
107
  current_study.discover_trials_cached()
@@ -113,10 +129,16 @@ with st.sidebar:
113
  if current_study:
114
  st.markdown(f"##### {current_study.name}")
115
  if st.button("刷新 Study 数据 (Refresh Study Data)", use_container_width=True):
116
- current_study.clear_cache()
117
  st.rerun()
118
- if st.button("概览 (Overview)", use_container_width=True, disabled=True): st.toast("功能待实现")
119
- if st.button("图表对比视图 (Chart Comparison View)", use_container_width=True, disabled=True): st.toast("功能待实现")
 
 
 
 
 
 
120
  else:
121
  st.markdown("未选择 Study")
122
 
@@ -124,18 +146,22 @@ with st.sidebar:
124
  st.markdown("### Trial")
125
  if current_study and trial_names:
126
  if st.session_state.selected_trial_name not in trial_names:
127
- st.session_state.selected_trial_name = trial_names[0] if trial_names else None
 
 
128
 
129
  selected_trial_name_from_ui = st.radio(
130
  "选择 Trial (Select Trial)",
131
  trial_names,
132
- index=trial_names.index(st.session_state.selected_trial_name) if st.session_state.selected_trial_name in trial_names else 0,
 
 
133
  label_visibility="collapsed",
134
- key="trial_selector_sidebar_ui"
135
  )
136
  if selected_trial_name_from_ui != st.session_state.selected_trial_name:
137
  st.session_state.selected_trial_name = selected_trial_name_from_ui
138
- st.session_state.shared_selected_global_step = None # Trial 变化时清除高亮
139
  st.rerun()
140
  if st.session_state.selected_trial_name:
141
  st.markdown(f"当前选择: **{st.session_state.selected_trial_name}**")
@@ -144,17 +170,22 @@ with st.sidebar:
144
  else:
145
  st.info("请先选择一个 Study。")
146
  st.markdown("---")
147
- if st.button("⚙️ App 设置 (App Settings)", use_container_width=True, disabled=True): st.toast("功能待实现")
 
148
 
149
  # --- Main Content Area ---
150
  current_trial: Trial | None = None
151
- if current_study and st.session_state.selected_trial_name and st.session_state.selected_trial_name in current_study.trials:
 
 
 
 
152
  current_trial = current_study.trials[st.session_state.selected_trial_name]
153
  current_trial.load_input_variables_cached()
154
  current_trial.load_metrics_cached()
155
 
156
  if current_study and current_trial:
157
- main_title_cols = st.columns([3,1, 0.5])
158
  with main_title_cols[0]:
159
  st.markdown(f"## {current_trial.name}")
160
  st.caption(f"属于 Study: {current_study.name}")
@@ -162,50 +193,60 @@ if current_study and current_trial:
162
  if st.button("刷新 Trial 数据 (Refresh Trial Data)", type="secondary"):
163
  current_trial.clear_cache()
164
  st.rerun()
165
- with main_title_cols[2]: st.button("...", help="更多选项 (More Options)", disabled=True)
 
166
 
167
  # 添加全局步骤控制器
168
  if current_trial.metrics_data:
169
  st.markdown("### 全局步骤控制 (Global Step Control)")
170
-
171
  # 获取所有指标的全局步骤范围
172
  all_global_steps = set()
173
  for metric_name in current_trial.metrics_data.keys():
174
  df_metric = current_trial.get_metric_dataframe(metric_name)
175
- if df_metric is not None and not df_metric.empty and 'global_step' in df_metric.columns:
176
- all_global_steps.update(df_metric['global_step'].tolist())
177
-
 
 
 
 
178
  if all_global_steps:
179
  all_global_steps = sorted(list(all_global_steps))
180
  min_step, max_step = min(all_global_steps), max(all_global_steps)
181
-
182
  # 控制器布局
183
  control_cols = st.columns([3, 1, 1, 1])
184
-
185
  with control_cols[0]:
186
  # 滑动条
187
  if st.session_state.shared_selected_global_step is None:
188
  # 默认选择最后一个step
189
  st.session_state.shared_selected_global_step = max_step
190
-
191
  # 确保当前选中的步骤在有效范围内
192
  if st.session_state.shared_selected_global_step not in all_global_steps:
193
  # 找到最接近的有效步骤
194
- closest_step = min(all_global_steps, key=lambda x: abs(x - st.session_state.shared_selected_global_step))
 
 
 
 
 
195
  st.session_state.shared_selected_global_step = closest_step
196
-
197
  selected_step = st.select_slider(
198
  "选择全局步骤",
199
  options=all_global_steps,
200
  value=st.session_state.shared_selected_global_step,
201
  format_func=lambda x: f"Step {x}",
202
- key="global_step_slider"
203
  )
204
-
205
  if selected_step != st.session_state.shared_selected_global_step:
206
  st.session_state.shared_selected_global_step = selected_step
207
  st.rerun()
208
-
209
  with control_cols[1]:
210
  # 播放/暂停按钮
211
  if st.session_state.is_auto_playing:
@@ -216,7 +257,7 @@ if current_study and current_trial:
216
  if st.button("▶️ 播放", type="primary", use_container_width=True):
217
  st.session_state.is_auto_playing = True
218
  st.rerun()
219
-
220
  with control_cols[2]:
221
  # 速度控制
222
  speed = st.selectbox(
@@ -224,37 +265,49 @@ if current_study and current_trial:
224
  options=[0.5, 1.0, 2.0, 4.0],
225
  index=[0.5, 1.0, 2.0, 4.0].index(st.session_state.auto_play_speed),
226
  format_func=lambda x: f"{x}x",
227
- key="speed_selector"
228
  )
229
  if speed != st.session_state.auto_play_speed:
230
  st.session_state.auto_play_speed = speed
231
-
232
  with control_cols[3]:
233
  # 重置按钮
234
  if st.button("🔄 重置", use_container_width=True):
235
  st.session_state.shared_selected_global_step = min_step
236
  st.session_state.is_auto_playing = False
237
  st.rerun()
238
-
239
  # 自动播放逻辑 - 设置标志但不立即rerun
240
  if st.session_state.is_auto_playing:
241
- current_index = all_global_steps.index(st.session_state.shared_selected_global_step)
 
 
242
  if current_index < len(all_global_steps) - 1:
243
  # 等待指定时间后移动到下一步
244
  time.sleep(1.0 / st.session_state.auto_play_speed)
245
- st.session_state.shared_selected_global_step = all_global_steps[current_index + 1]
 
 
246
  st.session_state.auto_play_needs_rerun = True
247
  else:
248
  # 到达末尾,停止播放
249
  st.session_state.is_auto_playing = False
250
  st.session_state.auto_play_needs_rerun = True
251
-
252
  # 显示当前步骤信息
253
- st.info(f"当前选中步骤: **{st.session_state.shared_selected_global_step}** / {max_step}")
254
-
 
 
255
  st.markdown("---")
256
 
257
- tab_titles = ["图表 (Charts)", "参数 (Parameters)", "系统 (System)", "日志 (Logs)", "环境 (Environment)"]
 
 
 
 
 
 
258
  tab_charts, tab_params, tab_system, tab_logs, tab_env = st.tabs(tab_titles)
259
 
260
  with tab_charts:
@@ -266,12 +319,14 @@ if current_study and current_trial:
266
  else:
267
  num_metrics = len(current_trial.metrics_data)
268
  cols_per_row = st.slider(
269
- "每行图表数量 (Charts per row)", 1, 4,
270
- min(2, num_metrics) if num_metrics > 0 else 1,
271
- key=f"cols_slider_{current_study.name}_{current_trial.name}"
 
 
272
  )
273
  metric_names = sorted(list(current_trial.metrics_data.keys()))
274
-
275
  for i in range(0, num_metrics, cols_per_row):
276
  metric_chunk = metric_names[i : i + cols_per_row]
277
  chart_cols = st.columns(cols_per_row)
@@ -281,78 +336,116 @@ if current_study and current_trial:
281
  if df_metric is None or df_metric.empty:
282
  st.warning(f"指标 '{metric_name}' 数据不完整或缺失。")
283
  continue
284
-
285
  with st.container(border=True):
286
  st.subheader(metric_name)
287
-
288
  # 添加metric组件 - 显示当前值和增量
289
  try:
290
- current_step = st.session_state.shared_selected_global_step
291
-
 
 
292
  # 获取所有可能的track
293
- all_tracks = df_metric['track'].unique() if 'track' in df_metric.columns else [None]
294
-
 
 
 
 
295
  # 为每个track创建metric组件
296
  if len(all_tracks) > 1:
297
  metric_cols = st.columns(len(all_tracks))
298
  else:
299
  metric_cols = [st] # 使用整个容器
300
-
301
  for idx, track in enumerate(all_tracks):
302
  # 查找当前步骤的数据
303
  if track is not None:
304
  current_step_data = df_metric[
305
- (df_metric['global_step'] == current_step) &
306
- (df_metric['track'] == track)
307
  ]
308
  else:
309
- current_step_data = df_metric[df_metric['global_step'] == current_step]
310
-
 
 
311
  current_value = None
312
  delta_value = None
313
-
314
  # 如果当前步骤没有该track的数据,向前查找最近的步骤
315
  if current_step_data.empty:
316
  # 向前查找最近的有该track数据的步骤
317
- current_index = all_global_steps.index(current_step)
318
- for search_idx in range(current_index - 1, -1, -1):
 
 
 
 
319
  search_step = all_global_steps[search_idx]
320
  if track is not None:
321
  search_data = df_metric[
322
- (df_metric['global_step'] == search_step) &
323
- (df_metric['track'] == track)
 
 
 
324
  ]
325
  else:
326
- search_data = df_metric[df_metric['global_step'] == search_step]
327
-
 
 
 
328
  if not search_data.empty:
329
- current_value = search_data['value'].iloc[0]
 
 
330
  current_step_found = search_step
331
  break
332
  else:
333
- current_value = current_step_data['value'].iloc[0]
 
 
334
  current_step_found = current_step
335
-
336
  # 计算增量:查找比当前找到的步骤更早的数据
337
  if current_value is not None:
338
- current_found_index = all_global_steps.index(current_step_found)
339
- for prev_idx in range(current_found_index - 1, -1, -1):
 
 
 
 
340
  prev_step = all_global_steps[prev_idx]
341
  if track is not None:
342
  prev_step_data = df_metric[
343
- (df_metric['global_step'] == prev_step) &
344
- (df_metric['track'] == track)
 
 
 
345
  ]
346
  else:
347
- prev_step_data = df_metric[df_metric['global_step'] == prev_step]
348
-
 
 
 
349
  if not prev_step_data.empty:
350
- prev_value = prev_step_data['value'].iloc[0]
 
 
351
  delta_value = current_value - prev_value
352
  break
353
-
354
  # 显示metric组件
355
- with metric_cols[idx] if len(all_tracks) > 1 else metric_cols[0]:
 
 
 
 
356
  if current_value is not None:
357
  # 确定label
358
  if track is not None:
@@ -364,120 +457,163 @@ if current_study and current_trial:
364
  if current_step_found != current_step:
365
  label = f"当前值 (Step {current_step_found})"
366
  else:
367
- label = f"当前值 (Step {current_step})"
368
-
 
 
369
  st.metric(
370
  label=label,
371
  value=f"{current_value:.4f}",
372
- delta=f"{delta_value:.4f}" if delta_value is not None else None
 
 
373
  )
374
  else:
375
  # 没有找到任何数据
376
- track_label = track if track is not None else "数据"
 
 
377
  st.metric(
378
  label=f"{track_label}",
379
  value="无数据",
380
- delta=None
381
  )
382
-
383
  except Exception as e:
384
  st.warning(f"计算指标值时出错: {e}")
385
 
386
  try:
387
  # 创建 Plotly 图表
388
  fig = go.Figure()
389
-
390
  # 按track分组绘制线条
391
- if 'track' in df_metric.columns:
392
- tracks = df_metric['track'].unique()
393
- colors = px.colors.qualitative.Set1[:len(tracks)]
394
-
395
  for k, track in enumerate(tracks):
396
- track_data = df_metric[df_metric['track'] == track]
397
- fig.add_trace(go.Scatter(
398
- x=track_data['global_step'],
399
- y=track_data['value'],
400
- mode='lines+markers',
401
- name=track,
402
- line=dict(color=colors[k % len(colors)]),
403
- marker=dict(size=6, color=colors[k % len(colors)],
404
- line=dict(width=1, color='white')),
405
- customdata=track_data[['global_step', 'value', 'track']],
406
- hovertemplate='<b>%{fullData.name}</b><br>' +
407
- 'Global Step: %{x}<br>' +
408
- 'Value: %{y}<br>' +
409
- '<extra></extra>'
410
- ))
 
 
 
 
 
 
 
 
 
 
 
411
  else:
412
  # 如果没有track列,绘制单条线
413
- fig.add_trace(go.Scatter(
414
- x=df_metric['global_step'],
415
- y=df_metric['value'],
416
- mode='lines+markers',
417
- name=metric_name,
418
- marker=dict(size=6, line=dict(width=1, color='white')),
419
- customdata=df_metric[['global_step', 'value']],
420
- hovertemplate='Global Step: %{x}<br>' +
421
- 'Value: %{y}<br>' +
422
- '<extra></extra>'
423
- ))
424
-
 
 
 
 
 
 
 
425
  # 如果有共享的选中步骤,添加高亮线
426
- if st.session_state.shared_selected_global_step is not None:
 
 
 
427
  fig.add_vline(
428
  x=st.session_state.shared_selected_global_step,
429
  line_width=2,
430
  line_dash="solid",
431
  line_color="firebrick",
432
- opacity=0.9
433
  )
434
-
435
  # 设置图表布局
436
  fig.update_layout(
437
  title=None,
438
- xaxis_title='全局步骤 (Global Step)',
439
  yaxis_title=metric_name,
440
  height=400,
441
  margin=dict(l=0, r=0, t=0, b=0),
442
- showlegend=True if 'track' in df_metric.columns and len(df_metric['track'].unique()) > 1 else False,
443
- hovermode='closest'
 
 
 
444
  )
445
-
446
  # 显示图表并处理点击事件
447
  chart_key = f"chart_metric_{current_study.name}_{current_trial.name}_{metric_name}"
448
  clicked_points = st.plotly_chart(
449
- fig,
450
  use_container_width=True,
451
  key=chart_key,
452
- on_select="rerun"
453
  )
454
-
455
  # 处理点击事件
456
- if clicked_points and 'selection' in clicked_points:
457
- selection = clicked_points['selection']
458
- if 'points' in selection and len(selection['points']) > 0:
 
 
 
459
  # 获取第一个点击点的 x 坐标 (global_step)
460
- clicked_x = selection['points'][0]['x']
461
  if clicked_x is not None:
462
  new_step = int(clicked_x)
463
- if st.session_state.get("shared_selected_global_step") != new_step:
 
 
 
 
 
464
  st.session_state.shared_selected_global_step = new_step
465
  # 点击图表时停止自动播放
466
  st.session_state.is_auto_playing = False
467
  st.rerun()
468
-
469
  except Exception as e:
470
  st.error(f"为指标 '{metric_name}' 生成图表时出错: {e}")
471
  st.dataframe(df_metric)
472
- # raise e
473
-
474
 
475
  with tab_params:
476
  st.header("输入参数 (Input Parameters)")
477
- if current_trial.input_variables: st.json(current_trial.input_variables)
478
- else: st.info("未找到 `input_variables.toml` 或文件为空。")
 
 
479
 
480
- for tab_content, name in [(tab_system, "系统监控"), (tab_logs, "日志"), (tab_env, "环境")]:
 
 
 
 
481
  with tab_content:
482
  st.header(name)
483
  st.info("此功能待您的 `flowillower` API 提供相关数据后实现。")
 
1
  import streamlit as st
2
+
3
  # --- Page Configuration ---
4
+ st.set_page_config(
5
+ layout="wide",
6
+ page_title="柳暗花明 (flowillower)",
7
+ page_icon=":sunrise_over_mountains:",
8
+ initial_sidebar_state="expanded",
9
+ )
10
 
11
  from pathlib import Path
12
  import plotly.graph_objects as go
 
21
  # 导入重构后的模块
22
  try:
23
  from utils import DATA_ROOT_PATH, AppMode
24
+ from data_models import Study, Trial # Study, Trial will be used
25
  from data_loader import discover_studies_cached, ensure_data_directory_exists
26
  from theme_selector import render_theme_selector # 新增:导入主题选择器
27
  except ImportError as e:
 
54
  st.session_state.auto_play_needs_rerun = False
55
 
56
 
 
 
57
  # --- UI Rendering ---
58
 
59
  # --- Header ---
 
67
  study_names = list(all_study_objects.keys())
68
 
69
  if not study_names:
70
+ st.warning(
71
+ f"在 {DATA_ROOT_PATH} 未找到任何 Study。请确保您的数据结构正确或使用 flowillower API 开始记录实验。"
72
+ )
73
 
74
  if study_names:
75
  with header_cols[1]:
76
  if st.session_state.selected_study_name not in study_names:
77
+ st.session_state.selected_study_name = (
78
+ study_names[0] if study_names else None
79
+ )
80
 
81
  selected_study_name_from_ui = st.selectbox(
82
  "选择 Study (Select Study)",
83
  study_names,
84
+ index=study_names.index(st.session_state.selected_study_name)
85
+ if st.session_state.selected_study_name in study_names
86
+ else 0,
87
  label_visibility="collapsed",
88
+ key="study_selector_main_ui",
89
  )
90
  if selected_study_name_from_ui != st.session_state.selected_study_name:
91
  st.session_state.selected_study_name = selected_study_name_from_ui
92
+ st.session_state.selected_trial_name = None
93
+ st.session_state.shared_selected_global_step = None # Study 变化时清除高亮
94
  st.rerun()
95
 
96
  with header_cols[2]:
 
100
  with header_cols[1]:
101
  st.info("没有可用的 Study。")
102
 
103
+ with header_cols[3]:
104
+ st.button("", help="添加 (Add)", disabled=True)
105
+ with header_cols[4]:
106
+ st.button("⚙️", help="设置 (Settings)", disabled=True)
107
+ with header_cols[5]:
108
+ st.button("👤", help="用户 (User)", disabled=True)
109
  with header_cols[6]: # 新增:主题选择器列
110
  with st.container():
111
  # st.markdown("**主题**")
 
114
 
115
  # --- Sidebar ---
116
  current_study: Study | None = None
117
+ if (
118
+ st.session_state.selected_study_name
119
+ and st.session_state.selected_study_name in all_study_objects
120
+ ):
121
  current_study = all_study_objects[st.session_state.selected_study_name]
122
  if not current_study.trials:
123
  current_study.discover_trials_cached()
 
129
  if current_study:
130
  st.markdown(f"##### {current_study.name}")
131
  if st.button("刷新 Study 数据 (Refresh Study Data)", use_container_width=True):
132
+ current_study.clear_cache()
133
  st.rerun()
134
+ if st.button("概览 (Overview)", use_container_width=True, disabled=True):
135
+ st.toast("功能待实现")
136
+ if st.button(
137
+ "图表对比视图 (Chart Comparison View)",
138
+ use_container_width=True,
139
+ disabled=True,
140
+ ):
141
+ st.toast("功能待实现")
142
  else:
143
  st.markdown("未选择 Study")
144
 
 
146
  st.markdown("### Trial")
147
  if current_study and trial_names:
148
  if st.session_state.selected_trial_name not in trial_names:
149
+ st.session_state.selected_trial_name = (
150
+ trial_names[0] if trial_names else None
151
+ )
152
 
153
  selected_trial_name_from_ui = st.radio(
154
  "选择 Trial (Select Trial)",
155
  trial_names,
156
+ index=trial_names.index(st.session_state.selected_trial_name)
157
+ if st.session_state.selected_trial_name in trial_names
158
+ else 0,
159
  label_visibility="collapsed",
160
+ key="trial_selector_sidebar_ui",
161
  )
162
  if selected_trial_name_from_ui != st.session_state.selected_trial_name:
163
  st.session_state.selected_trial_name = selected_trial_name_from_ui
164
+ st.session_state.shared_selected_global_step = None # Trial 变化时清除高亮
165
  st.rerun()
166
  if st.session_state.selected_trial_name:
167
  st.markdown(f"当前选择: **{st.session_state.selected_trial_name}**")
 
170
  else:
171
  st.info("请先选择一个 Study。")
172
  st.markdown("---")
173
+ if st.button("⚙️ App 设置 (App Settings)", use_container_width=True, disabled=True):
174
+ st.toast("功能待实现")
175
 
176
  # --- Main Content Area ---
177
  current_trial: Trial | None = None
178
+ if (
179
+ current_study
180
+ and st.session_state.selected_trial_name
181
+ and st.session_state.selected_trial_name in current_study.trials
182
+ ):
183
  current_trial = current_study.trials[st.session_state.selected_trial_name]
184
  current_trial.load_input_variables_cached()
185
  current_trial.load_metrics_cached()
186
 
187
  if current_study and current_trial:
188
+ main_title_cols = st.columns([3, 1, 0.5])
189
  with main_title_cols[0]:
190
  st.markdown(f"## {current_trial.name}")
191
  st.caption(f"属于 Study: {current_study.name}")
 
193
  if st.button("刷新 Trial 数据 (Refresh Trial Data)", type="secondary"):
194
  current_trial.clear_cache()
195
  st.rerun()
196
+ with main_title_cols[2]:
197
+ st.button("...", help="更多选项 (More Options)", disabled=True)
198
 
199
  # 添加全局步骤控制器
200
  if current_trial.metrics_data:
201
  st.markdown("### 全局步骤控制 (Global Step Control)")
202
+
203
  # 获取所有指标的全局步骤范围
204
  all_global_steps = set()
205
  for metric_name in current_trial.metrics_data.keys():
206
  df_metric = current_trial.get_metric_dataframe(metric_name)
207
+ if (
208
+ df_metric is not None
209
+ and not df_metric.empty
210
+ and "global_step" in df_metric.columns
211
+ ):
212
+ all_global_steps.update(df_metric["global_step"].tolist())
213
+
214
  if all_global_steps:
215
  all_global_steps = sorted(list(all_global_steps))
216
  min_step, max_step = min(all_global_steps), max(all_global_steps)
217
+
218
  # 控制器布局
219
  control_cols = st.columns([3, 1, 1, 1])
220
+
221
  with control_cols[0]:
222
  # 滑动条
223
  if st.session_state.shared_selected_global_step is None:
224
  # 默认选择最后一个step
225
  st.session_state.shared_selected_global_step = max_step
226
+
227
  # 确保当前选中的步骤在有效范围内
228
  if st.session_state.shared_selected_global_step not in all_global_steps:
229
  # 找到最接近的有效步骤
230
+ closest_step = min(
231
+ all_global_steps,
232
+ key=lambda x: abs(
233
+ x - st.session_state.shared_selected_global_step
234
+ ),
235
+ )
236
  st.session_state.shared_selected_global_step = closest_step
237
+
238
  selected_step = st.select_slider(
239
  "选择全局步骤",
240
  options=all_global_steps,
241
  value=st.session_state.shared_selected_global_step,
242
  format_func=lambda x: f"Step {x}",
243
+ key="global_step_slider",
244
  )
245
+
246
  if selected_step != st.session_state.shared_selected_global_step:
247
  st.session_state.shared_selected_global_step = selected_step
248
  st.rerun()
249
+
250
  with control_cols[1]:
251
  # 播放/暂停按钮
252
  if st.session_state.is_auto_playing:
 
257
  if st.button("▶️ 播放", type="primary", use_container_width=True):
258
  st.session_state.is_auto_playing = True
259
  st.rerun()
260
+
261
  with control_cols[2]:
262
  # 速度控制
263
  speed = st.selectbox(
 
265
  options=[0.5, 1.0, 2.0, 4.0],
266
  index=[0.5, 1.0, 2.0, 4.0].index(st.session_state.auto_play_speed),
267
  format_func=lambda x: f"{x}x",
268
+ key="speed_selector",
269
  )
270
  if speed != st.session_state.auto_play_speed:
271
  st.session_state.auto_play_speed = speed
272
+
273
  with control_cols[3]:
274
  # 重置按钮
275
  if st.button("🔄 重置", use_container_width=True):
276
  st.session_state.shared_selected_global_step = min_step
277
  st.session_state.is_auto_playing = False
278
  st.rerun()
279
+
280
  # 自动播放逻辑 - 设置标志但不立即rerun
281
  if st.session_state.is_auto_playing:
282
+ current_index = all_global_steps.index(
283
+ st.session_state.shared_selected_global_step
284
+ )
285
  if current_index < len(all_global_steps) - 1:
286
  # 等待指定时间后移动到下一步
287
  time.sleep(1.0 / st.session_state.auto_play_speed)
288
+ st.session_state.shared_selected_global_step = all_global_steps[
289
+ current_index + 1
290
+ ]
291
  st.session_state.auto_play_needs_rerun = True
292
  else:
293
  # 到达末尾,停止播放
294
  st.session_state.is_auto_playing = False
295
  st.session_state.auto_play_needs_rerun = True
296
+
297
  # 显示当前步骤信息
298
+ st.info(
299
+ f"当前选中步骤: **{st.session_state.shared_selected_global_step}** / {max_step}"
300
+ )
301
+
302
  st.markdown("---")
303
 
304
+ tab_titles = [
305
+ "图表 (Charts)",
306
+ "参数 (Parameters)",
307
+ "系统 (System)",
308
+ "日志 (Logs)",
309
+ "环境 (Environment)",
310
+ ]
311
  tab_charts, tab_params, tab_system, tab_logs, tab_env = st.tabs(tab_titles)
312
 
313
  with tab_charts:
 
319
  else:
320
  num_metrics = len(current_trial.metrics_data)
321
  cols_per_row = st.slider(
322
+ "每行图表数量 (Charts per row)",
323
+ 1,
324
+ 4,
325
+ min(2, num_metrics) if num_metrics > 0 else 1,
326
+ key=f"cols_slider_{current_study.name}_{current_trial.name}",
327
  )
328
  metric_names = sorted(list(current_trial.metrics_data.keys()))
329
+
330
  for i in range(0, num_metrics, cols_per_row):
331
  metric_chunk = metric_names[i : i + cols_per_row]
332
  chart_cols = st.columns(cols_per_row)
 
336
  if df_metric is None or df_metric.empty:
337
  st.warning(f"指标 '{metric_name}' 数据不完整或缺失。")
338
  continue
339
+
340
  with st.container(border=True):
341
  st.subheader(metric_name)
342
+
343
  # 添加metric组件 - 显示当前值和增量
344
  try:
345
+ current_step = (
346
+ st.session_state.shared_selected_global_step
347
+ )
348
+
349
  # 获取所有可能的track
350
+ all_tracks = (
351
+ df_metric["track"].unique()
352
+ if "track" in df_metric.columns
353
+ else [None]
354
+ )
355
+
356
  # 为每个track创建metric组件
357
  if len(all_tracks) > 1:
358
  metric_cols = st.columns(len(all_tracks))
359
  else:
360
  metric_cols = [st] # 使用整个容器
361
+
362
  for idx, track in enumerate(all_tracks):
363
  # 查找当前步骤的数据
364
  if track is not None:
365
  current_step_data = df_metric[
366
+ (df_metric["global_step"] == current_step)
367
+ & (df_metric["track"] == track)
368
  ]
369
  else:
370
+ current_step_data = df_metric[
371
+ df_metric["global_step"] == current_step
372
+ ]
373
+
374
  current_value = None
375
  delta_value = None
376
+
377
  # 如果当前步骤没有该track的数据,向前查找最近的步骤
378
  if current_step_data.empty:
379
  # 向前查找最近的有该track数据的步骤
380
+ current_index = all_global_steps.index(
381
+ current_step
382
+ )
383
+ for search_idx in range(
384
+ current_index - 1, -1, -1
385
+ ):
386
  search_step = all_global_steps[search_idx]
387
  if track is not None:
388
  search_data = df_metric[
389
+ (
390
+ df_metric["global_step"]
391
+ == search_step
392
+ )
393
+ & (df_metric["track"] == track)
394
  ]
395
  else:
396
+ search_data = df_metric[
397
+ df_metric["global_step"]
398
+ == search_step
399
+ ]
400
+
401
  if not search_data.empty:
402
+ current_value = search_data[
403
+ "value"
404
+ ].iloc[0]
405
  current_step_found = search_step
406
  break
407
  else:
408
+ current_value = current_step_data["value"].iloc[
409
+ 0
410
+ ]
411
  current_step_found = current_step
412
+
413
  # 计算增量:查找比当前找到的步骤更早的数据
414
  if current_value is not None:
415
+ current_found_index = all_global_steps.index(
416
+ current_step_found
417
+ )
418
+ for prev_idx in range(
419
+ current_found_index - 1, -1, -1
420
+ ):
421
  prev_step = all_global_steps[prev_idx]
422
  if track is not None:
423
  prev_step_data = df_metric[
424
+ (
425
+ df_metric["global_step"]
426
+ == prev_step
427
+ )
428
+ & (df_metric["track"] == track)
429
  ]
430
  else:
431
+ prev_step_data = df_metric[
432
+ df_metric["global_step"]
433
+ == prev_step
434
+ ]
435
+
436
  if not prev_step_data.empty:
437
+ prev_value = prev_step_data[
438
+ "value"
439
+ ].iloc[0]
440
  delta_value = current_value - prev_value
441
  break
442
+
443
  # 显示metric组件
444
+ with (
445
+ metric_cols[idx]
446
+ if len(all_tracks) > 1
447
+ else metric_cols[0]
448
+ ):
449
  if current_value is not None:
450
  # 确定label
451
  if track is not None:
 
457
  if current_step_found != current_step:
458
  label = f"当前值 (Step {current_step_found})"
459
  else:
460
+ label = (
461
+ f"当前值 (Step {current_step})"
462
+ )
463
+
464
  st.metric(
465
  label=label,
466
  value=f"{current_value:.4f}",
467
+ delta=f"{delta_value:.4f}"
468
+ if delta_value is not None
469
+ else None,
470
  )
471
  else:
472
  # 没有找到任何数据
473
+ track_label = (
474
+ track if track is not None else "数据"
475
+ )
476
  st.metric(
477
  label=f"{track_label}",
478
  value="无数据",
479
+ delta=None,
480
  )
481
+
482
  except Exception as e:
483
  st.warning(f"计算指标值时出错: {e}")
484
 
485
  try:
486
  # 创建 Plotly 图表
487
  fig = go.Figure()
488
+
489
  # 按track分组绘制线条
490
+ if "track" in df_metric.columns:
491
+ tracks = df_metric["track"].unique()
492
+ colors = px.colors.qualitative.Set1[: len(tracks)]
493
+
494
  for k, track in enumerate(tracks):
495
+ track_data = df_metric[
496
+ df_metric["track"] == track
497
+ ]
498
+ fig.add_trace(
499
+ go.Scatter(
500
+ x=track_data["global_step"],
501
+ y=track_data["value"],
502
+ mode="lines+markers",
503
+ name=track,
504
+ line=dict(
505
+ color=colors[k % len(colors)]
506
+ ),
507
+ marker=dict(
508
+ size=6,
509
+ color=colors[k % len(colors)],
510
+ line=dict(width=1, color="white"),
511
+ ),
512
+ customdata=track_data[
513
+ ["global_step", "value", "track"]
514
+ ],
515
+ hovertemplate="<b>%{fullData.name}</b><br>"
516
+ + "Global Step: %{x}<br>"
517
+ + "Value: %{y}<br>"
518
+ + "<extra></extra>",
519
+ )
520
+ )
521
  else:
522
  # 如果没有track列,绘制单条线
523
+ fig.add_trace(
524
+ go.Scatter(
525
+ x=df_metric["global_step"],
526
+ y=df_metric["value"],
527
+ mode="lines+markers",
528
+ name=metric_name,
529
+ marker=dict(
530
+ size=6,
531
+ line=dict(width=1, color="white"),
532
+ ),
533
+ customdata=df_metric[
534
+ ["global_step", "value"]
535
+ ],
536
+ hovertemplate="Global Step: %{x}<br>"
537
+ + "Value: %{y}<br>"
538
+ + "<extra></extra>",
539
+ )
540
+ )
541
+
542
  # 如果有共享的选中步骤,添加高亮线
543
+ if (
544
+ st.session_state.shared_selected_global_step
545
+ is not None
546
+ ):
547
  fig.add_vline(
548
  x=st.session_state.shared_selected_global_step,
549
  line_width=2,
550
  line_dash="solid",
551
  line_color="firebrick",
552
+ opacity=0.9,
553
  )
554
+
555
  # 设置图表布局
556
  fig.update_layout(
557
  title=None,
558
+ xaxis_title="全局步骤 (Global Step)",
559
  yaxis_title=metric_name,
560
  height=400,
561
  margin=dict(l=0, r=0, t=0, b=0),
562
+ showlegend=True
563
+ if "track" in df_metric.columns
564
+ and len(df_metric["track"].unique()) > 1
565
+ else False,
566
+ hovermode="closest",
567
  )
568
+
569
  # 显示图表并处理点击事件
570
  chart_key = f"chart_metric_{current_study.name}_{current_trial.name}_{metric_name}"
571
  clicked_points = st.plotly_chart(
572
+ fig,
573
  use_container_width=True,
574
  key=chart_key,
575
+ on_select="rerun",
576
  )
577
+
578
  # 处理点击事件
579
+ if clicked_points and "selection" in clicked_points:
580
+ selection = clicked_points["selection"]
581
+ if (
582
+ "points" in selection
583
+ and len(selection["points"]) > 0
584
+ ):
585
  # 获取第一个点击点的 x 坐标 (global_step)
586
+ clicked_x = selection["points"][0]["x"]
587
  if clicked_x is not None:
588
  new_step = int(clicked_x)
589
+ if (
590
+ st.session_state.get(
591
+ "shared_selected_global_step"
592
+ )
593
+ != new_step
594
+ ):
595
  st.session_state.shared_selected_global_step = new_step
596
  # 点击图表时停止自动播放
597
  st.session_state.is_auto_playing = False
598
  st.rerun()
599
+
600
  except Exception as e:
601
  st.error(f"为指标 '{metric_name}' 生成图表时出错: {e}")
602
  st.dataframe(df_metric)
603
+ # raise e
 
604
 
605
  with tab_params:
606
  st.header("输入参数 (Input Parameters)")
607
+ if current_trial.input_variables:
608
+ st.json(current_trial.input_variables)
609
+ else:
610
+ st.info("未找到 `input_variables.toml` 或文件为空。")
611
 
612
+ for tab_content, name in [
613
+ (tab_system, "系统监控"),
614
+ (tab_logs, "日志"),
615
+ (tab_env, "环境"),
616
+ ]:
617
  with tab_content:
618
  st.header(name)
619
  st.info("此功能待您的 `flowillower` API 提供相关数据后实现。")
src/test.py CHANGED
@@ -8,8 +8,9 @@ y1 = np.sin(x)
8
  y2 = np.cos(x)
9
 
10
  # 创建两个 FigureWidget 图表
11
- fig1 = go.FigureWidget(data=[go.Scatter(x=x, y=y1, mode='lines', name='sin(x)')])
12
- fig2 = go.FigureWidget(data=[go.Scatter(x=x, y=y2, mode='lines', name='cos(x)')])
 
13
 
14
  # 定义悬停事件的回调函数
15
  def hover_fn(trace, points, state):
@@ -17,20 +18,24 @@ def hover_fn(trace, points, state):
17
  hover_x = points.xs[0]
18
  with fig2.batch_update():
19
  # 在第二个图表上添加垂直线
20
- fig2.layout.shapes = [dict(
21
- type='line',
22
- x0=hover_x,
23
- x1=hover_x,
24
- y0=min(y2),
25
- y1=max(y2),
26
- line=dict(color='red', dash='dot')
27
- )]
 
 
 
28
 
29
  # 为第一个图表的第一个 trace 注册悬停事件
30
  fig1.data[0].on_hover(hover_fn)
31
 
32
  # 显示图表
33
  import streamlit as st
 
34
  st.plotly_chart(fig1, use_container_width=True)
35
  st.plotly_chart(fig2, use_container_width=True)
36
 
 
8
  y2 = np.cos(x)
9
 
10
  # 创建两个 FigureWidget 图表
11
+ fig1 = go.FigureWidget(data=[go.Scatter(x=x, y=y1, mode="lines", name="sin(x)")])
12
+ fig2 = go.FigureWidget(data=[go.Scatter(x=x, y=y2, mode="lines", name="cos(x)")])
13
+
14
 
15
  # 定义悬停事件的回调函数
16
  def hover_fn(trace, points, state):
 
18
  hover_x = points.xs[0]
19
  with fig2.batch_update():
20
  # 在第二个图表上添加垂直线
21
+ fig2.layout.shapes = [
22
+ dict(
23
+ type="line",
24
+ x0=hover_x,
25
+ x1=hover_x,
26
+ y0=min(y2),
27
+ y1=max(y2),
28
+ line=dict(color="red", dash="dot"),
29
+ )
30
+ ]
31
+
32
 
33
  # 为第一个图表的第一个 trace 注册悬停事件
34
  fig1.data[0].on_hover(hover_fn)
35
 
36
  # 显示图表
37
  import streamlit as st
38
+
39
  st.plotly_chart(fig1, use_container_width=True)
40
  st.plotly_chart(fig2, use_container_width=True)
41
 
src/theme_selector.py CHANGED
@@ -4,65 +4,68 @@ from pathlib import Path
4
  import os
5
  import time
6
 
 
7
  class ThemeSelector:
8
- def __init__(self, themes_dir=".streamlit/themes", config_path=".streamlit/config.toml"):
 
 
9
  self.themes_dir = Path(themes_dir)
10
  self.config_path = Path(config_path)
11
  self.themes = {}
12
  self.load_themes()
13
-
14
  def load_themes(self):
15
  """加载所有主题文件"""
16
  self.themes = {}
17
  if not self.themes_dir.exists():
18
  return
19
-
20
  for theme_file in self.themes_dir.glob("*.toml"):
21
  try:
22
  theme_data = toml.load(theme_file)
23
-
24
  # 从根级别获取theme_name和theme_poem
25
  theme_name = theme_data.get("theme_name", theme_file.stem)
26
  theme_poem = theme_data.get("theme_poem", "")
27
  theme_config = theme_data.get("theme", {})
28
-
29
  self.themes[theme_name] = {
30
  "file": theme_file,
31
  "name": theme_name,
32
  "poem": theme_poem,
33
- "config": theme_config
34
  }
35
  except Exception as e:
36
  st.warning(f"读取主题文件 {theme_file} 失败: {e}")
37
-
38
  def get_current_theme(self):
39
  """获取当前主题名称"""
40
  if not self.config_path.exists():
41
  return None
42
-
43
  try:
44
  # config = toml.load(self.config_path)
45
  # # 从根级别读取theme_name
46
  # current_theme_name = config.get("theme") or {}
47
  # current_theme_name = current_theme_name.get("theme_name")
48
  # return current_theme_name
49
- theme_toml = self.config_path.parent/"theme.toml"
50
  theme = toml.load(theme_toml)
51
  return theme.get("theme_name")
52
 
53
  except Exception:
54
  return None
55
-
56
  def apply_theme(self, theme_name):
57
  """应用选定的主题"""
58
  if theme_name not in self.themes:
59
  st.error(f"主题 '{theme_name}' 不存在")
60
  return False
61
-
62
  try:
63
  # 确保配置目录存在
64
  self.config_path.parent.mkdir(parents=True, exist_ok=True)
65
-
66
  # 读取现有配置或创建新配置
67
  config = {}
68
  if self.config_path.exists():
@@ -70,48 +73,51 @@ class ThemeSelector:
70
  config = toml.load(self.config_path)
71
  except Exception:
72
  config = {}
73
-
74
  # 添加根级别的theme_name和theme_poem
75
  # config["theme_name"] = self.themes[theme_name]["name"]
76
  # config["theme_poem"] = self.themes[theme_name]["poem"]
77
-
78
  # 更新主题配置
79
  theme_config = self.themes[theme_name]["config"].copy()
80
  # theme_config["theme_name"] = self.themes[theme_name]["name"]
81
  # theme_config["theme_poem"] = self.themes[theme_name]["poem"]
82
  config["theme"] |= theme_config
83
-
84
  # 写入配置文件
85
  with open(self.config_path, "w", encoding="utf-8") as f:
86
  toml.dump(config, f)
87
 
88
- theme_toml = self.config_path.parent/"theme.toml"
89
  with open(theme_toml, "w", encoding="utf-8") as f:
90
- toml.dump(dict(
91
- theme_name = self.themes[theme_name]["name"],
92
- theme_poem = self.themes[theme_name]["poem"]
93
- ), f)
94
-
 
 
 
95
  return True
96
-
97
  except Exception as e:
98
  st.error(f"应用主题失败: {e}")
99
  return False
100
-
101
  def render_theme_selector(self):
102
  """渲染主题选择器UI"""
103
  if not self.themes:
104
  st.warning("未找到可用主题")
105
  return
106
-
107
  theme_names = list(self.themes.keys())
108
  current_theme = self.get_current_theme()
109
-
110
  # 确定当前选中的索引
111
  current_index = 0
112
  if current_theme and current_theme in theme_names:
113
  current_index = theme_names.index(current_theme)
114
-
115
  # 主题选择下拉菜单
116
  selected_theme = st.selectbox(
117
  "选择主题",
@@ -119,9 +125,9 @@ class ThemeSelector:
119
  index=current_index,
120
  format_func=lambda x: self.themes[x]["name"],
121
  key="theme_selector_widget",
122
- label_visibility="collapsed"
123
  )
124
-
125
  # 如果选择了新主题
126
  if selected_theme != current_theme:
127
  if self.apply_theme(selected_theme):
@@ -131,16 +137,18 @@ class ThemeSelector:
131
  st.toast(f"✨ {theme_poem}", icon="🎨")
132
  else:
133
  st.toast(f"已切换到主题: {selected_theme}", icon="🎨")
134
-
135
  time.sleep(3)
136
  # 延迟重新运行以应用主题
137
  st.rerun()
138
-
139
  return selected_theme
140
 
 
141
  # 全局主题选择器实例
142
  _theme_selector = None
143
 
 
144
  def get_theme_selector():
145
  """获取全局主题选择器实例"""
146
  global _theme_selector
@@ -148,6 +156,7 @@ def get_theme_selector():
148
  _theme_selector = ThemeSelector()
149
  return _theme_selector
150
 
 
151
  def render_theme_selector():
152
  """便捷函数:渲染主题选择器"""
153
  return get_theme_selector().render_theme_selector()
 
4
  import os
5
  import time
6
 
7
+
8
  class ThemeSelector:
9
+ def __init__(
10
+ self, themes_dir=".streamlit/themes", config_path=".streamlit/config.toml"
11
+ ):
12
  self.themes_dir = Path(themes_dir)
13
  self.config_path = Path(config_path)
14
  self.themes = {}
15
  self.load_themes()
16
+
17
  def load_themes(self):
18
  """加载所有主题文件"""
19
  self.themes = {}
20
  if not self.themes_dir.exists():
21
  return
22
+
23
  for theme_file in self.themes_dir.glob("*.toml"):
24
  try:
25
  theme_data = toml.load(theme_file)
26
+
27
  # 从根级别获取theme_name和theme_poem
28
  theme_name = theme_data.get("theme_name", theme_file.stem)
29
  theme_poem = theme_data.get("theme_poem", "")
30
  theme_config = theme_data.get("theme", {})
31
+
32
  self.themes[theme_name] = {
33
  "file": theme_file,
34
  "name": theme_name,
35
  "poem": theme_poem,
36
+ "config": theme_config,
37
  }
38
  except Exception as e:
39
  st.warning(f"读取主题文件 {theme_file} 失败: {e}")
40
+
41
  def get_current_theme(self):
42
  """获取当前主题名称"""
43
  if not self.config_path.exists():
44
  return None
45
+
46
  try:
47
  # config = toml.load(self.config_path)
48
  # # 从根级别读取theme_name
49
  # current_theme_name = config.get("theme") or {}
50
  # current_theme_name = current_theme_name.get("theme_name")
51
  # return current_theme_name
52
+ theme_toml = self.config_path.parent / "theme.toml"
53
  theme = toml.load(theme_toml)
54
  return theme.get("theme_name")
55
 
56
  except Exception:
57
  return None
58
+
59
  def apply_theme(self, theme_name):
60
  """应用选定的主题"""
61
  if theme_name not in self.themes:
62
  st.error(f"主题 '{theme_name}' 不存在")
63
  return False
64
+
65
  try:
66
  # 确保配置目录存在
67
  self.config_path.parent.mkdir(parents=True, exist_ok=True)
68
+
69
  # 读取现有配置或创建新配置
70
  config = {}
71
  if self.config_path.exists():
 
73
  config = toml.load(self.config_path)
74
  except Exception:
75
  config = {}
76
+
77
  # 添加根级别的theme_name和theme_poem
78
  # config["theme_name"] = self.themes[theme_name]["name"]
79
  # config["theme_poem"] = self.themes[theme_name]["poem"]
80
+
81
  # 更新主题配置
82
  theme_config = self.themes[theme_name]["config"].copy()
83
  # theme_config["theme_name"] = self.themes[theme_name]["name"]
84
  # theme_config["theme_poem"] = self.themes[theme_name]["poem"]
85
  config["theme"] |= theme_config
86
+
87
  # 写入配置文件
88
  with open(self.config_path, "w", encoding="utf-8") as f:
89
  toml.dump(config, f)
90
 
91
+ theme_toml = self.config_path.parent / "theme.toml"
92
  with open(theme_toml, "w", encoding="utf-8") as f:
93
+ toml.dump(
94
+ dict(
95
+ theme_name=self.themes[theme_name]["name"],
96
+ theme_poem=self.themes[theme_name]["poem"],
97
+ ),
98
+ f,
99
+ )
100
+
101
  return True
102
+
103
  except Exception as e:
104
  st.error(f"应用主题失败: {e}")
105
  return False
106
+
107
  def render_theme_selector(self):
108
  """渲染主题选择器UI"""
109
  if not self.themes:
110
  st.warning("未找到可用主题")
111
  return
112
+
113
  theme_names = list(self.themes.keys())
114
  current_theme = self.get_current_theme()
115
+
116
  # 确定当前选中的索引
117
  current_index = 0
118
  if current_theme and current_theme in theme_names:
119
  current_index = theme_names.index(current_theme)
120
+
121
  # 主题选择下拉菜单
122
  selected_theme = st.selectbox(
123
  "选择主题",
 
125
  index=current_index,
126
  format_func=lambda x: self.themes[x]["name"],
127
  key="theme_selector_widget",
128
+ label_visibility="collapsed",
129
  )
130
+
131
  # 如果选择了新主题
132
  if selected_theme != current_theme:
133
  if self.apply_theme(selected_theme):
 
137
  st.toast(f"✨ {theme_poem}", icon="🎨")
138
  else:
139
  st.toast(f"已切换到主题: {selected_theme}", icon="🎨")
140
+
141
  time.sleep(3)
142
  # 延迟重新运行以应用主题
143
  st.rerun()
144
+
145
  return selected_theme
146
 
147
+
148
  # 全局主题选择器实例
149
  _theme_selector = None
150
 
151
+
152
  def get_theme_selector():
153
  """获取全局主题选择器实例"""
154
  global _theme_selector
 
156
  _theme_selector = ThemeSelector()
157
  return _theme_selector
158
 
159
+
160
  def render_theme_selector():
161
  """便捷函数:渲染主题选择器"""
162
  return get_theme_selector().render_theme_selector()
src/utils.py CHANGED
@@ -13,4 +13,4 @@ DATA_ROOT_PATH = Path("./data").resolve()
13
 
14
  class AppMode(Enum):
15
  VIEWING = auto()
16
- # Potentially other modes like COMPARISON, EDITING etc.
 
13
 
14
  class AppMode(Enum):
15
  VIEWING = auto()
16
+ # Potentially other modes like COMPARISON, EDITING etc.