File size: 11,719 Bytes
9bc98d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
301
302
303
304
305
306
307
308
309
310
import json
import os
import tkinter as tk
from tkinter import ttk

import pandas as pd
import rasterio
from 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()