import json import os from pathlib import Path import pandas as pd from PIL import Image try: import rasterio import streamlit as st except 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().parent HOST_NAME = "esdac" DATASETS_DIR = BASE_DIR / "datasets" / HOST_NAME STATUS_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()