File size: 8,431 Bytes
09451e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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()