geocif-studio 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- geocif_studio-0.1.0/PKG-INFO +56 -0
- geocif_studio-0.1.0/README.md +39 -0
- geocif_studio-0.1.0/geocif_studio/__init__.py +3 -0
- geocif_studio-0.1.0/geocif_studio/__main__.py +6 -0
- geocif_studio-0.1.0/geocif_studio/app.py +167 -0
- geocif_studio-0.1.0/geocif_studio/cli.py +87 -0
- geocif_studio-0.1.0/geocif_studio/core/__init__.py +1 -0
- geocif_studio-0.1.0/geocif_studio/core/checkpoints.py +295 -0
- geocif_studio-0.1.0/geocif_studio/core/doctor.py +502 -0
- geocif_studio-0.1.0/geocif_studio/core/project.py +716 -0
- geocif_studio-0.1.0/geocif_studio/core/runner.py +285 -0
- geocif_studio-0.1.0/geocif_studio/core/stages.py +73 -0
- geocif_studio-0.1.0/geocif_studio/core/templates.py +574 -0
- geocif_studio-0.1.0/geocif_studio/core/worker.py +153 -0
- geocif_studio-0.1.0/geocif_studio/pages/__init__.py +1 -0
- geocif_studio-0.1.0/geocif_studio/pages/step1_workspace.py +281 -0
- geocif_studio-0.1.0/geocif_studio/pages/step2_region_data.py +284 -0
- geocif_studio-0.1.0/geocif_studio/pages/step3_configure.py +282 -0
- geocif_studio-0.1.0/geocif_studio/pages/step4_run.py +277 -0
- geocif_studio-0.1.0/geocif_studio/pages/step5_results.py +353 -0
- geocif_studio-0.1.0/geocif_studio/pages/widgets.py +201 -0
- geocif_studio-0.1.0/geocif_studio/state.py +58 -0
- geocif_studio-0.1.0/geocif_studio.egg-info/PKG-INFO +56 -0
- geocif_studio-0.1.0/geocif_studio.egg-info/SOURCES.txt +33 -0
- geocif_studio-0.1.0/geocif_studio.egg-info/dependency_links.txt +1 -0
- geocif_studio-0.1.0/geocif_studio.egg-info/entry_points.txt +3 -0
- geocif_studio-0.1.0/geocif_studio.egg-info/requires.txt +10 -0
- geocif_studio-0.1.0/geocif_studio.egg-info/top_level.txt +1 -0
- geocif_studio-0.1.0/pyproject.toml +35 -0
- geocif_studio-0.1.0/setup.cfg +4 -0
- geocif_studio-0.1.0/tests/test_checkpoints.py +69 -0
- geocif_studio-0.1.0/tests/test_doctor_and_gate0.py +73 -0
- geocif_studio-0.1.0/tests/test_project_ini_sync.py +97 -0
- geocif_studio-0.1.0/tests/test_runner_worker.py +59 -0
- geocif_studio-0.1.0/tests/test_ui_smoke.py +182 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: geocif-studio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Guided localhost & desktop GUI for geoprepare, geomerge, geocif, and yield_outlook
|
|
5
|
+
Author-email: Ritvik Sahajpal <ritvik@umd.edu>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: nicegui>=2.0
|
|
10
|
+
Requires-Dist: configupdater>=3.2
|
|
11
|
+
Requires-Dist: psutil>=5.9
|
|
12
|
+
Requires-Dist: pandas<3
|
|
13
|
+
Provides-Extra: native
|
|
14
|
+
Requires-Dist: pywebview>=5.0; extra == "native"
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
17
|
+
|
|
18
|
+
# GeoCIF Studio
|
|
19
|
+
|
|
20
|
+
Guided local GUI (`http://127.0.0.1:8765` or standalone desktop window) for configuring, validating, running, and inspecting the **`geoprepare` → `geomerge` → `geocif` → `yield_outlook`** pipeline on a user's own machine.
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
1. **Workspace & Environment Doctor**: Create new 5-file GeoCIF projects, open existing HPC/production config folders, or import workshop training bundles (with 1-click `dir_base` local path relocation) plus GDAL/GMT/disk/credential checks.
|
|
25
|
+
2. **Region, Boundary & Gate-0 Audit**: Interactive Leaflet preview of administrative boundaries, Pooch metadata fetch, and pre-flight validation of `ADM_ID` / `num_ID`, pure-ASCII region names, and boundary-to-yield CSV matching.
|
|
26
|
+
3. **Guided Pipeline Configuration**: ~15 high-signal settings (EO datasets with live API-key badges, crop-mask rules, CPU budget, CID windowing, ML models, and Yield Outlook options) synchronized cleanly across `geobase.txt`, `countries.txt`, `crops.txt`, `geoextract.txt`, and `geocif.txt` while preserving inline `;` comments.
|
|
27
|
+
4. **Subprocess Pipeline Runner**: Runs each stage (`geodownload`, `geoextract`, `geomerge`, `indices_runner`, `yield_outlook`, `geoagmet`) in an isolated child process (`spawn`-safe on Windows, safe with `yield_outlook`'s `os._exit(0)`), with on-disk checkpoint detection, `reuse_db` fast map reruns, live streaming logs across browser refreshes, and clean `psutil` process-tree cancellation.
|
|
28
|
+
5. **Results & Yield Outlook Explorer**: Filterable gallery of Yield Outlook & diagnostic maps, inline `report_lite` PDF viewer, interactive SQLite forecast/skill explorer (`country_metrics` + Observed vs. Predicted charts), AgMet viewer, and CSV downloads.
|
|
29
|
+
|
|
30
|
+
## Installation (into `geo-stack`)
|
|
31
|
+
|
|
32
|
+
```powershell
|
|
33
|
+
# Windows (pixi geo-stack)
|
|
34
|
+
pixi run --manifest-path $env:USERPROFILE\geo-stack-env\geo-stack\pixi.toml pip install -e D:\projects\geocif-studio
|
|
35
|
+
|
|
36
|
+
# Optional standalone OS desktop window support:
|
|
37
|
+
pixi run --manifest-path $env:USERPROFILE\geo-stack-env\geo-stack\pixi.toml pip install -e "D:\projects\geocif-studio[native]"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Launching Locally
|
|
41
|
+
|
|
42
|
+
Double-click `launch-geocif-studio.bat` (Windows) / `launch-geocif-studio.sh` (Linux), or run from a terminal:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# Open in default browser on http://127.0.0.1:8765
|
|
46
|
+
geocif-studio
|
|
47
|
+
|
|
48
|
+
# Open a specific project immediately
|
|
49
|
+
geocif-studio --project D:\projects\GEO\config\argentina_admin2
|
|
50
|
+
|
|
51
|
+
# Open inside a standalone OS desktop window (requires [native] extra)
|
|
52
|
+
geocif-studio --native
|
|
53
|
+
|
|
54
|
+
# Over SSH tunnel from UMD HPC / Linux server
|
|
55
|
+
geocif-studio --no-browser --port 8765
|
|
56
|
+
```
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# GeoCIF Studio
|
|
2
|
+
|
|
3
|
+
Guided local GUI (`http://127.0.0.1:8765` or standalone desktop window) for configuring, validating, running, and inspecting the **`geoprepare` → `geomerge` → `geocif` → `yield_outlook`** pipeline on a user's own machine.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
1. **Workspace & Environment Doctor**: Create new 5-file GeoCIF projects, open existing HPC/production config folders, or import workshop training bundles (with 1-click `dir_base` local path relocation) plus GDAL/GMT/disk/credential checks.
|
|
8
|
+
2. **Region, Boundary & Gate-0 Audit**: Interactive Leaflet preview of administrative boundaries, Pooch metadata fetch, and pre-flight validation of `ADM_ID` / `num_ID`, pure-ASCII region names, and boundary-to-yield CSV matching.
|
|
9
|
+
3. **Guided Pipeline Configuration**: ~15 high-signal settings (EO datasets with live API-key badges, crop-mask rules, CPU budget, CID windowing, ML models, and Yield Outlook options) synchronized cleanly across `geobase.txt`, `countries.txt`, `crops.txt`, `geoextract.txt`, and `geocif.txt` while preserving inline `;` comments.
|
|
10
|
+
4. **Subprocess Pipeline Runner**: Runs each stage (`geodownload`, `geoextract`, `geomerge`, `indices_runner`, `yield_outlook`, `geoagmet`) in an isolated child process (`spawn`-safe on Windows, safe with `yield_outlook`'s `os._exit(0)`), with on-disk checkpoint detection, `reuse_db` fast map reruns, live streaming logs across browser refreshes, and clean `psutil` process-tree cancellation.
|
|
11
|
+
5. **Results & Yield Outlook Explorer**: Filterable gallery of Yield Outlook & diagnostic maps, inline `report_lite` PDF viewer, interactive SQLite forecast/skill explorer (`country_metrics` + Observed vs. Predicted charts), AgMet viewer, and CSV downloads.
|
|
12
|
+
|
|
13
|
+
## Installation (into `geo-stack`)
|
|
14
|
+
|
|
15
|
+
```powershell
|
|
16
|
+
# Windows (pixi geo-stack)
|
|
17
|
+
pixi run --manifest-path $env:USERPROFILE\geo-stack-env\geo-stack\pixi.toml pip install -e D:\projects\geocif-studio
|
|
18
|
+
|
|
19
|
+
# Optional standalone OS desktop window support:
|
|
20
|
+
pixi run --manifest-path $env:USERPROFILE\geo-stack-env\geo-stack\pixi.toml pip install -e "D:\projects\geocif-studio[native]"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Launching Locally
|
|
24
|
+
|
|
25
|
+
Double-click `launch-geocif-studio.bat` (Windows) / `launch-geocif-studio.sh` (Linux), or run from a terminal:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
# Open in default browser on http://127.0.0.1:8765
|
|
29
|
+
geocif-studio
|
|
30
|
+
|
|
31
|
+
# Open a specific project immediately
|
|
32
|
+
geocif-studio --project D:\projects\GEO\config\argentina_admin2
|
|
33
|
+
|
|
34
|
+
# Open inside a standalone OS desktop window (requires [native] extra)
|
|
35
|
+
geocif-studio --native
|
|
36
|
+
|
|
37
|
+
# Over SSH tunnel from UMD HPC / Linux server
|
|
38
|
+
geocif-studio --no-browser --port 8765
|
|
39
|
+
```
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Main NiceGUI application shell for GeoCIF Studio."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import mimetypes
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from fastapi import HTTPException, Query
|
|
9
|
+
from fastapi.responses import FileResponse
|
|
10
|
+
from nicegui import app, ui
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .core.project import REQUIRED_CONFIG_FILES
|
|
14
|
+
from .core.runner import JOB_RUNNER
|
|
15
|
+
from .pages.step1_workspace import render_step1
|
|
16
|
+
from .pages.step2_region_data import render_step2
|
|
17
|
+
from .pages.step3_configure import render_step3
|
|
18
|
+
from .pages.step4_run import render_step4
|
|
19
|
+
from .pages.step5_results import render_step5
|
|
20
|
+
from .state import APP_STATE
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _allowed_roots() -> list[Path]:
|
|
24
|
+
proj = APP_STATE.project
|
|
25
|
+
if proj is None:
|
|
26
|
+
return []
|
|
27
|
+
roots = [proj.project_root.resolve(), proj.config_dir.resolve()]
|
|
28
|
+
_, raw_base, sugg_base = proj.detect_foreign_dir_base()
|
|
29
|
+
for b in (raw_base, str(sugg_base)):
|
|
30
|
+
if b and Path(b).exists():
|
|
31
|
+
roots.append(Path(b).resolve())
|
|
32
|
+
return roots
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@app.get("/studio-file")
|
|
36
|
+
def serve_studio_file(path: str = Query(...)) -> FileResponse:
|
|
37
|
+
"""Serve PNG maps and report_lite PDFs strictly from active project folders."""
|
|
38
|
+
target = Path(path).resolve()
|
|
39
|
+
if not target.is_file():
|
|
40
|
+
raise HTTPException(status_code=404, detail="File not found")
|
|
41
|
+
|
|
42
|
+
allowed = any(
|
|
43
|
+
target == r or r in target.parents
|
|
44
|
+
for r in _allowed_roots()
|
|
45
|
+
)
|
|
46
|
+
if not allowed:
|
|
47
|
+
raise HTTPException(status_code=403, detail="Path outside active project")
|
|
48
|
+
|
|
49
|
+
mime, _ = mimetypes.guess_type(str(target))
|
|
50
|
+
headers = {"Content-Disposition": f'inline; filename="{target.name}"'}
|
|
51
|
+
return FileResponse(target, media_type=mime or "application/octet-stream", headers=headers)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@ui.page("/")
|
|
55
|
+
def index_page() -> None:
|
|
56
|
+
ui.colors(
|
|
57
|
+
primary="#166534", # Forest green (EO / agriculture)
|
|
58
|
+
secondary="#0f172a",
|
|
59
|
+
accent="#0284c7",
|
|
60
|
+
positive="#15803d",
|
|
61
|
+
warning="#d97706",
|
|
62
|
+
negative="#dc2626",
|
|
63
|
+
)
|
|
64
|
+
ui.page_title("GeoCIF Studio — Local EO & Crop Yield Outlook")
|
|
65
|
+
|
|
66
|
+
step_state = {"current": 1}
|
|
67
|
+
|
|
68
|
+
# ── Top Application Header ────────────────────────────────────────
|
|
69
|
+
with ui.header().classes("bg-slate-900 text-white px-6 py-3 items-center justify-between shadow"):
|
|
70
|
+
with ui.row().classes("items-center gap-3"):
|
|
71
|
+
ui.icon("Spa", color="emerald-4", size="28px")
|
|
72
|
+
with ui.column().classes("gap-0"):
|
|
73
|
+
ui.label(f"GeoCIF Studio v{__version__}").classes("text-base font-bold tracking-tight")
|
|
74
|
+
ui.label("Local geoprepare · geomerge · CID indices · Yield Outlook").classes(
|
|
75
|
+
"text-[11px] text-slate-300"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@ui.refreshable
|
|
79
|
+
def header_right() -> None:
|
|
80
|
+
with ui.row().classes("items-center gap-3"):
|
|
81
|
+
if APP_STATE.project is not None:
|
|
82
|
+
s = APP_STATE.project.load_guided_settings()
|
|
83
|
+
with ui.badge(color="emerald-8").classes("px-2.5 py-1 gap-1.5 text-xs"):
|
|
84
|
+
ui.icon("folder_special", size="14px")
|
|
85
|
+
ui.label(s.project_name)
|
|
86
|
+
ui.button(
|
|
87
|
+
"Inspect 5 INI Files",
|
|
88
|
+
icon="code",
|
|
89
|
+
on_click=_open_ini_inspector,
|
|
90
|
+
).props("outline dense size=sm text-color=white no-caps")
|
|
91
|
+
else:
|
|
92
|
+
ui.badge("No Project Loaded", color="grey-7").classes("px-2.5 py-1 text-xs")
|
|
93
|
+
|
|
94
|
+
job_badge = ui.badge("Idle", color="grey-8").classes("px-2.5 py-1 text-xs font-mono")
|
|
95
|
+
|
|
96
|
+
def _tick_job_badge() -> None:
|
|
97
|
+
if JOB_RUNNER.is_running and JOB_RUNNER.state:
|
|
98
|
+
job_badge.text = f"RUNNING: {JOB_RUNNER.state.current_stage or 'pipeline'}"
|
|
99
|
+
job_badge.props("color=amber-8")
|
|
100
|
+
else:
|
|
101
|
+
job_badge.text = "Runner Idle"
|
|
102
|
+
job_badge.props("color=grey-8")
|
|
103
|
+
|
|
104
|
+
ui.timer(1.0, _tick_job_badge)
|
|
105
|
+
|
|
106
|
+
header_right()
|
|
107
|
+
|
|
108
|
+
# ── 5-Step Navigation Bar + Main Workspace Body ───────────────────
|
|
109
|
+
with ui.column().classes("w-full max-w-[1440px] mx-auto px-5 py-4 gap-4"):
|
|
110
|
+
with ui.tabs().classes(
|
|
111
|
+
"w-full bg-white rounded-lg shadow-sm border border-slate-200 text-slate-800"
|
|
112
|
+
) as nav_tabs:
|
|
113
|
+
t1 = ui.tab(1, label="1. Workspace & Doctor", icon="home_repair_service")
|
|
114
|
+
t2 = ui.tab(2, label="2. Region & Data Check", icon="public")
|
|
115
|
+
t3 = ui.tab(3, label="3. Guided Configuration", icon="tune")
|
|
116
|
+
t4 = ui.tab(4, label="4. Run Pipeline", icon="play_circle")
|
|
117
|
+
t5 = ui.tab(5, label="5. Yield Outlook & Results", icon="analytics")
|
|
118
|
+
_ = (t1, t2, t3, t4, t5)
|
|
119
|
+
|
|
120
|
+
def go_step(step_num: int) -> None:
|
|
121
|
+
step_state["current"] = step_num
|
|
122
|
+
nav_tabs.value = step_num
|
|
123
|
+
step_content.refresh()
|
|
124
|
+
|
|
125
|
+
def on_project_changed() -> None:
|
|
126
|
+
header_right.refresh()
|
|
127
|
+
step_content.refresh()
|
|
128
|
+
|
|
129
|
+
@ui.refreshable
|
|
130
|
+
def step_content() -> None:
|
|
131
|
+
cur = int(nav_tabs.value or 1)
|
|
132
|
+
if cur == 1:
|
|
133
|
+
render_step1(on_project_changed, go_step)
|
|
134
|
+
elif cur == 2:
|
|
135
|
+
render_step2(on_project_changed, go_step)
|
|
136
|
+
elif cur == 3:
|
|
137
|
+
render_step3(on_project_changed, go_step)
|
|
138
|
+
elif cur == 4:
|
|
139
|
+
render_step4(on_project_changed, go_step)
|
|
140
|
+
elif cur == 5:
|
|
141
|
+
render_step5(go_step)
|
|
142
|
+
|
|
143
|
+
nav_tabs.on_value_change(lambda _e: step_content.refresh())
|
|
144
|
+
step_content()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _open_ini_inspector() -> None:
|
|
148
|
+
proj = APP_STATE.project
|
|
149
|
+
if proj is None:
|
|
150
|
+
return
|
|
151
|
+
with ui.dialog() as dlg, ui.card().classes("w-[88vw] max-w-[1050px] p-4 gap-2"):
|
|
152
|
+
with ui.row().classes("w-full items-center justify-between"):
|
|
153
|
+
ui.label(f"Generated / Synchronized Config Files ({proj.config_dir})").classes(
|
|
154
|
+
"text-sm font-bold text-slate-800"
|
|
155
|
+
)
|
|
156
|
+
ui.button(icon="close", on_click=dlg.close).props("flat round dense")
|
|
157
|
+
|
|
158
|
+
with ui.tabs().classes("w-full") as ftabs:
|
|
159
|
+
for fn in REQUIRED_CONFIG_FILES:
|
|
160
|
+
ui.tab(fn, label=fn)
|
|
161
|
+
with ui.tab_panels(ftabs, value=REQUIRED_CONFIG_FILES[0]).classes("w-full"):
|
|
162
|
+
for fn in REQUIRED_CONFIG_FILES:
|
|
163
|
+
fpath = proj.config_dir / fn
|
|
164
|
+
txt = fpath.read_text(encoding="utf-8") if fpath.is_file() else "(missing)"
|
|
165
|
+
with ui.tab_panel(fn):
|
|
166
|
+
ui.code(txt, language="ini").classes("w-full max-h-[65vh] overflow-auto text-xs")
|
|
167
|
+
dlg.open()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Command-line launcher for GeoCIF Studio (localhost browser or native desktop)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import socket
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _find_free_port(preferred: int, host: str = "127.0.0.1") -> int:
|
|
11
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
12
|
+
if sock.connect_ex((host, preferred)) != 0:
|
|
13
|
+
return preferred
|
|
14
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
15
|
+
sock.bind((host, 0))
|
|
16
|
+
return int(sock.getsockname()[1])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
20
|
+
p = argparse.ArgumentParser(
|
|
21
|
+
prog="geocif-studio",
|
|
22
|
+
description="Launch the local GeoCIF Studio GUI (geoprepare -> geomerge -> geocif -> yield_outlook).",
|
|
23
|
+
)
|
|
24
|
+
p.add_argument(
|
|
25
|
+
"--host",
|
|
26
|
+
default="127.0.0.1",
|
|
27
|
+
help="Bind address (default: 127.0.0.1 — strictly local machine only).",
|
|
28
|
+
)
|
|
29
|
+
p.add_argument(
|
|
30
|
+
"--port",
|
|
31
|
+
type=int,
|
|
32
|
+
default=8765,
|
|
33
|
+
help="Preferred TCP port (default: 8765; auto-picks a free port if busy).",
|
|
34
|
+
)
|
|
35
|
+
p.add_argument(
|
|
36
|
+
"--native",
|
|
37
|
+
action="store_true",
|
|
38
|
+
help="Open inside a standalone native OS desktop window (requires pywebview).",
|
|
39
|
+
)
|
|
40
|
+
p.add_argument(
|
|
41
|
+
"--no-browser",
|
|
42
|
+
action="store_true",
|
|
43
|
+
help="Start the localhost server without automatically opening a browser tab.",
|
|
44
|
+
)
|
|
45
|
+
p.add_argument(
|
|
46
|
+
"--project",
|
|
47
|
+
type=str,
|
|
48
|
+
default=None,
|
|
49
|
+
help="Optional project or 5-file config folder to open immediately on startup.",
|
|
50
|
+
)
|
|
51
|
+
return p
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def main(argv: list[str] | None = None) -> None:
|
|
55
|
+
args = build_parser().parse_args(argv)
|
|
56
|
+
|
|
57
|
+
if args.project:
|
|
58
|
+
from .core.project import StudioProject
|
|
59
|
+
from .state import APP_STATE
|
|
60
|
+
|
|
61
|
+
opened = StudioProject.open_existing(Path(args.project))
|
|
62
|
+
APP_STATE.set_project(opened)
|
|
63
|
+
|
|
64
|
+
# Import app routes before calling ui.run
|
|
65
|
+
import os
|
|
66
|
+
from nicegui import ui
|
|
67
|
+
|
|
68
|
+
from . import app as _studio_app # noqa: F401
|
|
69
|
+
|
|
70
|
+
if "PYTEST_CURRENT_TEST" in os.environ and "NICEGUI_SCREEN_TEST_PORT" not in os.environ:
|
|
71
|
+
os.environ.pop("PYTEST_CURRENT_TEST", None)
|
|
72
|
+
|
|
73
|
+
port = _find_free_port(args.port, args.host)
|
|
74
|
+
print(f"GeoCIF Studio listening on http://{args.host}:{port}", flush=True)
|
|
75
|
+
|
|
76
|
+
ui.run(
|
|
77
|
+
host=args.host,
|
|
78
|
+
port=port,
|
|
79
|
+
title="GeoCIF Studio",
|
|
80
|
+
show=not args.no_browser,
|
|
81
|
+
native=args.native,
|
|
82
|
+
reload=False,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ in {"__main__", "__mp_main__"}:
|
|
87
|
+
main()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core backend modules for GeoCIF Studio."""
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Disk checkpoint and output artifact scanner for GeoCIF Studio.
|
|
2
|
+
|
|
3
|
+
Inspects ``[PATHS]`` on disk so:
|
|
4
|
+
1. Step 4 (Pipeline Runner) shows green/grey checkpoint badges per stage and
|
|
5
|
+
lets users resume from any stage or pick an existing ``outlook_*.db`` for
|
|
6
|
+
fast ``reuse_db`` map regeneration.
|
|
7
|
+
2. Step 5 (Results Explorer) discovers Yield Outlook maps, ``report_lite`` PDFs,
|
|
8
|
+
diagnostic figures, FDW/prediction CSVs, AgMet graphics, and SQLite tables.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import datetime as dt
|
|
14
|
+
import sqlite3
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
from .project import StudioProject
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class StageCheckpoint:
|
|
26
|
+
stage_id: str
|
|
27
|
+
has_data: bool
|
|
28
|
+
summary: str
|
|
29
|
+
latest_mtime: str = ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class ProjectArtifacts:
|
|
34
|
+
"""Discovered output files for Results Explorer & reuse_db selection."""
|
|
35
|
+
|
|
36
|
+
dir_output_proj: Path | None = None
|
|
37
|
+
sqlite_dbs: list[Path] = field(default_factory=list)
|
|
38
|
+
outlook_dirs: list[Path] = field(default_factory=list)
|
|
39
|
+
outlook_maps: list[Path] = field(default_factory=list)
|
|
40
|
+
diagnostic_plots: list[Path] = field(default_factory=list)
|
|
41
|
+
pdf_reports: list[Path] = field(default_factory=list)
|
|
42
|
+
csv_exports: list[Path] = field(default_factory=list)
|
|
43
|
+
agmet_images: list[Path] = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _fmt_mtime(paths: list[Path]) -> str:
|
|
47
|
+
if not paths:
|
|
48
|
+
return ""
|
|
49
|
+
latest = max((p.stat().st_mtime for p in paths if p.exists()), default=0.0)
|
|
50
|
+
if latest <= 0:
|
|
51
|
+
return ""
|
|
52
|
+
return dt.datetime.fromtimestamp(latest).strftime("%Y-%m-%d %H:%M")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def scan_stage_checkpoints(project: StudioProject) -> dict[str, StageCheckpoint]:
|
|
56
|
+
"""Check on-disk outputs for each of the 6 v1 pipeline stages."""
|
|
57
|
+
needs_reloc, _, _ = project.detect_foreign_dir_base()
|
|
58
|
+
if needs_reloc:
|
|
59
|
+
return {
|
|
60
|
+
sid: StageCheckpoint(sid, False, "Repoint dir_base first")
|
|
61
|
+
for sid in (
|
|
62
|
+
"geodownload",
|
|
63
|
+
"geoextract",
|
|
64
|
+
"geomerge",
|
|
65
|
+
"indices_runner",
|
|
66
|
+
"yield_outlook",
|
|
67
|
+
"geoagmet",
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
gp = project.geoprepare_parser()
|
|
72
|
+
gc = project.geocif_parser()
|
|
73
|
+
s = project.load_guided_settings()
|
|
74
|
+
dir_intermed = Path(gp.get("PATHS", "dir_intermed"))
|
|
75
|
+
dir_output = Path(gp.get("PATHS", "dir_output"))
|
|
76
|
+
proj_out = dir_output / s.project_name
|
|
77
|
+
thresh_dir = f"crop_t{s.floor}" if s.threshold else f"crop_p{s.ceil}"
|
|
78
|
+
|
|
79
|
+
# 1. geodownload: check dir_intermed subfolders with .tif/.nc files
|
|
80
|
+
intermed_subdirs = [p for p in dir_intermed.iterdir() if p.is_dir()] if dir_intermed.is_dir() else []
|
|
81
|
+
has_dl = len(intermed_subdirs) > 0
|
|
82
|
+
cp_dl = StageCheckpoint(
|
|
83
|
+
"geodownload",
|
|
84
|
+
has_dl,
|
|
85
|
+
f"{len(intermed_subdirs)} dataset folder(s) in intermed/" if has_dl else "No processed rasters yet",
|
|
86
|
+
_fmt_mtime(intermed_subdirs),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# 2. geoextract: per-region variable CSVs under {proj_out}/{thresh_dir}/{country}/{crop}/{var}/
|
|
90
|
+
extract_csvs: list[Path] = []
|
|
91
|
+
for c in s.countries:
|
|
92
|
+
c_dir = proj_out / thresh_dir / c
|
|
93
|
+
if c_dir.is_dir():
|
|
94
|
+
for crop_sub in c_dir.iterdir():
|
|
95
|
+
if crop_sub.is_dir():
|
|
96
|
+
extract_csvs.extend(list(crop_sub.glob("*/*.csv"))[:50])
|
|
97
|
+
has_ext = len(extract_csvs) > 0
|
|
98
|
+
cp_ext = StageCheckpoint(
|
|
99
|
+
"geoextract",
|
|
100
|
+
has_ext,
|
|
101
|
+
"Extracted variable CSVs present" if has_ext else "Not extracted yet",
|
|
102
|
+
_fmt_mtime(extract_csvs),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# 3. geomerge: {country}_{crop}_s{season}.csv
|
|
106
|
+
merged_files: list[Path] = []
|
|
107
|
+
for c in s.countries:
|
|
108
|
+
for crop in s.crops:
|
|
109
|
+
for seas in s.seasons:
|
|
110
|
+
fname = f"{c}_{crop}_s{seas}.csv"
|
|
111
|
+
for cand in (
|
|
112
|
+
proj_out / thresh_dir / c / fname,
|
|
113
|
+
proj_out / "countries" / c / fname,
|
|
114
|
+
dir_output / "countries" / c / fname,
|
|
115
|
+
):
|
|
116
|
+
if cand.is_file():
|
|
117
|
+
merged_files.append(cand)
|
|
118
|
+
break
|
|
119
|
+
has_merge = len(merged_files) > 0
|
|
120
|
+
cp_merge = StageCheckpoint(
|
|
121
|
+
"geomerge",
|
|
122
|
+
has_merge,
|
|
123
|
+
f"{len(merged_files)} merged crop CSV(s)" if has_merge else "No merged CSVs yet",
|
|
124
|
+
_fmt_mtime(merged_files),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
# 4. indices_runner: CID CSVs under {proj_out}/cids or {proj_out}/indices
|
|
128
|
+
cid_files: list[Path] = []
|
|
129
|
+
for sub_name in ("cids", "indices", "cid"):
|
|
130
|
+
cid_root = proj_out / sub_name
|
|
131
|
+
if cid_root.is_dir():
|
|
132
|
+
cid_files.extend(list(cid_root.rglob("*.csv"))[:100])
|
|
133
|
+
has_cid = len(cid_files) > 0
|
|
134
|
+
cp_cid = StageCheckpoint(
|
|
135
|
+
"indices_runner",
|
|
136
|
+
has_cid,
|
|
137
|
+
f"{len(cid_files)}+ CID index CSV(s)" if has_cid else "No CID files yet",
|
|
138
|
+
_fmt_mtime(cid_files),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# 5. yield_outlook: SQLite DBs + outlook analysis dirs
|
|
142
|
+
art = discover_artifacts(project)
|
|
143
|
+
has_out = len(art.sqlite_dbs) > 0 or len(art.outlook_maps) > 0
|
|
144
|
+
cp_out = StageCheckpoint(
|
|
145
|
+
"yield_outlook",
|
|
146
|
+
has_out,
|
|
147
|
+
(
|
|
148
|
+
f"{len(art.sqlite_dbs)} DB(s), {len(art.outlook_maps)} map(s), {len(art.pdf_reports)} PDF(s)"
|
|
149
|
+
if has_out
|
|
150
|
+
else "No outlook run yet"
|
|
151
|
+
),
|
|
152
|
+
_fmt_mtime(art.sqlite_dbs or art.outlook_maps),
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# 6. geoagmet
|
|
156
|
+
has_ag = len(art.agmet_images) > 0
|
|
157
|
+
cp_ag = StageCheckpoint(
|
|
158
|
+
"geoagmet",
|
|
159
|
+
has_ag,
|
|
160
|
+
f"{len(art.agmet_images)} AgMet chart(s)" if has_ag else "Optional — not run yet",
|
|
161
|
+
_fmt_mtime(art.agmet_images[:30]),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
_ = gc
|
|
165
|
+
return {
|
|
166
|
+
"geodownload": cp_dl,
|
|
167
|
+
"geoextract": cp_ext,
|
|
168
|
+
"geomerge": cp_merge,
|
|
169
|
+
"indices_runner": cp_cid,
|
|
170
|
+
"yield_outlook": cp_out,
|
|
171
|
+
"geoagmet": cp_ag,
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def discover_artifacts(project: StudioProject) -> ProjectArtifacts:
|
|
176
|
+
"""Scan project output folders for SQLite DBs, PNG maps, PDFs, CSVs, and AgMet figures."""
|
|
177
|
+
needs_reloc, _, _ = project.detect_foreign_dir_base()
|
|
178
|
+
if needs_reloc:
|
|
179
|
+
return ProjectArtifacts()
|
|
180
|
+
|
|
181
|
+
gp = project.geoprepare_parser()
|
|
182
|
+
s = project.load_guided_settings()
|
|
183
|
+
dir_output = Path(gp.get("PATHS", "dir_output"))
|
|
184
|
+
proj_out = dir_output / s.project_name
|
|
185
|
+
|
|
186
|
+
sqlite_dbs: list[Path] = []
|
|
187
|
+
db_dir = proj_out / "ml" / "db"
|
|
188
|
+
if db_dir.is_dir():
|
|
189
|
+
sqlite_dbs = [
|
|
190
|
+
p
|
|
191
|
+
for p in sorted(db_dir.glob("*.db"), key=lambda x: x.stat().st_mtime, reverse=True)
|
|
192
|
+
if not p.name.startswith("cidc_")
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
outlook_dirs: list[Path] = []
|
|
196
|
+
outlook_maps: list[Path] = []
|
|
197
|
+
diagnostic_plots: list[Path] = []
|
|
198
|
+
pdf_reports: list[Path] = []
|
|
199
|
+
csv_exports: list[Path] = []
|
|
200
|
+
|
|
201
|
+
analysis_root = proj_out / "ml" / "analysis"
|
|
202
|
+
if analysis_root.is_dir():
|
|
203
|
+
outlook_dirs = sorted(
|
|
204
|
+
[p for p in analysis_root.glob("*/outlook") if p.is_dir()],
|
|
205
|
+
key=lambda x: x.stat().st_mtime,
|
|
206
|
+
reverse=True,
|
|
207
|
+
)
|
|
208
|
+
for odir in outlook_dirs[:5]:
|
|
209
|
+
maps_dir = odir / "maps"
|
|
210
|
+
if maps_dir.is_dir():
|
|
211
|
+
outlook_maps.extend(
|
|
212
|
+
sorted(maps_dir.rglob("*.png"), key=lambda x: x.stat().st_mtime, reverse=True)
|
|
213
|
+
)
|
|
214
|
+
for png in sorted(odir.glob("*.png"), key=lambda x: x.stat().st_mtime, reverse=True):
|
|
215
|
+
diagnostic_plots.append(png)
|
|
216
|
+
for sub_diag in ("diagnostics", "plots", "cone", "leadtime"):
|
|
217
|
+
sd = odir / sub_diag
|
|
218
|
+
if sd.is_dir():
|
|
219
|
+
diagnostic_plots.extend(sorted(sd.rglob("*.png")))
|
|
220
|
+
pdf_reports.extend(sorted(odir.rglob("*.pdf")))
|
|
221
|
+
csv_exports.extend(sorted(odir.glob("*.csv")))
|
|
222
|
+
|
|
223
|
+
# Also check top-level proj_out for FDW exports or standalone explore PNGs/PDFs
|
|
224
|
+
if proj_out.is_dir():
|
|
225
|
+
for fdw in sorted(proj_out.rglob("*fdw*.csv")):
|
|
226
|
+
if fdw not in csv_exports:
|
|
227
|
+
csv_exports.append(fdw)
|
|
228
|
+
for pdf in sorted(proj_out.rglob("*.pdf")):
|
|
229
|
+
if pdf not in pdf_reports:
|
|
230
|
+
pdf_reports.append(pdf)
|
|
231
|
+
if not outlook_maps and not diagnostic_plots:
|
|
232
|
+
diagnostic_plots.extend(sorted(proj_out.rglob("*.png"))[:60])
|
|
233
|
+
|
|
234
|
+
# AgMet images
|
|
235
|
+
agmet_images: list[Path] = []
|
|
236
|
+
for ag_cand in (proj_out / "agmet", dir_output / "agmet"):
|
|
237
|
+
if ag_cand.is_dir():
|
|
238
|
+
agmet_images.extend(
|
|
239
|
+
sorted(ag_cand.rglob("*.png"), key=lambda x: x.stat().st_mtime, reverse=True)[:120]
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
return ProjectArtifacts(
|
|
243
|
+
dir_output_proj=proj_out,
|
|
244
|
+
sqlite_dbs=sqlite_dbs,
|
|
245
|
+
outlook_dirs=outlook_dirs,
|
|
246
|
+
outlook_maps=outlook_maps[:120],
|
|
247
|
+
diagnostic_plots=diagnostic_plots[:120],
|
|
248
|
+
pdf_reports=pdf_reports,
|
|
249
|
+
csv_exports=csv_exports[:50],
|
|
250
|
+
agmet_images=agmet_images,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def inspect_sqlite_db(db_path: Path) -> dict[str, Any]:
|
|
255
|
+
"""Query prediction tables and summary accuracy metrics from an outlook/geocif SQLite DB."""
|
|
256
|
+
if not db_path.is_file():
|
|
257
|
+
return {"tables": [], "metrics": pd.DataFrame()}
|
|
258
|
+
|
|
259
|
+
system_tables = {
|
|
260
|
+
"country_metrics",
|
|
261
|
+
"regional_metrics",
|
|
262
|
+
"regional_metrics_by_year",
|
|
263
|
+
"shap_values",
|
|
264
|
+
"feature_importance",
|
|
265
|
+
"models",
|
|
266
|
+
"sqlite_master",
|
|
267
|
+
}
|
|
268
|
+
with sqlite3.connect(db_path) as con:
|
|
269
|
+
all_tables = pd.read_sql(
|
|
270
|
+
"SELECT name FROM sqlite_master WHERE type='table'", con
|
|
271
|
+
)["name"].tolist()
|
|
272
|
+
pred_tables = [
|
|
273
|
+
t for t in all_tables if t not in system_tables and not t.startswith("config_")
|
|
274
|
+
]
|
|
275
|
+
metrics_df = pd.DataFrame()
|
|
276
|
+
if "country_metrics" in all_tables:
|
|
277
|
+
try:
|
|
278
|
+
metrics_df = pd.read_sql('SELECT * FROM "country_metrics"', con)
|
|
279
|
+
except Exception:
|
|
280
|
+
pass
|
|
281
|
+
return {"tables": pred_tables, "metrics": metrics_df}
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def load_prediction_table(db_path: Path, table_name: str) -> pd.DataFrame:
|
|
285
|
+
"""Load rows from a single country_crop prediction table safely."""
|
|
286
|
+
with sqlite3.connect(db_path) as con:
|
|
287
|
+
valid = pd.read_sql(
|
|
288
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
|
|
289
|
+
con,
|
|
290
|
+
params=(table_name,),
|
|
291
|
+
)
|
|
292
|
+
if valid.empty:
|
|
293
|
+
return pd.DataFrame()
|
|
294
|
+
df = pd.read_sql(f'SELECT * FROM "{table_name}"', con)
|
|
295
|
+
return df
|