Kuangdai commited on
Commit
09451e0
·
1 Parent(s): 1ce16f7

Add Streamlit dataset viewers

Browse files
.gitattributes CHANGED
@@ -4,3 +4,6 @@ datasets/esdac/** filter=lfs diff=lfs merge=lfs -text
4
  datasets/fusion/** filter=lfs diff=lfs merge=lfs -text
5
  src/fuse_esdac/large_inputs/** filter=lfs diff=lfs merge=lfs -text
6
  resources/*.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
4
  datasets/fusion/** filter=lfs diff=lfs merge=lfs -text
5
  src/fuse_esdac/large_inputs/** filter=lfs diff=lfs merge=lfs -text
6
  resources/*.png filter=lfs diff=lfs merge=lfs -text
7
+ resources/*.jpg filter=lfs diff=lfs merge=lfs -text
8
+ resources/*.jpeg filter=lfs diff=lfs merge=lfs -text
9
+ resources/*.webp filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -67,7 +67,7 @@ For users who only need the final fused dataset (16 GB):
67
  ```bash
68
  GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/earthroverprogram/lucas-mega
69
  cd lucas-mega
70
- git lfs pull --include="datasets/fusion" --exclude="datasets/esdac,src/fuse_esdac/large_inputs"
71
  ```
72
 
73
  The fusion dataset is the released LUCAS-MEGA dataset. It integrates standardized source datasets into a unified
@@ -88,6 +88,14 @@ to dense asset files.
88
  | `gadm_tree_europe.pkl` | GADM administrative hierarchy attached to samples for geographic reasoning and regional lookup. |
89
  | `assets/` | Dense feature data, including hydraulic conductivity curves, water retention curves, particle size distribution spectra, and site images where available. |
90
 
 
 
 
 
 
 
 
 
91
  ---
92
 
93
  ## Download the Standardized Representation
@@ -95,7 +103,7 @@ to dense asset files.
95
  For users interested in the intermediate standardized data (70 GB):
96
 
97
  ```bash
98
- git lfs pull --include="datasets/esdac" --exclude="datasets/fusion,src/fuse_esdac/large_inputs"
99
  ```
100
 
101
  The standardized representation contains cleaned and normalized individual source datasets. These datasets have been
@@ -110,13 +118,13 @@ It includes:
110
  This layer is useful for inspecting source datasets, understanding preprocessing, developing new fusion rules, debugging
111
  the pipeline, or extending LUCAS-MEGA.
112
 
113
- Use `viewer.py` to visualize the standardized data and metadata:
114
 
115
  ```bash
116
- python viewer.py
117
  ```
118
 
119
- <img src="resources/preview.png" alt="preview" style="width:60%;">
120
 
121
  ---
122
 
 
67
  ```bash
68
  GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/earthroverprogram/lucas-mega
69
  cd lucas-mega
70
+ git lfs pull --include="datasets/fusion,resources" --exclude="datasets/esdac,src/fuse_esdac/large_inputs"
71
  ```
72
 
73
  The fusion dataset is the released LUCAS-MEGA dataset. It integrates standardized source datasets into a unified
 
88
  | `gadm_tree_europe.pkl` | GADM administrative hierarchy attached to samples for geographic reasoning and regional lookup. |
89
  | `assets/` | Dense feature data, including hydraulic conductivity curves, water retention curves, particle size distribution spectra, and site images where available. |
90
 
91
+ Use `viewer_fusion.py` to explore fused properties on an interactive sample map:
92
+
93
+ ```bash
94
+ streamlit run viewer_fusion.py
95
+ ```
96
+
97
+ <img src="resources/viewer_fusion.png" alt="Fusion viewer" style="width:70%;">
98
+
99
  ---
100
 
101
  ## Download the Standardized Representation
 
103
  For users interested in the intermediate standardized data (70 GB):
104
 
105
  ```bash
106
+ git lfs pull --include="datasets/esdac,resources" --exclude="datasets/fusion,src/fuse_esdac/large_inputs"
107
  ```
108
 
109
  The standardized representation contains cleaned and normalized individual source datasets. These datasets have been
 
118
  This layer is useful for inspecting source datasets, understanding preprocessing, developing new fusion rules, debugging
119
  the pipeline, or extending LUCAS-MEGA.
120
 
121
+ Use `viewer_standardization.py` to inspect standardized source datasets and metadata:
122
 
123
  ```bash
124
+ streamlit run viewer_standardization.py
125
  ```
126
 
127
+ <img src="resources/viewer_standardization.png" alt="Standardization viewer" style="width:70%;">
128
 
129
  ---
130
 
requirements.txt CHANGED
@@ -2,17 +2,16 @@ pandas~=2.3.3
2
  rasterio~=1.4.3
3
  numpy~=2.3.4
4
  pillow~=12.0.0
5
- openpyxl~=3.1.5
6
  matplotlib~=3.10.7
7
  geopandas~=1.1.1
8
  dbfread~=2.0.7
9
  packaging~=25.0
10
  gdal~=3.11.4
11
-
12
  pyproj~=3.7.2
13
  tqdm~=4.67.1
14
  shapely~=2.1.2
15
  requests~=2.32.5
16
  beautifulsoup4~=4.14.2
17
- duckdb~=1.4.1
18
- openai~=2.6.1
 
 
2
  rasterio~=1.4.3
3
  numpy~=2.3.4
4
  pillow~=12.0.0
 
5
  matplotlib~=3.10.7
6
  geopandas~=1.1.1
7
  dbfread~=2.0.7
8
  packaging~=25.0
9
  gdal~=3.11.4
 
10
  pyproj~=3.7.2
11
  tqdm~=4.67.1
12
  shapely~=2.1.2
13
  requests~=2.32.5
14
  beautifulsoup4~=4.14.2
15
+ openai~=2.6.1
16
+ pydeck~=0.9.2
17
+ streamlit~=1.57.0
resources/{viewer.png → erp.jpeg} RENAMED
File without changes
resources/{preview.png → viewer_fusion.png} RENAMED
File without changes
resources/viewer_standardization.png ADDED

Git LFS Details

  • SHA256: 47d4531300f5cde0282778cdddd71f20c871a408a15d5de70aa9c5594c69963e
  • Pointer size: 132 Bytes
  • Size of remote file: 3.12 MB
viewer.py DELETED
@@ -1,309 +0,0 @@
1
- import json
2
- import os
3
- import tkinter as tk
4
- from tkinter import ttk
5
-
6
- import pandas as pd
7
- import rasterio
8
- from PIL import Image, ImageTk
9
-
10
-
11
- class DatasetTreeViewer(tk.Tk):
12
- def __init__(self, host_name):
13
- super().__init__()
14
- self.title("Dataset Viewer — © Earth Rover Program, 2025")
15
- self.geometry("1200x700")
16
- self.base_path = os.path.join("datasets", host_name)
17
- self.datasets = self.get_datasets(host_name)
18
-
19
- # === Layout ===
20
- paned = tk.PanedWindow(self, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=6)
21
- paned.pack(fill=tk.BOTH, expand=True)
22
-
23
- left_frame = tk.Frame(paned)
24
- right_frame = tk.Frame(paned)
25
- paned.add(left_frame)
26
- paned.paneconfigure(left_frame, minsize=300)
27
- paned.add(right_frame)
28
-
29
- bottom_frame = tk.Frame(self)
30
- bottom_frame.pack(fill=tk.X)
31
-
32
- # === Checkbox grid above Treeview (2x2 layout)
33
- checkbox_outer_frame = tk.Frame(left_frame)
34
- checkbox_outer_frame.pack(pady=4)
35
-
36
- self.status_filters = {}
37
- default_checked = {"PROCESSED"}
38
- status_options = ["UNEXAMINED", "SKIPPED", "REQUESTED", "DOWNLOADED", "PROCESSED"]
39
-
40
- for idx, status in enumerate(status_options):
41
- row = idx // 2
42
- col = idx % 2
43
- var = tk.BooleanVar(value=status in default_checked)
44
- cb = tk.Checkbutton(
45
- checkbox_outer_frame,
46
- text=status.capitalize(),
47
- variable=var,
48
- command=self.build_tree,
49
- anchor="w",
50
- width=15, # fixed width for alignment
51
- padx=0
52
- )
53
- cb.grid(row=row, column=col, sticky="w")
54
- self.status_filters[status] = var
55
-
56
- # === Treeview
57
- self.tree = ttk.Treeview(left_frame)
58
- self.tree.heading("#0", text=f"Datasets from {host_name.upper()}")
59
- self.tree.pack(fill=tk.BOTH, expand=True)
60
- self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)
61
-
62
- # === Viewer frame
63
- self.viewer_frame = tk.Frame(right_frame)
64
- self.viewer_frame.pack(fill=tk.BOTH, expand=True)
65
-
66
- # === Bottom info
67
- self.info_text = tk.Text(bottom_frame, height=10, wrap=tk.WORD)
68
- self.info_text.pack(fill=tk.X)
69
-
70
- self.build_tree()
71
-
72
- def get_datasets(self, host_name):
73
- status_path = os.path.join("src", host_name, "status.json")
74
- datasets = {}
75
-
76
- try:
77
- with open(status_path, "r") as f:
78
- items = json.load(f)
79
-
80
- for item in items:
81
- name = item["name"]
82
- dataset_path = os.path.join(self.base_path, name)
83
- processed_path = os.path.join(dataset_path, "processed")
84
-
85
- if not os.path.exists(processed_path):
86
- continue
87
-
88
- file_list = []
89
- for root, _, files in os.walk(processed_path):
90
- for f in files:
91
- if f.endswith((".csv", ".png", ".tif", ".tiff", ".json", ".txt")):
92
- full_path = os.path.join(root, f)
93
- rel_path = os.path.relpath(full_path, processed_path)
94
- file_list.append(rel_path)
95
-
96
- datasets[name] = {
97
- "name": name,
98
- "title": item.get("title", ""),
99
- "abstract": item.get("abstract") or "",
100
- "request_needed": item.get("request_needed", False),
101
- "status": item.get("status"),
102
- "notes": item.get("notes"),
103
- "screened_by": item.get("screened_by"),
104
- "requested_downloaded_by": item.get("requested_downloaded_by"),
105
- "processed_by": item.get("processed_by"),
106
- "files": sorted(file_list),
107
- "path": dataset_path
108
- }
109
- except Exception as e:
110
- print(f"Error reading {status_path}: {e}")
111
-
112
- return datasets
113
-
114
- def build_tree(self):
115
- self.tree.delete(*self.tree.get_children())
116
- selected_statuses = {k for k, v in self.status_filters.items() if v.get()}
117
-
118
- for dataset_name, data in self.datasets.items():
119
- if data.get("status") not in selected_statuses:
120
- continue
121
-
122
- dataset_node = self.tree.insert("", "end", text=dataset_name, open=False)
123
- node_map = {"": dataset_node}
124
-
125
- for rel_path in data["files"]:
126
- parts = rel_path.split(os.sep)
127
- current = dataset_node
128
- for i, part in enumerate(parts):
129
- sub_path = os.path.join(*parts[:i + 1])
130
- if sub_path not in node_map:
131
- node_map[sub_path] = self.tree.insert(current, "end", text=part, open=False)
132
- current = node_map[sub_path]
133
-
134
- def on_tree_select(self, event):
135
- selected_id = self.tree.focus()
136
- item = self.tree.item(selected_id)
137
- text = item["text"]
138
- parent_id = self.tree.parent(selected_id)
139
-
140
- if parent_id == "":
141
- dataset_name = text
142
- data = self.datasets[dataset_name]
143
- self.info_text.delete(1.0, tk.END)
144
- lines = [
145
- f"Name: {data['name']}",
146
- f"Title: {data['title']}",
147
- ]
148
- if data.get("abstract"):
149
- lines.append(f"Abstract: {data['abstract']}")
150
- lines.append(f"Request needed: {data['request_needed']}")
151
- lines.append(f"Status: {data['status']}")
152
- if data['notes'] is not None:
153
- lines.append(f"Notes: {data['notes']}")
154
- self.info_text.insert(tk.END, "\n".join(lines))
155
- self.clear_viewer()
156
- return
157
-
158
- # Traverse upward to get dataset name
159
- full_path_parts = []
160
- current_id = selected_id
161
- while True:
162
- parent = self.tree.parent(current_id)
163
- if parent == "":
164
- dataset_name = self.tree.item(current_id)["text"]
165
- break
166
- full_path_parts.insert(0, self.tree.item(current_id)["text"])
167
- current_id = parent
168
-
169
- rel_file_path = os.path.join(*full_path_parts)
170
- full_file_path = os.path.join(self.datasets[dataset_name]["path"], "processed", rel_file_path)
171
-
172
- self.info_text.delete(1.0, tk.END)
173
-
174
- if os.path.isdir(full_file_path):
175
- self.info_text.insert(tk.END, f"Directory: {rel_file_path} from dataset: {dataset_name}\n")
176
- self.clear_viewer()
177
- else:
178
- self.info_text.insert(tk.END, f"File: {rel_file_path} from dataset: {dataset_name}\n")
179
- self.load_file(full_file_path)
180
-
181
- def clear_viewer(self):
182
- for widget in self.viewer_frame.winfo_children():
183
- widget.destroy()
184
-
185
- def load_file(self, path):
186
- self.clear_viewer()
187
-
188
- if path.endswith(".csv"):
189
- try:
190
- df = pd.read_csv(path, low_memory=False)
191
- self.show_csv(df)
192
- self.info_text.insert(tk.END, f"Number of entries: {len(df)}\n")
193
- except Exception as e:
194
- self.info_text.insert(tk.END, f"Error reading CSV:\n{e}")
195
-
196
- elif path.endswith(".png"):
197
- try:
198
- self.viewer_frame.update_idletasks()
199
- frame_w = self.viewer_frame.winfo_width()
200
- frame_h = self.viewer_frame.winfo_height()
201
-
202
- img = Image.open(path)
203
- img_w, img_h = img.size
204
-
205
- ratio_w = frame_w / img_w
206
- ratio_h = frame_h / img_h
207
- scale = min(ratio_w, ratio_h)
208
-
209
- new_w = int(img_w * scale)
210
- new_h = int(img_h * scale)
211
- resized = img.resize((new_w, new_h), Image.LANCZOS)
212
- photo = ImageTk.PhotoImage(resized)
213
-
214
- label = tk.Label(self.viewer_frame, image=photo)
215
- label.image = photo
216
- label.pack(expand=True)
217
- self.info_text.insert(tk.END, f"Shape: {img_h}x{img_w}\n")
218
- except Exception as e:
219
- self.info_text.insert(tk.END, f"Error displaying PNG:\n{e}")
220
-
221
- elif path.endswith(".json"):
222
- try:
223
- with open(path, "r") as f:
224
- content = json.load(f)
225
- text_widget = tk.Text(self.viewer_frame, wrap=tk.NONE)
226
- text_widget.insert(tk.END, json.dumps(content, indent=2))
227
- text_widget.configure(state="disabled")
228
- text_widget.pack(fill=tk.BOTH, expand=True)
229
- except Exception as e:
230
- self.info_text.insert(tk.END, f"Error reading JSON:\n{e}")
231
-
232
- elif path.endswith(".tif"):
233
- try:
234
- with rasterio.open(path) as src:
235
- shape = (src.height, src.width)
236
- dtype = src.dtypes[0]
237
- nodata = src.nodata
238
- crs = src.crs
239
- transform = src.transform
240
-
241
- summary = [
242
- f"Shape: {shape}",
243
- f"Datatype: {dtype}",
244
- f"NoData value: {nodata}",
245
- f"CRS: {crs}",
246
- f"Transform:\n{transform}",
247
- ]
248
-
249
- text_widget = tk.Text(self.viewer_frame, wrap=tk.NONE)
250
- text_widget.insert(tk.END, "\n".join(summary))
251
- text_widget.configure(state="disabled")
252
- text_widget.pack(fill=tk.BOTH, expand=True)
253
-
254
- except Exception as e:
255
- self.info_text.insert(tk.END, f"Error reading TIF:\n{e}")
256
-
257
- else:
258
- try:
259
- with open(path, "r", encoding="utf-8") as f:
260
- content = f.read()
261
- text_widget = tk.Text(self.viewer_frame, wrap=tk.NONE)
262
- text_widget.insert(tk.END, content)
263
- text_widget.configure(state="disabled")
264
- text_widget.pack(fill=tk.BOTH, expand=True)
265
- except Exception as e:
266
- self.info_text.insert(tk.END, f"Unsupported format for quick view: {os.path.basename(path)}\n")
267
-
268
- def show_csv(self, df):
269
- df = df.head(100)
270
- table = ttk.Treeview(self.viewer_frame, show="headings")
271
- table.pack(fill=tk.BOTH, expand=True)
272
-
273
- scroll_y = tk.Scrollbar(self.viewer_frame, orient="vertical", command=table.yview)
274
- scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
275
-
276
- scroll_x = tk.Scrollbar(self.viewer_frame, orient="horizontal", command=table.xview)
277
- scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
278
-
279
- table.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
280
- table["columns"] = list(df.columns)
281
-
282
- for col in df.columns:
283
- col_values = df[col].astype(str).head(20).tolist()
284
- max_len = max([len(col)] + [len(val) for val in col_values])
285
- width_px = max(80, min(400, max_len * 7))
286
- table.heading(col, text=col)
287
- table.column(col, width=width_px, anchor="w", stretch=False)
288
-
289
- for _, row in df.iterrows():
290
- values = [self.format_value(val) for val in row]
291
- table.insert("", "end", values=values)
292
-
293
- @staticmethod
294
- def format_value(val):
295
- if isinstance(val, float):
296
- return f"{val:.6g}"
297
- return str(val)
298
-
299
-
300
- # === Run Viewer ===
301
- if __name__ == "__main__":
302
- host_name_ = "esdac"
303
- app = DatasetTreeViewer(host_name_)
304
- try:
305
- icon = tk.PhotoImage(file="resources/viewer.png")
306
- app.iconphoto(True, icon)
307
- except Exception as ex:
308
- print("Failed to load icon:", ex)
309
- app.mainloop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
viewer_fusion.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import colorsys
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ try:
11
+ import pydeck as pdk
12
+ import streamlit as st
13
+ except ImportError as exc:
14
+ raise SystemExit(
15
+ "viewer_fusion.py requires streamlit and pydeck.\n"
16
+ "Install them with: pip install streamlit pydeck\n"
17
+ "Then run: streamlit run viewer_fusion.py"
18
+ ) from exc
19
+
20
+
21
+ BASE_DIR = Path(__file__).resolve().parent
22
+ FUSION_DIR = BASE_DIR / "datasets" / "fusion"
23
+ ICON_PATH = BASE_DIR / "resources" / "erp.jpeg"
24
+ TABLE_PATH = FUSION_DIR / "data_table.csv"
25
+ META_NAMES_PATH = FUSION_DIR / "meta_column_names.json"
26
+ META_COMPLETE_PATH = FUSION_DIR / "meta_column_complete.json"
27
+ DEFAULT_PROPERTY = "texture:USDA_class"
28
+
29
+ BASE_COLUMNS = [
30
+ "id",
31
+ "LAT_LONG",
32
+ "GADM_IDS",
33
+ "GADM_NAMES",
34
+ "COUNTRY_CODE",
35
+ "SAMPLE_DATE",
36
+ "SAMPLE_DEPTH_RANGE_CM",
37
+ "SAMPLE_SOURCE_DATASET",
38
+ ]
39
+
40
+
41
+ def split_property_name(name):
42
+ if ":" not in name:
43
+ return "other", name
44
+ theme, prop = name.split(":", 1)
45
+ return theme, prop
46
+
47
+
48
+ @st.cache_data(show_spinner=False)
49
+ def load_metadata():
50
+ with open(META_NAMES_PATH, encoding="utf-8") as f:
51
+ names = json.load(f)["column_names"]
52
+
53
+ with open(META_COMPLETE_PATH, encoding="utf-8") as f:
54
+ meta = json.load(f)
55
+
56
+ groups = {}
57
+ for name in names:
58
+ theme, prop = split_property_name(name)
59
+ groups.setdefault(theme, []).append((prop, name))
60
+
61
+ for theme in groups:
62
+ groups[theme].sort(key=lambda item: item[0].lower())
63
+
64
+ return names, meta, dict(sorted(groups.items()))
65
+
66
+
67
+ def parse_lat_long(value):
68
+ if pd.isna(value):
69
+ return np.nan, np.nan
70
+ if isinstance(value, str):
71
+ try:
72
+ parsed = ast.literal_eval(value)
73
+ except (SyntaxError, ValueError):
74
+ return np.nan, np.nan
75
+ else:
76
+ parsed = value
77
+ if not isinstance(parsed, (list, tuple)) or len(parsed) < 2:
78
+ return np.nan, np.nan
79
+ return float(parsed[0]), float(parsed[1])
80
+
81
+
82
+ def vector_mean(value):
83
+ if pd.isna(value) or value == "":
84
+ return np.nan
85
+ if isinstance(value, str):
86
+ try:
87
+ value = ast.literal_eval(value)
88
+ except (SyntaxError, ValueError):
89
+ return np.nan
90
+ if not isinstance(value, (list, tuple)):
91
+ return np.nan
92
+ nums = pd.to_numeric(pd.Series(value), errors="coerce").dropna()
93
+ return float(nums.mean()) if len(nums) else np.nan
94
+
95
+
96
+ @st.cache_data(show_spinner=False)
97
+ def load_property_frame(property_name):
98
+ columns = ["id", "LAT_LONG", "GADM_NAMES", "COUNTRY_CODE", property_name]
99
+ df = pd.read_csv(
100
+ TABLE_PATH,
101
+ usecols=columns,
102
+ low_memory=False,
103
+ keep_default_na=True,
104
+ )
105
+
106
+ lat_lon = df["LAT_LONG"].map(parse_lat_long)
107
+ df["lat"] = [item[0] for item in lat_lon]
108
+ df["lon"] = [item[1] for item in lat_lon]
109
+ df = df.dropna(subset=["lat", "lon"])
110
+ return df
111
+
112
+
113
+ COLOR_STOPS = [
114
+ (68, 1, 84),
115
+ (59, 82, 139),
116
+ (33, 145, 140),
117
+ (94, 201, 98),
118
+ (253, 231, 37),
119
+ ]
120
+
121
+
122
+ def interpolate_color(value, vmin, vmax):
123
+ if pd.isna(value):
124
+ return [150, 150, 150, 55]
125
+ if pd.isna(vmin) or pd.isna(vmax) or vmax <= vmin:
126
+ t = 0.5
127
+ else:
128
+ t = float((value - vmin) / (vmax - vmin))
129
+ t = max(0.0, min(1.0, t))
130
+
131
+ pos = t * (len(COLOR_STOPS) - 1)
132
+ left = int(np.floor(pos))
133
+ right = min(left + 1, len(COLOR_STOPS) - 1)
134
+ frac = pos - left
135
+ rgb = [
136
+ int(COLOR_STOPS[left][i] + frac * (COLOR_STOPS[right][i] - COLOR_STOPS[left][i]))
137
+ for i in range(3)
138
+ ]
139
+ return rgb + [180]
140
+
141
+
142
+ def category_color(value):
143
+ if pd.isna(value) or value == "":
144
+ return [150, 150, 150, 55]
145
+ digest = hashlib.md5(str(value).encode("utf-8")).hexdigest()
146
+ hue = int(digest[:8], 16) / 0xFFFFFFFF
147
+ red, green, blue = colorsys.hsv_to_rgb(hue, 0.62, 0.92)
148
+ return [int(red * 255), int(green * 255), int(blue * 255), 185]
149
+
150
+
151
+ def get_visual_mode(property_meta):
152
+ datatype = property_meta.get("datatype")
153
+ is_array = property_meta.get("is_array_valued", False)
154
+ if is_array:
155
+ return "numeric vector mean"
156
+ if datatype in {"int", "float"}:
157
+ return "numeric scalar"
158
+ return "categorical"
159
+
160
+
161
+ def calculate_color_values(df, property_name, property_meta):
162
+ raw = df[property_name]
163
+ mode = get_visual_mode(property_meta)
164
+
165
+ if mode == "numeric vector mean":
166
+ values = raw.map(vector_mean)
167
+ elif mode == "numeric scalar":
168
+ values = pd.to_numeric(raw, errors="coerce")
169
+ else:
170
+ values = raw.fillna("").astype(str)
171
+ return raw, values, mode
172
+
173
+
174
+ def prepare_visual_values(df, property_name, property_meta, color_limits=None):
175
+ raw, values, mode = calculate_color_values(df, property_name, property_meta)
176
+
177
+ out = df.copy()
178
+ out["display_value"] = raw.fillna("").astype(str)
179
+
180
+ if mode.startswith("numeric"):
181
+ non_null = values.dropna()
182
+ if len(non_null):
183
+ default_vmin = float(non_null.quantile(0.02))
184
+ default_vmax = float(non_null.quantile(0.98))
185
+ else:
186
+ default_vmin = default_vmax = np.nan
187
+ if color_limits:
188
+ vmin, vmax = color_limits
189
+ else:
190
+ vmin, vmax = default_vmin, default_vmax
191
+ out["color_value"] = values
192
+ out["color"] = [interpolate_color(v, vmin, vmax) for v in values]
193
+ legend = {
194
+ "mode": mode,
195
+ "valid": int(values.notna().sum()),
196
+ "missing": int(values.isna().sum()),
197
+ "min": float(non_null.min()) if len(non_null) else None,
198
+ "max": float(non_null.max()) if len(non_null) else None,
199
+ "p02": default_vmin if len(non_null) else None,
200
+ "p98": default_vmax if len(non_null) else None,
201
+ "vmin": vmin if len(non_null) else None,
202
+ "vmax": vmax if len(non_null) else None,
203
+ }
204
+ else:
205
+ categories = values.replace("", np.nan)
206
+ unique_count = int(categories.nunique(dropna=True))
207
+ out["color_value"] = values
208
+ out["color"] = [category_color(v) for v in values]
209
+ legend = {
210
+ "mode": mode,
211
+ "valid": int(categories.notna().sum()),
212
+ "missing": int(categories.isna().sum()),
213
+ "unique": unique_count,
214
+ "top_values": categories.value_counts(dropna=True).head(12).to_dict(),
215
+ }
216
+
217
+ out["property"] = property_name
218
+ return out, legend
219
+
220
+
221
+ def render_sidebar(groups, meta):
222
+ st.sidebar.title("Fusion Viewer")
223
+
224
+ search = st.sidebar.text_input(
225
+ "Search property",
226
+ "",
227
+ placeholder="type part of theme:name (unit)",
228
+ )
229
+ if search.strip():
230
+ needle = search.strip().lower()
231
+ matches = [
232
+ name
233
+ for theme_items in groups.values()
234
+ for _, name in theme_items
235
+ if needle in name.lower()
236
+ ]
237
+ if not matches:
238
+ st.sidebar.warning("No matching properties.")
239
+ return None
240
+ st.sidebar.caption(f"{len(matches)} matching properties")
241
+ property_name = st.sidebar.radio(
242
+ "Matching properties",
243
+ matches[:80],
244
+ format_func=lambda x: x,
245
+ label_visibility="collapsed",
246
+ )
247
+ if len(matches) > 80:
248
+ st.sidebar.caption("Showing first 80 matches. Type more to narrow.")
249
+ else:
250
+ themes = list(groups.keys())
251
+ default_theme, _ = split_property_name(DEFAULT_PROPERTY)
252
+ theme_index = themes.index(default_theme) if default_theme in themes else 0
253
+ theme = st.sidebar.selectbox("Theme", themes, index=theme_index)
254
+ options = [name for _, name in groups[theme]]
255
+ property_index = options.index(DEFAULT_PROPERTY) if DEFAULT_PROPERTY in options else 0
256
+ property_name = st.sidebar.selectbox(
257
+ "Property",
258
+ options,
259
+ index=property_index,
260
+ format_func=lambda x: split_property_name(x)[1],
261
+ )
262
+
263
+ with st.sidebar.expander("Property metadata", expanded=False):
264
+ item = meta.get(property_name, {})
265
+ st.write("datatype:", item.get("datatype"))
266
+ st.write("array:", item.get("is_array_valued"))
267
+ st.write("null_fraction:", item.get("null_fraction"))
268
+ st.write("source_datasets:", item.get("source_datasets"))
269
+ description = item.get("description")
270
+ if description:
271
+ st.caption(description)
272
+
273
+ return property_name
274
+
275
+
276
+ def render_color_controls(property_name, property_meta, df):
277
+ raw, values, mode = calculate_color_values(df, property_name, property_meta)
278
+ if not mode.startswith("numeric"):
279
+ return None
280
+
281
+ non_null = values.dropna()
282
+ if not len(non_null):
283
+ st.sidebar.warning("No numeric values available for this property.")
284
+ return None
285
+
286
+ data_min = float(non_null.min())
287
+ data_max = float(non_null.max())
288
+ default_vmin = float(non_null.quantile(0.02))
289
+ default_vmax = float(non_null.quantile(0.98))
290
+
291
+ st.sidebar.subheader("Color scale")
292
+ use_full_range = st.sidebar.checkbox("Use full data range", value=False)
293
+ if use_full_range:
294
+ return data_min, data_max
295
+
296
+ vmin = st.sidebar.number_input(
297
+ "vmin",
298
+ value=default_vmin,
299
+ min_value=data_min,
300
+ max_value=data_max,
301
+ format="%.6g",
302
+ )
303
+ vmax = st.sidebar.number_input(
304
+ "vmax",
305
+ value=default_vmax,
306
+ min_value=data_min,
307
+ max_value=data_max,
308
+ format="%.6g",
309
+ )
310
+ if vmax <= vmin:
311
+ st.sidebar.warning("vmax must be larger than vmin; using percentile defaults.")
312
+ return default_vmin, default_vmax
313
+ return float(vmin), float(vmax)
314
+
315
+
316
+ def render_legend(legend):
317
+ cols = st.columns(4)
318
+ cols[0].metric("Mode", legend["mode"])
319
+ cols[1].metric("Valid", f"{legend['valid']:,}")
320
+ cols[2].metric("Missing", f"{legend['missing']:,}")
321
+
322
+ if legend["mode"].startswith("numeric"):
323
+ cols[3].metric("Range", "2%-98%")
324
+ st.caption(
325
+ f"Actual min/max: {legend['min']} / {legend['max']} | "
326
+ f"color clamp: {legend['p02']} / {legend['p98']}"
327
+ )
328
+ else:
329
+ cols[3].metric("Unique", f"{legend['unique']:,}")
330
+ if legend["top_values"]:
331
+ st.caption("Top categories: " + "; ".join(
332
+ f"{k}: {v}" for k, v in legend["top_values"].items()
333
+ ))
334
+
335
+
336
+ def render_colorbar(legend):
337
+ if legend["mode"].startswith("numeric"):
338
+ gradient = ", ".join(f"rgb({r}, {g}, {b})" for r, g, b in COLOR_STOPS)
339
+ st.markdown(
340
+ f"""
341
+ <div style="margin-top: 0.75rem;">
342
+ <div style="height: 14px; border-radius: 7px;
343
+ background: linear-gradient(90deg, {gradient});"></div>
344
+ <div style="display: flex; justify-content: space-between;
345
+ font-size: 0.82rem; color: #666; margin-top: 0.2rem;">
346
+ <span>vmin: {legend["vmin"]}</span>
347
+ <span>vmax: {legend["vmax"]}</span>
348
+ </div>
349
+ </div>
350
+ """,
351
+ unsafe_allow_html=True,
352
+ )
353
+ else:
354
+ top_values = legend.get("top_values", {})
355
+ if not top_values:
356
+ return
357
+ swatches = []
358
+ for value in top_values:
359
+ r, g, b, _ = category_color(value)
360
+ swatches.append(
361
+ "<span style='display:inline-flex; align-items:center; gap:0.25rem; "
362
+ "margin:0 0.65rem 0.35rem 0;'>"
363
+ f"<span style='width:0.75rem; height:0.75rem; border-radius:50%; "
364
+ f"background:rgb({r},{g},{b}); display:inline-block;'></span>"
365
+ f"<span>{value}</span></span>"
366
+ )
367
+ st.markdown("".join(swatches), unsafe_allow_html=True)
368
+
369
+
370
+ def render_map(df):
371
+ midpoint = [float(df["lon"].median()), float(df["lat"].median())]
372
+ df = df.copy()
373
+ df["tooltip_location"] = df["GADM_NAMES"].fillna("").astype(str).str.replace(
374
+ r"^[\[\]'\" ]+|[\[\]'\" ]+$",
375
+ "",
376
+ regex=True,
377
+ )
378
+ df["tooltip_text"] = (
379
+ df["id"].fillna("").astype(str)
380
+ + "\n"
381
+ + df["COUNTRY_CODE"].fillna("").astype(str)
382
+ + " · "
383
+ + df["tooltip_location"].fillna("").astype(str)
384
+ + "\n"
385
+ + df["property"].fillna("").astype(str)
386
+ + "\n"
387
+ + df["display_value"].fillna("").astype(str)
388
+ )
389
+ map_data = df[
390
+ ["id", "lon", "lat", "color", "tooltip_text"]
391
+ ].to_dict(orient="records")
392
+
393
+ layer = pdk.Layer(
394
+ "ScatterplotLayer",
395
+ data=map_data,
396
+ get_position="[lon, lat]",
397
+ get_fill_color="color",
398
+ get_radius=1800,
399
+ radius_min_pixels=2,
400
+ radius_max_pixels=12,
401
+ pickable=True,
402
+ auto_highlight=True,
403
+ )
404
+
405
+ view_state = pdk.ViewState(
406
+ longitude=midpoint[0],
407
+ latitude=midpoint[1],
408
+ zoom=3.2,
409
+ min_zoom=2,
410
+ max_zoom=12,
411
+ )
412
+
413
+ tooltip = {"text": "{tooltip_text}"}
414
+
415
+ deck = pdk.Deck(
416
+ layers=[layer],
417
+ initial_view_state=view_state,
418
+ map_style="light",
419
+ tooltip=tooltip,
420
+ )
421
+ st.pydeck_chart(deck, use_container_width=True, height=720)
422
+
423
+
424
+ def main():
425
+ st.set_page_config(
426
+ page_title="Fusion Viewer",
427
+ page_icon=str(ICON_PATH),
428
+ layout="wide",
429
+ initial_sidebar_state="expanded",
430
+ )
431
+
432
+ names, meta, groups = load_metadata()
433
+ property_name = render_sidebar(groups, meta)
434
+ if property_name is None:
435
+ return
436
+
437
+ st.title("Fusion Viewer")
438
+ st.caption(f"{len(names):,} properties from datasets/fusion")
439
+
440
+ with st.spinner("Loading selected property..."):
441
+ df = load_property_frame(property_name)
442
+ color_limits = render_color_controls(property_name, meta[property_name], df)
443
+ vis_df, legend = prepare_visual_values(
444
+ df,
445
+ property_name,
446
+ meta[property_name],
447
+ color_limits=color_limits,
448
+ )
449
+
450
+ render_map(vis_df)
451
+ render_colorbar(legend)
452
+ render_legend(legend)
453
+
454
+
455
+ if __name__ == "__main__":
456
+ main()
viewer_standardization.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+
5
+ import pandas as pd
6
+ from PIL import Image
7
+
8
+ try:
9
+ import rasterio
10
+ import streamlit as st
11
+ except ImportError as exc:
12
+ raise SystemExit(
13
+ "viewer_standardization.py requires streamlit and rasterio.\n"
14
+ "Install missing packages, then run: streamlit run viewer_standardization.py"
15
+ ) from exc
16
+
17
+
18
+ BASE_DIR = Path(__file__).resolve().parent
19
+ HOST_NAME = "esdac"
20
+ DATASETS_DIR = BASE_DIR / "datasets" / HOST_NAME
21
+ STATUS_PATH = BASE_DIR / "src" / HOST_NAME / "status.json"
22
+ ICON_PATH = BASE_DIR / "resources" / "erp.jpeg"
23
+ DEFAULT_DATASET = "soil-bulk-density-europe"
24
+ DEFAULT_FILE = "Public/packing_density.png"
25
+
26
+ VIEWABLE_EXTENSIONS = {
27
+ ".csv",
28
+ ".json",
29
+ ".png",
30
+ ".jpg",
31
+ ".jpeg",
32
+ ".txt",
33
+ ".tif",
34
+ ".tiff",
35
+ }
36
+ STATUS_OPTIONS = ["UNEXAMINED", "SKIPPED", "REQUESTED", "DOWNLOADED", "PROCESSED"]
37
+
38
+
39
+ def format_bytes(size):
40
+ size = float(size)
41
+ for unit in ["B", "KB", "MB", "GB"]:
42
+ if size < 1024 or unit == "GB":
43
+ return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B"
44
+ size /= 1024
45
+ return f"{size:.1f} GB"
46
+
47
+
48
+ @st.cache_data(show_spinner=False)
49
+ def get_datasets():
50
+ datasets = {}
51
+
52
+ try:
53
+ with open(STATUS_PATH, encoding="utf-8") as f:
54
+ items = json.load(f)
55
+ except Exception as exc:
56
+ return datasets, f"Error reading {STATUS_PATH}: {exc}"
57
+
58
+ for item in items:
59
+ name = item["name"]
60
+ dataset_path = DATASETS_DIR / name
61
+ processed_path = dataset_path / "processed"
62
+
63
+ if not processed_path.exists():
64
+ continue
65
+
66
+ file_list = []
67
+ for root, _, files in os.walk(processed_path):
68
+ root_path = Path(root)
69
+ for file_name in files:
70
+ path = root_path / file_name
71
+ if path.suffix.lower() in VIEWABLE_EXTENSIONS:
72
+ rel_path = path.relative_to(processed_path)
73
+ file_list.append(str(rel_path))
74
+
75
+ datasets[name] = {
76
+ "name": name,
77
+ "title": item.get("title", ""),
78
+ "url": item.get("url"),
79
+ "abstract": item.get("abstract") or "",
80
+ "request_needed": item.get("request_needed", False),
81
+ "status": item.get("status"),
82
+ "notes": item.get("notes"),
83
+ "screened_by": item.get("screened_by"),
84
+ "requested_downloaded_by": item.get("requested_downloaded_by"),
85
+ "processed_by": item.get("processed_by"),
86
+ "files": sorted(file_list),
87
+ "path": str(dataset_path),
88
+ "processed_path": str(processed_path),
89
+ }
90
+
91
+ return datasets, None
92
+
93
+
94
+ def file_stats(path):
95
+ stat = path.stat()
96
+ return {
97
+ "Path": str(path),
98
+ "Size": format_bytes(stat.st_size),
99
+ "Modified": pd.Timestamp(stat.st_mtime, unit="s").strftime("%Y-%m-%d %H:%M:%S"),
100
+ }
101
+
102
+
103
+ def format_value(value):
104
+ if isinstance(value, float):
105
+ return f"{value:.6g}"
106
+ return str(value)
107
+
108
+
109
+ def render_dataset_info(data):
110
+ st.subheader(data["name"])
111
+ if data.get("title"):
112
+ st.write(data["title"])
113
+
114
+ cols = st.columns(4)
115
+ cols[0].metric("Status", data.get("status") or "NA")
116
+ cols[1].metric("Files", f"{len(data.get('files', [])):,}")
117
+ cols[2].metric("Request needed", str(data.get("request_needed")))
118
+ cols[3].metric("Processed by", data.get("processed_by") or "NA")
119
+
120
+ details = {
121
+ "URL": data.get("url"),
122
+ "Screened by": data.get("screened_by"),
123
+ "Requested/downloaded by": data.get("requested_downloaded_by"),
124
+ "Notes": data.get("notes"),
125
+ "Dataset path": data.get("path"),
126
+ }
127
+ visible_details = {k: v for k, v in details.items() if v not in (None, "")}
128
+ if visible_details:
129
+ st.table(pd.DataFrame(visible_details.items(), columns=["Field", "Value"]))
130
+
131
+ if data.get("abstract"):
132
+ with st.expander("Abstract", expanded=True):
133
+ st.write(data["abstract"])
134
+
135
+
136
+ def show_csv(path):
137
+ max_rows = st.sidebar.slider("CSV preview rows", 20, 500, 100, step=20)
138
+ df = pd.read_csv(path, low_memory=False, nrows=max_rows)
139
+ st.dataframe(
140
+ df,
141
+ use_container_width=True,
142
+ height=620,
143
+ )
144
+ st.caption(f"Previewing first {len(df):,} rows and {len(df.columns):,} columns.")
145
+
146
+
147
+ def show_image(path):
148
+ image = Image.open(path)
149
+ st.image(image, use_container_width=True)
150
+ st.caption(f"Shape: {image.height} x {image.width}")
151
+
152
+
153
+ def show_json(path):
154
+ with open(path, encoding="utf-8") as f:
155
+ content = json.load(f)
156
+ st.json(content, expanded=False)
157
+
158
+
159
+ def show_raster(path):
160
+ with rasterio.open(path) as src:
161
+ summary = {
162
+ "Shape": f"{src.height} x {src.width}",
163
+ "Bands": src.count,
164
+ "Datatype": ", ".join(src.dtypes),
165
+ "NoData value": src.nodata,
166
+ "CRS": str(src.crs),
167
+ "Bounds": str(src.bounds),
168
+ "Transform": str(src.transform),
169
+ }
170
+ st.table(pd.DataFrame(summary.items(), columns=["Field", "Value"]))
171
+
172
+
173
+ def show_text(path):
174
+ max_chars = st.sidebar.slider("Text preview characters", 1_000, 100_000, 20_000, step=1_000)
175
+ with open(path, encoding="utf-8", errors="replace") as f:
176
+ content = f.read(max_chars + 1)
177
+ truncated = len(content) > max_chars
178
+ if truncated:
179
+ content = content[:max_chars]
180
+ st.code(content)
181
+ if truncated:
182
+ st.caption(f"Preview truncated at {max_chars:,} characters.")
183
+
184
+
185
+ def render_file(path):
186
+ suffix = path.suffix.lower()
187
+
188
+ st.subheader(path.name)
189
+ st.table(pd.DataFrame(file_stats(path).items(), columns=["Field", "Value"]))
190
+
191
+ try:
192
+ if suffix == ".csv":
193
+ show_csv(path)
194
+ elif suffix in {".png", ".jpg", ".jpeg"}:
195
+ show_image(path)
196
+ elif suffix == ".json":
197
+ show_json(path)
198
+ elif suffix in {".tif", ".tiff"}:
199
+ show_raster(path)
200
+ else:
201
+ show_text(path)
202
+ except Exception as exc:
203
+ st.error(f"Error previewing {path.name}: {exc}")
204
+
205
+
206
+ def select_dataset(datasets):
207
+ selected_statuses = st.sidebar.multiselect(
208
+ "Status",
209
+ STATUS_OPTIONS,
210
+ default=["PROCESSED"],
211
+ )
212
+
213
+ search = st.sidebar.text_input("Search dataset", "")
214
+ needle = search.strip().lower()
215
+
216
+ filtered = [
217
+ item
218
+ for item in datasets.values()
219
+ if item.get("status") in selected_statuses
220
+ and (
221
+ not needle
222
+ or needle in item["name"].lower()
223
+ or needle in (item.get("title") or "").lower()
224
+ )
225
+ ]
226
+ filtered.sort(key=lambda item: item["name"].lower())
227
+
228
+ if not filtered:
229
+ return None
230
+
231
+ default_index = 0
232
+ for idx, item in enumerate(filtered):
233
+ if item["name"] == DEFAULT_DATASET:
234
+ default_index = idx
235
+ break
236
+
237
+ return st.sidebar.selectbox(
238
+ "Dataset",
239
+ filtered,
240
+ index=default_index,
241
+ format_func=lambda item: item["name"],
242
+ )
243
+
244
+
245
+ def select_file(dataset):
246
+ files = dataset.get("files", [])
247
+ if not files:
248
+ return None
249
+
250
+ search = st.sidebar.text_input("Search file", "")
251
+ needle = search.strip().lower()
252
+ filtered = [path for path in files if not needle or needle in path.lower()]
253
+
254
+ if not filtered:
255
+ st.sidebar.warning("No matching files.")
256
+ return None
257
+
258
+ options = ["Dataset overview"] + filtered
259
+ default_index = options.index(DEFAULT_FILE) if DEFAULT_FILE in options else 0
260
+
261
+ return st.sidebar.selectbox(
262
+ "Processed file",
263
+ options,
264
+ index=default_index,
265
+ )
266
+
267
+
268
+ def main():
269
+ st.set_page_config(
270
+ page_title="Standardization Viewer",
271
+ page_icon=str(ICON_PATH) if ICON_PATH.exists() else None,
272
+ layout="wide",
273
+ initial_sidebar_state="expanded",
274
+ )
275
+
276
+ st.sidebar.title("Standardization Viewer")
277
+ datasets, error = get_datasets()
278
+ if error:
279
+ st.error(error)
280
+ return
281
+
282
+ dataset = select_dataset(datasets)
283
+ if dataset is None:
284
+ st.warning("No datasets match the selected filters.")
285
+ return
286
+
287
+ selected_file = select_file(dataset)
288
+
289
+ st.title("Standardization Viewer")
290
+ render_dataset_info(dataset)
291
+
292
+ if selected_file and selected_file != "Dataset overview":
293
+ path = Path(dataset["processed_path"]) / selected_file
294
+ st.divider()
295
+ render_file(path)
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()