Kuangdai commited on
Commit ·
09451e0
1
Parent(s): 1ce16f7
Add Streamlit dataset viewers
Browse filesFiles changed (9)
- .gitattributes+3
- README.md+13-5
- requirements.txt+3-4
- resources/viewer.png → resources/erp.jpegRenamed
- resources/preview.png → resources/viewer_fusion.pngRenamed
- resources/viewer_standardization.pngAdded
- viewer.pyDeleted-309
- viewer_fusion.pyAdded+456
- viewer_standardization.pyAdded+299
3 unmodified lines4563 unmodified linesdatasets/fusion/** filter=lfs diff=lfs merge=lfs -textsrc/fuse_esdac/large_inputs/** filter=lfs diff=lfs merge=lfs -textresources/*.png filter=lfs diff=lfs merge=lfs -text3 unmodified lines4567893 unmodified linesdatasets/fusion/** filter=lfs diff=lfs merge=lfs -textsrc/fuse_esdac/large_inputs/** filter=lfs diff=lfs merge=lfs -textresources/*.png filter=lfs diff=lfs merge=lfs -textresources/*.jpg filter=lfs diff=lfs merge=lfs -textresources/*.jpeg filter=lfs diff=lfs merge=lfs -textresources/*.webp filter=lfs diff=lfs merge=lfs -text
66 unmodified lines6768697071727314 unmodified lines8889909192931 unmodified line95969798991001018 unmodified lines11011111211311411511611711811912012112266 unmodified lines```bashGIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/earthroverprogram/lucas-megacd lucas-megagit lfs pull --include="datasets/fusion" --exclude="datasets/esdac,src/fuse_esdac/large_inputs"```The fusion dataset is the released LUCAS-MEGA dataset. It integrates standardized source datasets into a unified14 unmodified lines| `gadm_tree_europe.pkl` | GADM administrative hierarchy attached to samples for geographic reasoning and regional lookup. || `assets/` | Dense feature data, including hydraulic conductivity curves, water retention curves, particle size distribution spectra, and site images where available. |---## Download the Standardized Representation1 unmodified lineFor users interested in the intermediate standardized data (70 GB):```bashgit lfs pull --include="datasets/esdac" --exclude="datasets/fusion,src/fuse_esdac/large_inputs"```The standardized representation contains cleaned and normalized individual source datasets. These datasets have been8 unmodified linesThis layer is useful for inspecting source datasets, understanding preprocessing, developing new fusion rules, debuggingthe pipeline, or extending LUCAS-MEGA.Use `viewer.py` to visualize the standardized data and metadata:```bashpython viewer.py```<img src="resources/preview.png" alt="preview" style="width:60%;">---66 unmodified lines6768697071727314 unmodified lines8889909192939495969798991001011 unmodified line1031041051061071081098 unmodified lines11811912012112212312412512612712812913066 unmodified lines```bashGIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/earthroverprogram/lucas-megacd lucas-megagit lfs pull --include="datasets/fusion,resources" --exclude="datasets/esdac,src/fuse_esdac/large_inputs"```The fusion dataset is the released LUCAS-MEGA dataset. It integrates standardized source datasets into a unified14 unmodified lines| `gadm_tree_europe.pkl` | GADM administrative hierarchy attached to samples for geographic reasoning and regional lookup. || `assets/` | Dense feature data, including hydraulic conductivity curves, water retention curves, particle size distribution spectra, and site images where available. |Use `viewer_fusion.py` to explore fused properties on an interactive sample map:```bashstreamlit run viewer_fusion.py```<img src="resources/viewer_fusion.png" alt="Fusion viewer" style="width:70%;">---## Download the Standardized Representation1 unmodified lineFor users interested in the intermediate standardized data (70 GB):```bashgit lfs pull --include="datasets/esdac,resources" --exclude="datasets/fusion,src/fuse_esdac/large_inputs"```The standardized representation contains cleaned and normalized individual source datasets. These datasets have been8 unmodified linesThis layer is useful for inspecting source datasets, understanding preprocessing, developing new fusion rules, debuggingthe pipeline, or extending LUCAS-MEGA.Use `viewer_standardization.py` to inspect standardized source datasets and metadata:```bashstreamlit run viewer_standardization.py```<img src="resources/viewer_standardization.png" alt="Standardization viewer" style="width:70%;">---
1 unmodified line234567891011121314151617181 unmodified linerasterio~=1.4.3numpy~=2.3.4pillow~=12.0.0openpyxl~=3.1.5matplotlib~=3.10.7geopandas~=1.1.1dbfread~=2.0.7packaging~=25.0gdal~=3.11.4pyproj~=3.7.2tqdm~=4.67.1shapely~=2.1.2requests~=2.32.5beautifulsoup4~=4.14.2duckdb~=1.4.1openai~=2.6.11 unmodified line2345678910111213141516171 unmodified linerasterio~=1.4.3numpy~=2.3.4pillow~=12.0.0matplotlib~=3.10.7geopandas~=1.1.1dbfread~=2.0.7packaging~=25.0gdal~=3.11.4pyproj~=3.7.2tqdm~=4.67.1shapely~=2.1.2requests~=2.32.5beautifulsoup4~=4.14.2openai~=2.6.1pydeck~=0.9.2streamlit~=1.57.0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309import jsonimport osimport tkinter as tkfrom tkinter import ttk
import pandas as pdimport rasteriofrom PIL import Image, ImageTk
class DatasetTreeViewer(tk.Tk): def __init__(self, host_name): super().__init__() self.title("Dataset Viewer — © Earth Rover Program, 2025") self.geometry("1200x700") self.base_path = os.path.join("datasets", host_name) self.datasets = self.get_datasets(host_name)
# === Layout === paned = tk.PanedWindow(self, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=6) paned.pack(fill=tk.BOTH, expand=True)
left_frame = tk.Frame(paned) right_frame = tk.Frame(paned) paned.add(left_frame) paned.paneconfigure(left_frame, minsize=300) paned.add(right_frame)
bottom_frame = tk.Frame(self) bottom_frame.pack(fill=tk.X)
# === Checkbox grid above Treeview (2x2 layout) checkbox_outer_frame = tk.Frame(left_frame) checkbox_outer_frame.pack(pady=4)
self.status_filters = {} default_checked = {"PROCESSED"} status_options = ["UNEXAMINED", "SKIPPED", "REQUESTED", "DOWNLOADED", "PROCESSED"]
for idx, status in enumerate(status_options): row = idx // 2 col = idx % 2 var = tk.BooleanVar(value=status in default_checked) cb = tk.Checkbutton( checkbox_outer_frame, text=status.capitalize(), variable=var, command=self.build_tree, anchor="w", width=15, # fixed width for alignment padx=0 ) cb.grid(row=row, column=col, sticky="w") self.status_filters[status] = var
# === Treeview self.tree = ttk.Treeview(left_frame) self.tree.heading("#0", text=f"Datasets from {host_name.upper()}") self.tree.pack(fill=tk.BOTH, expand=True) self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)
# === Viewer frame self.viewer_frame = tk.Frame(right_frame) self.viewer_frame.pack(fill=tk.BOTH, expand=True)
# === Bottom info self.info_text = tk.Text(bottom_frame, height=10, wrap=tk.WORD) self.info_text.pack(fill=tk.X)
self.build_tree()
def get_datasets(self, host_name): status_path = os.path.join("src", host_name, "status.json") datasets = {}
try: with open(status_path, "r") as f: items = json.load(f)
for item in items: name = item["name"] dataset_path = os.path.join(self.base_path, name) processed_path = os.path.join(dataset_path, "processed")
if not os.path.exists(processed_path): continue
file_list = [] for root, _, files in os.walk(processed_path): for f in files: if f.endswith((".csv", ".png", ".tif", ".tiff", ".json", ".txt")): full_path = os.path.join(root, f) rel_path = os.path.relpath(full_path, processed_path) file_list.append(rel_path)
datasets[name] = { "name": name, "title": item.get("title", ""), "abstract": item.get("abstract") or "", "request_needed": item.get("request_needed", False), "status": item.get("status"), "notes": item.get("notes"), "screened_by": item.get("screened_by"), "requested_downloaded_by": item.get("requested_downloaded_by"), "processed_by": item.get("processed_by"), "files": sorted(file_list), "path": dataset_path } except Exception as e: print(f"Error reading {status_path}: {e}")
return datasets
def build_tree(self): self.tree.delete(*self.tree.get_children()) selected_statuses = {k for k, v in self.status_filters.items() if v.get()}
for dataset_name, data in self.datasets.items(): if data.get("status") not in selected_statuses: continue
dataset_node = self.tree.insert("", "end", text=dataset_name, open=False) node_map = {"": dataset_node}
for rel_path in data["files"]: parts = rel_path.split(os.sep) current = dataset_node for i, part in enumerate(parts): sub_path = os.path.join(*parts[:i + 1]) if sub_path not in node_map: node_map[sub_path] = self.tree.insert(current, "end", text=part, open=False) current = node_map[sub_path]
def on_tree_select(self, event): selected_id = self.tree.focus() item = self.tree.item(selected_id) text = item["text"] parent_id = self.tree.parent(selected_id)
if parent_id == "": dataset_name = text data = self.datasets[dataset_name] self.info_text.delete(1.0, tk.END) lines = [ f"Name: {data['name']}", f"Title: {data['title']}", ] if data.get("abstract"): lines.append(f"Abstract: {data['abstract']}") lines.append(f"Request needed: {data['request_needed']}") lines.append(f"Status: {data['status']}") if data['notes'] is not None: lines.append(f"Notes: {data['notes']}") self.info_text.insert(tk.END, "\n".join(lines)) self.clear_viewer() return
# Traverse upward to get dataset name full_path_parts = [] current_id = selected_id while True: parent = self.tree.parent(current_id) if parent == "": dataset_name = self.tree.item(current_id)["text"] break full_path_parts.insert(0, self.tree.item(current_id)["text"]) current_id = parent
rel_file_path = os.path.join(*full_path_parts) full_file_path = os.path.join(self.datasets[dataset_name]["path"], "processed", rel_file_path)
self.info_text.delete(1.0, tk.END)
if os.path.isdir(full_file_path): self.info_text.insert(tk.END, f"Directory: {rel_file_path} from dataset: {dataset_name}\n") self.clear_viewer() else: self.info_text.insert(tk.END, f"File: {rel_file_path} from dataset: {dataset_name}\n") self.load_file(full_file_path)
def clear_viewer(self): for widget in self.viewer_frame.winfo_children(): widget.destroy()
def load_file(self, path): self.clear_viewer()
if path.endswith(".csv"): try: df = pd.read_csv(path, low_memory=False) self.show_csv(df) self.info_text.insert(tk.END, f"Number of entries: {len(df)}\n") except Exception as e: self.info_text.insert(tk.END, f"Error reading CSV:\n{e}")
elif path.endswith(".png"): try: self.viewer_frame.update_idletasks() frame_w = self.viewer_frame.winfo_width() frame_h = self.viewer_frame.winfo_height()
img = Image.open(path) img_w, img_h = img.size
ratio_w = frame_w / img_w ratio_h = frame_h / img_h scale = min(ratio_w, ratio_h)
new_w = int(img_w * scale) new_h = int(img_h * scale) resized = img.resize((new_w, new_h), Image.LANCZOS) photo = ImageTk.PhotoImage(resized)
label = tk.Label(self.viewer_frame, image=photo) label.image = photo label.pack(expand=True) self.info_text.insert(tk.END, f"Shape: {img_h}x{img_w}\n") except Exception as e: self.info_text.insert(tk.END, f"Error displaying PNG:\n{e}")
elif path.endswith(".json"): try: with open(path, "r") as f: content = json.load(f) text_widget = tk.Text(self.viewer_frame, wrap=tk.NONE) text_widget.insert(tk.END, json.dumps(content, indent=2)) text_widget.configure(state="disabled") text_widget.pack(fill=tk.BOTH, expand=True) except Exception as e: self.info_text.insert(tk.END, f"Error reading JSON:\n{e}")
elif path.endswith(".tif"): try: with rasterio.open(path) as src: shape = (src.height, src.width) dtype = src.dtypes[0] nodata = src.nodata crs = src.crs transform = src.transform
summary = [ f"Shape: {shape}", f"Datatype: {dtype}", f"NoData value: {nodata}", f"CRS: {crs}", f"Transform:\n{transform}", ]
text_widget = tk.Text(self.viewer_frame, wrap=tk.NONE) text_widget.insert(tk.END, "\n".join(summary)) text_widget.configure(state="disabled") text_widget.pack(fill=tk.BOTH, expand=True)
except Exception as e: self.info_text.insert(tk.END, f"Error reading TIF:\n{e}")
else: try: with open(path, "r", encoding="utf-8") as f: content = f.read() text_widget = tk.Text(self.viewer_frame, wrap=tk.NONE) text_widget.insert(tk.END, content) text_widget.configure(state="disabled") text_widget.pack(fill=tk.BOTH, expand=True) except Exception as e: self.info_text.insert(tk.END, f"Unsupported format for quick view: {os.path.basename(path)}\n")
def show_csv(self, df): df = df.head(100) table = ttk.Treeview(self.viewer_frame, show="headings") table.pack(fill=tk.BOTH, expand=True)
scroll_y = tk.Scrollbar(self.viewer_frame, orient="vertical", command=table.yview) scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
scroll_x = tk.Scrollbar(self.viewer_frame, orient="horizontal", command=table.xview) scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
table.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set) table["columns"] = list(df.columns)
for col in df.columns: col_values = df[col].astype(str).head(20).tolist() max_len = max([len(col)] + [len(val) for val in col_values]) width_px = max(80, min(400, max_len * 7)) table.heading(col, text=col) table.column(col, width=width_px, anchor="w", stretch=False)
for _, row in df.iterrows(): values = [self.format_value(val) for val in row] table.insert("", "end", values=values)
@staticmethod def format_value(val): if isinstance(val, float): return f"{val:.6g}" return str(val)
# === Run Viewer ===if __name__ == "__main__": host_name_ = "esdac" app = DatasetTreeViewer(host_name_) try: icon = tk.PhotoImage(file="resources/viewer.png") app.iconphoto(True, icon) except Exception as ex: print("Failed to load icon:", ex) app.mainloop()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456import astimport colorsysimport hashlibimport jsonfrom pathlib import Path
import numpy as npimport pandas as pd
try: import pydeck as pdk import streamlit as stexcept ImportError as exc: raise SystemExit( "viewer_fusion.py requires streamlit and pydeck.\n" "Install them with: pip install streamlit pydeck\n" "Then run: streamlit run viewer_fusion.py" ) from exc
BASE_DIR = Path(__file__).resolve().parentFUSION_DIR = BASE_DIR / "datasets" / "fusion"ICON_PATH = BASE_DIR / "resources" / "erp.jpeg"TABLE_PATH = FUSION_DIR / "data_table.csv"META_NAMES_PATH = FUSION_DIR / "meta_column_names.json"META_COMPLETE_PATH = FUSION_DIR / "meta_column_complete.json"DEFAULT_PROPERTY = "texture:USDA_class"
BASE_COLUMNS = [ "id", "LAT_LONG", "GADM_IDS", "GADM_NAMES", "COUNTRY_CODE", "SAMPLE_DATE", "SAMPLE_DEPTH_RANGE_CM", "SAMPLE_SOURCE_DATASET",]
def split_property_name(name): if ":" not in name: return "other", name theme, prop = name.split(":", 1) return theme, prop
@st.cache_data(show_spinner=False)def load_metadata(): with open(META_NAMES_PATH, encoding="utf-8") as f: names = json.load(f)["column_names"]
with open(META_COMPLETE_PATH, encoding="utf-8") as f: meta = json.load(f)
groups = {} for name in names: theme, prop = split_property_name(name) groups.setdefault(theme, []).append((prop, name))
for theme in groups: groups[theme].sort(key=lambda item: item[0].lower())
return names, meta, dict(sorted(groups.items()))
def parse_lat_long(value): if pd.isna(value): return np.nan, np.nan if isinstance(value, str): try: parsed = ast.literal_eval(value) except (SyntaxError, ValueError): return np.nan, np.nan else: parsed = value if not isinstance(parsed, (list, tuple)) or len(parsed) < 2: return np.nan, np.nan return float(parsed[0]), float(parsed[1])
def vector_mean(value): if pd.isna(value) or value == "": return np.nan if isinstance(value, str): try: value = ast.literal_eval(value) except (SyntaxError, ValueError): return np.nan if not isinstance(value, (list, tuple)): return np.nan nums = pd.to_numeric(pd.Series(value), errors="coerce").dropna() return float(nums.mean()) if len(nums) else np.nan
@st.cache_data(show_spinner=False)def load_property_frame(property_name): columns = ["id", "LAT_LONG", "GADM_NAMES", "COUNTRY_CODE", property_name] df = pd.read_csv( TABLE_PATH, usecols=columns, low_memory=False, keep_default_na=True, )
lat_lon = df["LAT_LONG"].map(parse_lat_long) df["lat"] = [item[0] for item in lat_lon] df["lon"] = [item[1] for item in lat_lon] df = df.dropna(subset=["lat", "lon"]) return df
COLOR_STOPS = [ (68, 1, 84), (59, 82, 139), (33, 145, 140), (94, 201, 98), (253, 231, 37),]
def interpolate_color(value, vmin, vmax): if pd.isna(value): return [150, 150, 150, 55] if pd.isna(vmin) or pd.isna(vmax) or vmax <= vmin: t = 0.5 else: t = float((value - vmin) / (vmax - vmin)) t = max(0.0, min(1.0, t))
pos = t * (len(COLOR_STOPS) - 1) left = int(np.floor(pos)) right = min(left + 1, len(COLOR_STOPS) - 1) frac = pos - left rgb = [ int(COLOR_STOPS[left][i] + frac * (COLOR_STOPS[right][i] - COLOR_STOPS[left][i])) for i in range(3) ] return rgb + [180]
def category_color(value): if pd.isna(value) or value == "": return [150, 150, 150, 55] digest = hashlib.md5(str(value).encode("utf-8")).hexdigest() hue = int(digest[:8], 16) / 0xFFFFFFFF red, green, blue = colorsys.hsv_to_rgb(hue, 0.62, 0.92) return [int(red * 255), int(green * 255), int(blue * 255), 185]
def get_visual_mode(property_meta): datatype = property_meta.get("datatype") is_array = property_meta.get("is_array_valued", False) if is_array: return "numeric vector mean" if datatype in {"int", "float"}: return "numeric scalar" return "categorical"
def calculate_color_values(df, property_name, property_meta): raw = df[property_name] mode = get_visual_mode(property_meta)
if mode == "numeric vector mean": values = raw.map(vector_mean) elif mode == "numeric scalar": values = pd.to_numeric(raw, errors="coerce") else: values = raw.fillna("").astype(str) return raw, values, mode
def prepare_visual_values(df, property_name, property_meta, color_limits=None): raw, values, mode = calculate_color_values(df, property_name, property_meta)
out = df.copy() out["display_value"] = raw.fillna("").astype(str)
if mode.startswith("numeric"): non_null = values.dropna() if len(non_null): default_vmin = float(non_null.quantile(0.02)) default_vmax = float(non_null.quantile(0.98)) else: default_vmin = default_vmax = np.nan if color_limits: vmin, vmax = color_limits else: vmin, vmax = default_vmin, default_vmax out["color_value"] = values out["color"] = [interpolate_color(v, vmin, vmax) for v in values] legend = { "mode": mode, "valid": int(values.notna().sum()), "missing": int(values.isna().sum()), "min": float(non_null.min()) if len(non_null) else None, "max": float(non_null.max()) if len(non_null) else None, "p02": default_vmin if len(non_null) else None, "p98": default_vmax if len(non_null) else None, "vmin": vmin if len(non_null) else None, "vmax": vmax if len(non_null) else None, } else: categories = values.replace("", np.nan) unique_count = int(categories.nunique(dropna=True)) out["color_value"] = values out["color"] = [category_color(v) for v in values] legend = { "mode": mode, "valid": int(categories.notna().sum()), "missing": int(categories.isna().sum()), "unique": unique_count, "top_values": categories.value_counts(dropna=True).head(12).to_dict(), }
out["property"] = property_name return out, legend
def render_sidebar(groups, meta): st.sidebar.title("Fusion Viewer")
search = st.sidebar.text_input( "Search property", "", placeholder="type part of theme:name (unit)", ) if search.strip(): needle = search.strip().lower() matches = [ name for theme_items in groups.values() for _, name in theme_items if needle in name.lower() ] if not matches: st.sidebar.warning("No matching properties.") return None st.sidebar.caption(f"{len(matches)} matching properties") property_name = st.sidebar.radio( "Matching properties", matches[:80], format_func=lambda x: x, label_visibility="collapsed", ) if len(matches) > 80: st.sidebar.caption("Showing first 80 matches. Type more to narrow.") else: themes = list(groups.keys()) default_theme, _ = split_property_name(DEFAULT_PROPERTY) theme_index = themes.index(default_theme) if default_theme in themes else 0 theme = st.sidebar.selectbox("Theme", themes, index=theme_index) options = [name for _, name in groups[theme]] property_index = options.index(DEFAULT_PROPERTY) if DEFAULT_PROPERTY in options else 0 property_name = st.sidebar.selectbox( "Property", options, index=property_index, format_func=lambda x: split_property_name(x)[1], )
with st.sidebar.expander("Property metadata", expanded=False): item = meta.get(property_name, {}) st.write("datatype:", item.get("datatype")) st.write("array:", item.get("is_array_valued")) st.write("null_fraction:", item.get("null_fraction")) st.write("source_datasets:", item.get("source_datasets")) description = item.get("description") if description: st.caption(description)
return property_name
def render_color_controls(property_name, property_meta, df): raw, values, mode = calculate_color_values(df, property_name, property_meta) if not mode.startswith("numeric"): return None
non_null = values.dropna() if not len(non_null): st.sidebar.warning("No numeric values available for this property.") return None
data_min = float(non_null.min()) data_max = float(non_null.max()) default_vmin = float(non_null.quantile(0.02)) default_vmax = float(non_null.quantile(0.98))
st.sidebar.subheader("Color scale") use_full_range = st.sidebar.checkbox("Use full data range", value=False) if use_full_range: return data_min, data_max
vmin = st.sidebar.number_input( "vmin", value=default_vmin, min_value=data_min, max_value=data_max, format="%.6g", ) vmax = st.sidebar.number_input( "vmax", value=default_vmax, min_value=data_min, max_value=data_max, format="%.6g", ) if vmax <= vmin: st.sidebar.warning("vmax must be larger than vmin; using percentile defaults.") return default_vmin, default_vmax return float(vmin), float(vmax)
def render_legend(legend): cols = st.columns(4) cols[0].metric("Mode", legend["mode"]) cols[1].metric("Valid", f"{legend['valid']:,}") cols[2].metric("Missing", f"{legend['missing']:,}")
if legend["mode"].startswith("numeric"): cols[3].metric("Range", "2%-98%") st.caption( f"Actual min/max: {legend['min']} / {legend['max']} | " f"color clamp: {legend['p02']} / {legend['p98']}" ) else: cols[3].metric("Unique", f"{legend['unique']:,}") if legend["top_values"]: st.caption("Top categories: " + "; ".join( f"{k}: {v}" for k, v in legend["top_values"].items() ))
def render_colorbar(legend): if legend["mode"].startswith("numeric"): gradient = ", ".join(f"rgb({r}, {g}, {b})" for r, g, b in COLOR_STOPS) st.markdown( f""" <div style="margin-top: 0.75rem;"> <div style="height: 14px; border-radius: 7px; background: linear-gradient(90deg, {gradient});"></div> <div style="display: flex; justify-content: space-between; font-size: 0.82rem; color: #666; margin-top: 0.2rem;"> <span>vmin: {legend["vmin"]}</span> <span>vmax: {legend["vmax"]}</span> </div> </div> """, unsafe_allow_html=True, ) else: top_values = legend.get("top_values", {}) if not top_values: return swatches = [] for value in top_values: r, g, b, _ = category_color(value) swatches.append( "<span style='display:inline-flex; align-items:center; gap:0.25rem; " "margin:0 0.65rem 0.35rem 0;'>" f"<span style='width:0.75rem; height:0.75rem; border-radius:50%; " f"background:rgb({r},{g},{b}); display:inline-block;'></span>" f"<span>{value}</span></span>" ) st.markdown("".join(swatches), unsafe_allow_html=True)
def render_map(df): midpoint = [float(df["lon"].median()), float(df["lat"].median())] df = df.copy() df["tooltip_location"] = df["GADM_NAMES"].fillna("").astype(str).str.replace( r"^[\[\]'\" ]+|[\[\]'\" ]+$", "", regex=True, ) df["tooltip_text"] = ( df["id"].fillna("").astype(str) + "\n" + df["COUNTRY_CODE"].fillna("").astype(str) + " · " + df["tooltip_location"].fillna("").astype(str) + "\n" + df["property"].fillna("").astype(str) + "\n" + df["display_value"].fillna("").astype(str) ) map_data = df[ ["id", "lon", "lat", "color", "tooltip_text"] ].to_dict(orient="records")
layer = pdk.Layer( "ScatterplotLayer", data=map_data, get_position="[lon, lat]", get_fill_color="color", get_radius=1800, radius_min_pixels=2, radius_max_pixels=12, pickable=True, auto_highlight=True, )
view_state = pdk.ViewState( longitude=midpoint[0], latitude=midpoint[1], zoom=3.2, min_zoom=2, max_zoom=12, )
tooltip = {"text": "{tooltip_text}"}
deck = pdk.Deck( layers=[layer], initial_view_state=view_state, map_style="light", tooltip=tooltip, ) st.pydeck_chart(deck, use_container_width=True, height=720)
def main(): st.set_page_config( page_title="Fusion Viewer", page_icon=str(ICON_PATH), layout="wide", initial_sidebar_state="expanded", )
names, meta, groups = load_metadata() property_name = render_sidebar(groups, meta) if property_name is None: return
st.title("Fusion Viewer") st.caption(f"{len(names):,} properties from datasets/fusion")
with st.spinner("Loading selected property..."): df = load_property_frame(property_name) color_limits = render_color_controls(property_name, meta[property_name], df) vis_df, legend = prepare_visual_values( df, property_name, meta[property_name], color_limits=color_limits, )
render_map(vis_df) render_colorbar(legend) render_legend(legend)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299import jsonimport osfrom pathlib import Path
import pandas as pdfrom PIL import Image
try: import rasterio import streamlit as stexcept ImportError as exc: raise SystemExit( "viewer_standardization.py requires streamlit and rasterio.\n" "Install missing packages, then run: streamlit run viewer_standardization.py" ) from exc
BASE_DIR = Path(__file__).resolve().parentHOST_NAME = "esdac"DATASETS_DIR = BASE_DIR / "datasets" / HOST_NAMESTATUS_PATH = BASE_DIR / "src" / HOST_NAME / "status.json"ICON_PATH = BASE_DIR / "resources" / "erp.jpeg"DEFAULT_DATASET = "soil-bulk-density-europe"DEFAULT_FILE = "Public/packing_density.png"
VIEWABLE_EXTENSIONS = { ".csv", ".json", ".png", ".jpg", ".jpeg", ".txt", ".tif", ".tiff",}STATUS_OPTIONS = ["UNEXAMINED", "SKIPPED", "REQUESTED", "DOWNLOADED", "PROCESSED"]
def format_bytes(size): size = float(size) for unit in ["B", "KB", "MB", "GB"]: if size < 1024 or unit == "GB": return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B" size /= 1024 return f"{size:.1f} GB"
@st.cache_data(show_spinner=False)def get_datasets(): datasets = {}
try: with open(STATUS_PATH, encoding="utf-8") as f: items = json.load(f) except Exception as exc: return datasets, f"Error reading {STATUS_PATH}: {exc}"
for item in items: name = item["name"] dataset_path = DATASETS_DIR / name processed_path = dataset_path / "processed"
if not processed_path.exists(): continue
file_list = [] for root, _, files in os.walk(processed_path): root_path = Path(root) for file_name in files: path = root_path / file_name if path.suffix.lower() in VIEWABLE_EXTENSIONS: rel_path = path.relative_to(processed_path) file_list.append(str(rel_path))
datasets[name] = { "name": name, "title": item.get("title", ""), "url": item.get("url"), "abstract": item.get("abstract") or "", "request_needed": item.get("request_needed", False), "status": item.get("status"), "notes": item.get("notes"), "screened_by": item.get("screened_by"), "requested_downloaded_by": item.get("requested_downloaded_by"), "processed_by": item.get("processed_by"), "files": sorted(file_list), "path": str(dataset_path), "processed_path": str(processed_path), }
return datasets, None
def file_stats(path): stat = path.stat() return { "Path": str(path), "Size": format_bytes(stat.st_size), "Modified": pd.Timestamp(stat.st_mtime, unit="s").strftime("%Y-%m-%d %H:%M:%S"), }
def format_value(value): if isinstance(value, float): return f"{value:.6g}" return str(value)
def render_dataset_info(data): st.subheader(data["name"]) if data.get("title"): st.write(data["title"])
cols = st.columns(4) cols[0].metric("Status", data.get("status") or "NA") cols[1].metric("Files", f"{len(data.get('files', [])):,}") cols[2].metric("Request needed", str(data.get("request_needed"))) cols[3].metric("Processed by", data.get("processed_by") or "NA")
details = { "URL": data.get("url"), "Screened by": data.get("screened_by"), "Requested/downloaded by": data.get("requested_downloaded_by"), "Notes": data.get("notes"), "Dataset path": data.get("path"), } visible_details = {k: v for k, v in details.items() if v not in (None, "")} if visible_details: st.table(pd.DataFrame(visible_details.items(), columns=["Field", "Value"]))
if data.get("abstract"): with st.expander("Abstract", expanded=True): st.write(data["abstract"])
def show_csv(path): max_rows = st.sidebar.slider("CSV preview rows", 20, 500, 100, step=20) df = pd.read_csv(path, low_memory=False, nrows=max_rows) st.dataframe( df, use_container_width=True, height=620, ) st.caption(f"Previewing first {len(df):,} rows and {len(df.columns):,} columns.")
def show_image(path): image = Image.open(path) st.image(image, use_container_width=True) st.caption(f"Shape: {image.height} x {image.width}")
def show_json(path): with open(path, encoding="utf-8") as f: content = json.load(f) st.json(content, expanded=False)
def show_raster(path): with rasterio.open(path) as src: summary = { "Shape": f"{src.height} x {src.width}", "Bands": src.count, "Datatype": ", ".join(src.dtypes), "NoData value": src.nodata, "CRS": str(src.crs), "Bounds": str(src.bounds), "Transform": str(src.transform), } st.table(pd.DataFrame(summary.items(), columns=["Field", "Value"]))
def show_text(path): max_chars = st.sidebar.slider("Text preview characters", 1_000, 100_000, 20_000, step=1_000) with open(path, encoding="utf-8", errors="replace") as f: content = f.read(max_chars + 1) truncated = len(content) > max_chars if truncated: content = content[:max_chars] st.code(content) if truncated: st.caption(f"Preview truncated at {max_chars:,} characters.")
def render_file(path): suffix = path.suffix.lower()
st.subheader(path.name) st.table(pd.DataFrame(file_stats(path).items(), columns=["Field", "Value"]))
try: if suffix == ".csv": show_csv(path) elif suffix in {".png", ".jpg", ".jpeg"}: show_image(path) elif suffix == ".json": show_json(path) elif suffix in {".tif", ".tiff"}: show_raster(path) else: show_text(path) except Exception as exc: st.error(f"Error previewing {path.name}: {exc}")
def select_dataset(datasets): selected_statuses = st.sidebar.multiselect( "Status", STATUS_OPTIONS, default=["PROCESSED"], )
search = st.sidebar.text_input("Search dataset", "") needle = search.strip().lower()
filtered = [ item for item in datasets.values() if item.get("status") in selected_statuses and ( not needle or needle in item["name"].lower() or needle in (item.get("title") or "").lower() ) ] filtered.sort(key=lambda item: item["name"].lower())
if not filtered: return None
default_index = 0 for idx, item in enumerate(filtered): if item["name"] == DEFAULT_DATASET: default_index = idx break
return st.sidebar.selectbox( "Dataset", filtered, index=default_index, format_func=lambda item: item["name"], )
def select_file(dataset): files = dataset.get("files", []) if not files: return None
search = st.sidebar.text_input("Search file", "") needle = search.strip().lower() filtered = [path for path in files if not needle or needle in path.lower()]
if not filtered: st.sidebar.warning("No matching files.") return None
options = ["Dataset overview"] + filtered default_index = options.index(DEFAULT_FILE) if DEFAULT_FILE in options else 0
return st.sidebar.selectbox( "Processed file", options, index=default_index, )
def main(): st.set_page_config( page_title="Standardization Viewer", page_icon=str(ICON_PATH) if ICON_PATH.exists() else None, layout="wide", initial_sidebar_state="expanded", )
st.sidebar.title("Standardization Viewer") datasets, error = get_datasets() if error: st.error(error) return
dataset = select_dataset(datasets) if dataset is None: st.warning("No datasets match the selected filters.") return
selected_file = select_file(dataset)
st.title("Standardization Viewer") render_dataset_info(dataset)
if selected_file and selected_file != "Dataset overview": path = Path(dataset["processed_path"]) / selected_file st.divider() render_file(path)
if __name__ == "__main__": main().gitattributes+3
README.md+13-5
requirements.txt+3-4
resources/viewer.png → resources/erp.jpegRenamed

Large File Pointer Details
- SHA256: 1437caa11206267ff5e57599109e9e2854f69bd3e7f7203e4abd6635bb357930
- Pointer size: 130 Bytes
- Size of remote file: 16.4 kB

Large File Pointer Details
- SHA256: fcee6493ef55e882e60fb5aa30decc7ccc0732c152918b182ac7c5a9a5846c31
- Pointer size: 129 Bytes
- Size of remote file: 9.17 kB
resources/preview.png → resources/viewer_fusion.pngRenamed

Large File Pointer Details
- SHA256: a9107fa7b923dc632085994d4cf2029fa05c4858afc894288033aa0171407b2e
- Pointer size: 132 Bytes
- Size of remote file: 2.34 MB

Large File Pointer Details
- SHA256: a86dfd63dd8e1630ed69c6dc4da72ac42afd4dd6ab1a3b9eb250c7c647a87a2d
- Pointer size: 132 Bytes
- Size of remote file: 2.01 MB
resources/viewer_standardization.pngAdded

Large File Pointer Details
- SHA256: 47d4531300f5cde0282778cdddd71f20c871a408a15d5de70aa9c5594c69963e
- Pointer size: 132 Bytes
- Size of remote file: 3.12 MB
viewer.pyDeleted-309
viewer_fusion.pyAdded+456
viewer_standardization.pyAdded+299