| import ast |
| import colorsys |
| import hashlib |
| import json |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
|
|
| try: |
| import pydeck as pdk |
| import streamlit as st |
| except 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().parent |
| FUSION_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" |
| DEFAULT_VIEWPORT = {"lat": 50.0, "lon": 10.0, "zoom": 3.2} |
| MAP_HEIGHT_PX = 560 |
|
|
| CORE_UI_PROPERTIES = [ |
| {"label": "USDA texture class", "property": "texture:USDA_class"}, |
| {"label": "clay percentage", "property": "texture:clay_percentage (%)"}, |
| {"label": "silt percentage", "property": "texture:silt_percentage (%)"}, |
| {"label": "sand percentage", "property": "texture:sand_percentage (%)"}, |
| {"label": "coarse fragments", "property": "texture:coarse_percentage (%)"}, |
| {"label": "bulk density", "property": "mass_density:bulk_density (g/cm³)"}, |
| {"label": "bulk density 0-10cm", "property": "mass_density:bulk_density_0_10cm (g/cm³)"}, |
| {"label": "bulk density 10-20cm", "property": "mass_density:bulk_density_10_20cm (g/cm³)"}, |
| {"label": "pH in water", "property": "chemical:pH_in_H2O"}, |
| {"label": "pH in CaCl2", "property": "chemical:pH_in_CaCl2"}, |
| {"label": "organic carbon", "property": "carbon:organic_carbon_content (g/kg)"}, |
| {"label": "topsoil organic carbon", "property": "carbon:organic_carbon_content_topsoil (g/kg)"}, |
| {"label": "calcium carbonate", "property": "carbon:CaCO3_content (g/kg)"}, |
| {"label": "extractable nitrogen", "property": "fertility:N_extractable (g/kg)"}, |
| {"label": "extractable phosphorus", "property": "fertility:P_extractable (mg/kg)"}, |
| {"label": "extractable potassium", "property": "fertility:K_extractable (mg/kg)"}, |
| {"label": "cation exchange capacity", "property": "fertility:cation_exchange_capacity (cmol(+)/kg)"}, |
| {"label": "annual precipitation", "property": "climate:annual_precipitation (mm)"}, |
| {"label": "annual temperature", "property": "climate:annual_temperature (°C)"}, |
| {"label": "elevation", "property": "topography_geology:elevation (m)"}, |
| {"label": "slope", "property": "topography_geology:slope (deg)"}, |
| ] |
|
|
| CORE_VIEWPORTS = { |
| "europe": {"lat": 50.0, "lon": 10.0, "zoom": 3.2}, |
| "iberia": {"lat": 40.0, "lon": -4.0, "zoom": 5.0}, |
| "portugal": {"lat": 39.6, "lon": -8.0, "zoom": 6.0}, |
| "spain": {"lat": 40.3, "lon": -3.7, "zoom": 5.6}, |
| "france": {"lat": 46.6, "lon": 2.2, "zoom": 5.4}, |
| "germany": {"lat": 51.2, "lon": 10.4, "zoom": 5.5}, |
| "italy": {"lat": 42.8, "lon": 12.5, "zoom": 5.4}, |
| "uk": {"lat": 54.2, "lon": -2.5, "zoom": 5.3}, |
| "ireland": {"lat": 53.4, "lon": -8.0, "zoom": 6.0}, |
| "netherlands": {"lat": 52.2, "lon": 5.3, "zoom": 7.0}, |
| "poland": {"lat": 52.1, "lon": 19.4, "zoom": 5.7}, |
| "greece": {"lat": 39.0, "lon": 22.0, "zoom": 5.6}, |
| "scandinavia": {"lat": 62.0, "lon": 15.0, "zoom": 4.2}, |
| "balkans": {"lat": 44.0, "lon": 20.0, "zoom": 5.0}, |
| } |
|
|
| 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 |
|
|
|
|
| def init_ui_state(): |
| st.session_state.setdefault("selected_property", DEFAULT_PROPERTY) |
| st.session_state.setdefault("viewport", DEFAULT_VIEWPORT.copy()) |
| st.session_state.setdefault("ui_agent_messages", []) |
|
|
|
|
| def apply_compact_layout(): |
| st.markdown( |
| """ |
| <style> |
| .block-container { |
| max-width: 100%; |
| padding-top: 1.0rem; |
| padding-right: 1.25rem; |
| padding-left: 1.25rem; |
| padding-bottom: 1.25rem; |
| } |
| [data-testid="stSidebar"] .block-container { |
| padding-top: 1.0rem; |
| } |
| h1 { |
| margin-top: 0; |
| margin-bottom: 0.35rem; |
| } |
| div[data-testid="stCaptionContainer"] { |
| margin-bottom: 0.4rem; |
| } |
| </style> |
| """, |
| unsafe_allow_html=True, |
| ) |
|
|
|
|
| @st.cache_data(show_spinner=False) |
| def list_openai_models(api_key): |
| try: |
| from openai import OpenAI |
| except ImportError: |
| return [], "OpenAI SDK is not installed. Install it with: pip install openai" |
|
|
| try: |
| client = OpenAI(api_key=api_key) |
| models = client.models.list() |
| except Exception as exc: |
| return [], f"Could not load OpenAI models: {exc}" |
|
|
| model_ids = sorted(model.id for model in models.data) |
| chat_like = [ |
| model_id |
| for model_id in model_ids |
| if model_id.startswith(("gpt-", "o")) |
| and not any(token in model_id for token in ("audio", "transcribe", "tts", "image", "realtime")) |
| ] |
| return chat_like or model_ids, None |
|
|
|
|
| @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", |
| "SAMPLE_DEPTH_RANGE_CM", |
| "SAMPLE_SOURCE_DATASET", |
| 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 |
|
|
|
|
| def parse_sample_identity(sample_id): |
| parts = str(sample_id).rsplit("_", 2) |
| if len(parts) == 3: |
| dataset_id, point_id, sample_id = parts |
| return dataset_id, point_id, sample_id |
| return "", str(sample_id), str(sample_id) |
|
|
|
|
| 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") |
|
|
| api_key = st.sidebar.text_input( |
| "OpenAI API token", |
| type="password", |
| help="Used only for this browser session. It is not saved to disk.", |
| ) |
| model = None |
| agent_enabled = False |
| if api_key.strip(): |
| with st.sidebar.spinner("Loading models..."): |
| models, model_error = list_openai_models(api_key.strip()) |
| if model_error: |
| st.sidebar.warning(model_error) |
| elif models: |
| preferred = "gpt-5" |
| default_index = models.index(preferred) if preferred in models else 0 |
| model = st.sidebar.selectbox("UI agent model", models, index=default_index) |
| agent_enabled = True |
| else: |
| st.sidebar.warning("No OpenAI models available for this API token.") |
| else: |
| st.sidebar.selectbox( |
| "UI agent model", |
| ["Enter API token first"], |
| index=0, |
| disabled=True, |
| ) |
|
|
| 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], |
| index=matches[:80].index(st.session_state.selected_property) |
| if st.session_state.selected_property in matches[:80] |
| else 0, |
| format_func=lambda x: x, |
| label_visibility="collapsed", |
| ) |
| st.session_state.selected_property = property_name |
| if len(matches) > 80: |
| st.sidebar.caption("Showing first 80 matches. Type more to narrow.") |
| else: |
| themes = list(groups.keys()) |
| current_theme, _ = split_property_name(st.session_state.selected_property) |
| theme_index = themes.index(current_theme) if current_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(st.session_state.selected_property) |
| if st.session_state.selected_property in options |
| else 0 |
| ) |
| property_name = st.sidebar.selectbox( |
| "Property", |
| options, |
| index=property_index, |
| format_func=lambda x: split_property_name(x)[1], |
| ) |
| st.session_state.selected_property = property_name |
|
|
| 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, api_key, model, agent_enabled |
|
|
|
|
| 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") |
| st.sidebar.caption("Scale is computed from all samples for the selected property, not from the current map view.") |
| property_key = hashlib.md5(property_name.encode("utf-8")).hexdigest()[:12] |
| use_full_range = st.sidebar.checkbox( |
| "Use full data range", |
| value=False, |
| key=f"use_full_range_{property_key}", |
| ) |
| 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", |
| key=f"vmin_{property_key}", |
| ) |
| vmax = st.sidebar.number_input( |
| "vmax", |
| value=default_vmax, |
| min_value=data_min, |
| max_value=data_max, |
| format="%.6g", |
| key=f"vmax_{property_key}", |
| ) |
| 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 is_valid_display_value(value): |
| text = str(value).strip() |
| return text != "" and text.lower() not in {"nan", "none", "null"} |
|
|
|
|
| def format_overlap_line(row): |
| sample = row.get("sample_id", row.get("id", "")) |
| value = row.get("display_value", "") |
| depth = row.get("SAMPLE_DEPTH_RANGE_CM", "") |
| source = row.get("SAMPLE_SOURCE_DATASET", "") |
| parts = [str(sample)] |
| if is_valid_display_value(depth): |
| parts.append(f"depth={depth}") |
| if is_valid_display_value(source): |
| parts.append(str(source)) |
| prefix = " | ".join(parts) |
| return f"{prefix}: {value}" |
|
|
|
|
| def build_map_records(df): |
| df = df.copy() |
| identities = df["id"].map(parse_sample_identity) |
| df["dataset_id"] = [item[0] for item in identities] |
| df["point_id"] = [item[1] for item in identities] |
| df["sample_id"] = [item[2] for item in identities] |
| df["tooltip_location"] = df["GADM_NAMES"].fillna("").astype(str).str.replace( |
| r"^[\[\]'\" ]+|[\[\]'\" ]+$", |
| "", |
| regex=True, |
| ) |
|
|
| single_records = [] |
| overlap_records = [] |
|
|
| for point_id, group in df.groupby("point_id", sort=False): |
| if len(group) == 1: |
| row = group.iloc[0] |
| single_records.append({ |
| "id": row["id"], |
| "lon": float(row["lon"]), |
| "lat": float(row["lat"]), |
| "color": row["color"], |
| "tooltip_text": ( |
| f"{row['id']}\n" |
| f"{row['COUNTRY_CODE']} · {row['tooltip_location']}\n" |
| f"{row['property']}\n" |
| f"{row['display_value']}" |
| ), |
| }) |
| continue |
|
|
| valid = group[group["display_value"].map(is_valid_display_value)] |
| selected = valid.iloc[0] if len(valid) else group.iloc[0] |
| lines = [format_overlap_line(row) for _, row in group.head(16).iterrows()] |
| if len(group) > 16: |
| lines.append(f"... {len(group) - 16} more samples") |
|
|
| overlap_records.append({ |
| "id": f"{point_id} ({len(group)} samples)", |
| "lon": float(selected["lon"]), |
| "lat": float(selected["lat"]), |
| "color": selected["color"], |
| "tooltip_text": ( |
| f"Point {point_id}: {len(group)} samples\n" |
| f"{selected['COUNTRY_CODE']} · {selected['tooltip_location']}\n" |
| f"{selected['property']}\n" |
| + "\n".join(lines) |
| ), |
| }) |
|
|
| return single_records, overlap_records |
|
|
|
|
| def render_map(df): |
| viewport = st.session_state.get("viewport", DEFAULT_VIEWPORT) |
| single_records, overlap_records = build_map_records(df) |
|
|
| layers = [] |
| if single_records: |
| layers.append(pdk.Layer( |
| "ScatterplotLayer", |
| data=single_records, |
| get_position="[lon, lat]", |
| get_fill_color="color", |
| get_radius=1800, |
| radius_min_pixels=2, |
| radius_max_pixels=12, |
| pickable=True, |
| auto_highlight=True, |
| )) |
|
|
| if overlap_records: |
| layers.append(pdk.Layer( |
| "ScatterplotLayer", |
| data=overlap_records, |
| get_position="[lon, lat]", |
| stroked=True, |
| filled=True, |
| get_fill_color="[0, 0, 0, 1]", |
| get_line_color="color", |
| get_radius=1800, |
| radius_min_pixels=2, |
| radius_max_pixels=12, |
| line_width_min_pixels=3, |
| pickable=True, |
| auto_highlight=True, |
| )) |
|
|
| view_state = pdk.ViewState( |
| longitude=viewport.get("lon", DEFAULT_VIEWPORT["lon"]), |
| latitude=viewport.get("lat", DEFAULT_VIEWPORT["lat"]), |
| zoom=viewport.get("zoom", DEFAULT_VIEWPORT["zoom"]), |
| min_zoom=2, |
| max_zoom=12, |
| ) |
|
|
| tooltip = {"text": "{tooltip_text}"} |
|
|
| deck = pdk.Deck( |
| layers=layers, |
| initial_view_state=view_state, |
| map_style="light", |
| tooltip=tooltip, |
| ) |
| st.pydeck_chart(deck, use_container_width=True, height=MAP_HEIGHT_PX) |
| if overlap_records: |
| st.caption( |
| f"{len(overlap_records):,} overlapping point markers are shown as rings. " |
| "Their color uses the first sample in the group with a valid selected-property value." |
| ) |
|
|
|
|
| def core_property_prompt(): |
| lines = [ |
| f"- {item['label']}: {item['property']}" |
| for item in CORE_UI_PROPERTIES |
| ] |
| return "\n".join(lines) |
|
|
|
|
| def strip_unit_suffix(property_name): |
| text = str(property_name).strip() |
| if text.endswith(")") and " (" in text: |
| return text.rsplit(" (", 1)[0] |
| return text |
|
|
|
|
| def normalize_property_text(text): |
| return " ".join(str(text).strip().lower().split()) |
|
|
|
|
| def resolve_property_name(candidate, valid_properties): |
| if not candidate: |
| return None, None |
|
|
| candidate = str(candidate).strip() |
| if candidate in valid_properties: |
| return candidate, None |
|
|
| normalized_candidate = normalize_property_text(candidate) |
| valid_by_normalized = { |
| normalize_property_text(prop): prop |
| for prop in valid_properties |
| } |
| if normalized_candidate in valid_by_normalized: |
| return valid_by_normalized[normalized_candidate], None |
|
|
| valid_by_no_unit = {} |
| for prop in valid_properties: |
| key = normalize_property_text(strip_unit_suffix(prop)) |
| valid_by_no_unit.setdefault(key, []).append(prop) |
| no_unit_matches = valid_by_no_unit.get(normalized_candidate, []) |
| if len(no_unit_matches) == 1: |
| return no_unit_matches[0], None |
| if len(no_unit_matches) > 1: |
| return None, f"ambiguous property without unit {candidate!r}: {no_unit_matches[:8]}" |
|
|
| core_aliases = {} |
| for item in CORE_UI_PROPERTIES: |
| prop = item["property"] |
| aliases = { |
| item["label"], |
| prop, |
| strip_unit_suffix(prop), |
| prop.split(":", 1)[-1], |
| strip_unit_suffix(prop.split(":", 1)[-1]), |
| } |
| for alias in aliases: |
| core_aliases.setdefault(normalize_property_text(alias), prop) |
|
|
| if normalized_candidate in core_aliases: |
| return core_aliases[normalized_candidate], None |
|
|
| return None, f"unknown property {candidate!r}" |
|
|
|
|
| def viewport_prompt(): |
| lines = [ |
| f"- {name}: lat={view['lat']}, lon={view['lon']}, zoom={view['zoom']}" |
| for name, view in CORE_VIEWPORTS.items() |
| ] |
| return "\n".join(lines) |
|
|
|
|
| def build_ui_agent_prompt(user_query, current_property, current_viewport): |
| return f""" |
| You are a UI-control agent for the LUCAS-MEGA Fusion Viewer. |
| |
| Your only job is to decide whether the user's query should update the UI. |
| Do not answer general knowledge questions. Do not explain soil science. |
| Return exactly one JSON object and nothing else. |
| |
| If the query is unrelated to changing the map/property UI, return: |
| {{"need_update_ui": false, "property": null, "viewport_center": null, "viewport_bbox": null}} |
| |
| If the query should update the UI, return: |
| {{ |
| "need_update_ui": true, |
| "property": one of the allowed property strings or null, |
| "viewport_center": {{"lat": number, "lon": number, "zoom": number}} or null, |
| "viewport_bbox": null |
| }} |
| |
| Allowed properties: |
| {core_property_prompt()} |
| |
| Allowed named viewports: |
| {viewport_prompt()} |
| |
| Rules: |
| - Pick the closest allowed property. Do not invent property names. |
| - The "property" value must be copied exactly from the allowed property strings, including units in parentheses. |
| - Never omit units from property names when units are present. |
| - For location requests, use the closest allowed named viewport when possible. |
| - If the user asks for a property but no location, update only "property". |
| - If the user asks for a location but no property, update only "viewport_center". |
| - If the user asks for both, update both. |
| - Use viewport_bbox only if you are certain; otherwise use viewport_center. |
| |
| Current property: {current_property} |
| Current viewport: {json.dumps(current_viewport)} |
| User query: {user_query} |
| """.strip() |
|
|
|
|
| def call_ui_agent(api_key, model, user_query): |
| try: |
| from openai import OpenAI |
| except ImportError: |
| return None, "OpenAI SDK is not installed. Install it with: pip install openai" |
|
|
| client = OpenAI(api_key=api_key) |
| response = client.chat.completions.create( |
| model=model, |
| messages=[ |
| { |
| "role": "user", |
| "content": build_ui_agent_prompt( |
| user_query=user_query, |
| current_property=st.session_state.selected_property, |
| current_viewport=st.session_state.viewport, |
| ), |
| } |
| ], |
| response_format={"type": "json_object"}, |
| ) |
| text = response.choices[0].message.content or "{}" |
| try: |
| return json.loads(text), None |
| except json.JSONDecodeError as exc: |
| return None, f"Could not parse UI-agent JSON: {exc}" |
|
|
|
|
| def validate_viewport(viewport): |
| if not isinstance(viewport, dict): |
| return None |
| try: |
| lat = float(viewport["lat"]) |
| lon = float(viewport["lon"]) |
| zoom = float(viewport["zoom"]) |
| except (KeyError, TypeError, ValueError): |
| return None |
| if not (-90 <= lat <= 90 and -180 <= lon <= 180 and 2 <= zoom <= 12): |
| return None |
| return {"lat": lat, "lon": lon, "zoom": zoom} |
|
|
|
|
| def apply_ui_agent_result(result, valid_properties): |
| if not isinstance(result, dict): |
| return False, "No need to update UI. General reasoning is under development." |
| if not result.get("need_update_ui"): |
| return False, "No need to update UI. General reasoning is under development." |
|
|
| updates = [] |
| property_name = result.get("property") |
| if property_name: |
| resolved_property, property_error = resolve_property_name(property_name, valid_properties) |
| if resolved_property: |
| st.session_state.selected_property = resolved_property |
| updates.append(f"property -> {resolved_property}") |
| else: |
| return False, f"UI update rejected: {property_error}" |
|
|
| viewport = validate_viewport(result.get("viewport_center")) |
| if viewport: |
| st.session_state.viewport = viewport |
| updates.append( |
| f"viewport -> lat={viewport['lat']:.3f}, lon={viewport['lon']:.3f}, zoom={viewport['zoom']:.2f}" |
| ) |
|
|
| if not updates: |
| return False, "No need to update UI. General reasoning is under development." |
| return True, "Updated UI: " + "; ".join(updates) |
|
|
|
|
| @st.fragment |
| def render_chat(api_key, model, valid_properties, agent_enabled): |
| st.divider() |
| st.subheader("UI Agent") |
|
|
| for message in st.session_state.ui_agent_messages: |
| with st.chat_message(message["role"]): |
| st.write(message["content"]) |
|
|
| if not agent_enabled: |
| st.text_input( |
| "Ask the UI agent to change property or region", |
| value="Enter an OpenAI API token in the sidebar to enable the UI agent.", |
| disabled=True, |
| label_visibility="collapsed", |
| ) |
| return |
|
|
| prompt = st.chat_input("Ask the UI agent to change property or region") |
| if not prompt: |
| return |
|
|
| st.session_state.ui_agent_messages.append({"role": "user", "content": prompt}) |
|
|
| result, error = call_ui_agent(api_key.strip(), model.strip(), prompt) |
| if error: |
| answer = error |
| should_rerun = False |
| else: |
| should_rerun, answer = apply_ui_agent_result(result, valid_properties) |
|
|
| st.session_state.ui_agent_messages.append({"role": "assistant", "content": answer}) |
| if should_rerun: |
| st.rerun() |
| st.rerun(scope="fragment") |
|
|
|
|
| def main(): |
| st.set_page_config( |
| page_title="Fusion Viewer", |
| page_icon=str(ICON_PATH), |
| layout="wide", |
| initial_sidebar_state="expanded", |
| ) |
| apply_compact_layout() |
|
|
| init_ui_state() |
| names, meta, groups = load_metadata() |
| valid_properties = set(names) |
| if st.session_state.selected_property not in valid_properties: |
| st.session_state.selected_property = DEFAULT_PROPERTY |
|
|
| sidebar_result = render_sidebar(groups, meta) |
| if sidebar_result is None: |
| return |
| property_name, api_key, model, agent_enabled = sidebar_result |
|
|
| 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) |
| render_chat(api_key, model, valid_properties, agent_enabled) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|