geochip 3.0.0__py3-none-any.whl
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.
- geochip/__init__.py +36 -0
- geochip/auth.py +273 -0
- geochip/cli.py +235 -0
- geochip/config.py +115 -0
- geochip/datasets.py +172 -0
- geochip/downloader.py +407 -0
- geochip/geometry.py +300 -0
- geochip/tiler.py +278 -0
- geochip/ui.py +376 -0
- geochip/uploader.py +205 -0
- geochip-3.0.0.dist-info/METADATA +229 -0
- geochip-3.0.0.dist-info/RECORD +16 -0
- geochip-3.0.0.dist-info/WHEEL +5 -0
- geochip-3.0.0.dist-info/entry_points.txt +3 -0
- geochip-3.0.0.dist-info/licenses/LICENSE +21 -0
- geochip-3.0.0.dist-info/top_level.txt +1 -0
geochip/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""
|
|
2
|
+
GeoChip CLI: Interactive Geospatial Earth Observation Pipeline & Roboflow Ingestion.
|
|
3
|
+
|
|
4
|
+
Download multi-sensor satellite imagery (Sentinel-2, Landsat 8/9, Sentinel-1 SAR, MODIS, SRTM DEM),
|
|
5
|
+
generate georeferenced image chips, and upload annotation batches to Roboflow.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "3.0.0"
|
|
9
|
+
|
|
10
|
+
from .auth import init_earth_engine, login_flow, test_all_connections, test_earth_engine_connection
|
|
11
|
+
from .datasets import COMPOSITE_METHODS, DATASETS
|
|
12
|
+
from .downloader import interactive_download_workflow, load_aoi_geometry
|
|
13
|
+
from .geometry import AOIData, estimate_download_size_mb, list_available_aois, load_aoi_data
|
|
14
|
+
from .tiler import CHIP_SIZES, create_single_raster_chips, interactive_chipping_workflow
|
|
15
|
+
from .uploader import interactive_upload_flow, upload_chips_to_roboflow
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"__version__",
|
|
19
|
+
"AOIData",
|
|
20
|
+
"CHIP_SIZES",
|
|
21
|
+
"COMPOSITE_METHODS",
|
|
22
|
+
"DATASETS",
|
|
23
|
+
"create_single_raster_chips",
|
|
24
|
+
"estimate_download_size_mb",
|
|
25
|
+
"init_earth_engine",
|
|
26
|
+
"interactive_chipping_workflow",
|
|
27
|
+
"interactive_download_workflow",
|
|
28
|
+
"interactive_upload_flow",
|
|
29
|
+
"list_available_aois",
|
|
30
|
+
"load_aoi_data",
|
|
31
|
+
"load_aoi_geometry",
|
|
32
|
+
"login_flow",
|
|
33
|
+
"test_all_connections",
|
|
34
|
+
"test_earth_engine_connection",
|
|
35
|
+
"upload_chips_to_roboflow",
|
|
36
|
+
]
|
geochip/auth.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Google Earth Engine & Roboflow Authentication and Credentials Management.
|
|
3
|
+
Provides interactive login, connection status checks, and masked credential setup.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .config import (
|
|
12
|
+
extract_roboflow_slug,
|
|
13
|
+
is_valid_credential_val,
|
|
14
|
+
load_app_env,
|
|
15
|
+
save_env_variable,
|
|
16
|
+
)
|
|
17
|
+
from .ui import (
|
|
18
|
+
print_error,
|
|
19
|
+
print_info,
|
|
20
|
+
print_step,
|
|
21
|
+
print_success,
|
|
22
|
+
print_warning,
|
|
23
|
+
prompt_confirm,
|
|
24
|
+
prompt_input,
|
|
25
|
+
prompt_secret,
|
|
26
|
+
select,
|
|
27
|
+
spinner,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
load_app_env()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_ee_project_id() -> str | None:
|
|
34
|
+
"""Retrieve the configured Earth Engine GCP project ID."""
|
|
35
|
+
val = os.getenv("EE_PROJECT_ID", "").strip()
|
|
36
|
+
return val if is_valid_credential_val(val) else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_connection_status() -> dict[str, bool]:
|
|
40
|
+
"""Perform a fast local check of Earth Engine and Roboflow credential readiness."""
|
|
41
|
+
ee_creds_file = Path.home() / ".config" / "earthengine" / "credentials"
|
|
42
|
+
gee_ready = ee_creds_file.is_file() or bool(get_ee_project_id())
|
|
43
|
+
|
|
44
|
+
rf_key = os.getenv("ROBOFLOW_API_KEY", "").strip()
|
|
45
|
+
rf_ws = os.getenv("ROBOFLOW_WORKSPACE", "").strip()
|
|
46
|
+
rf_proj = os.getenv("ROBOFLOW_PROJECT", "").strip()
|
|
47
|
+
roboflow_ready = (
|
|
48
|
+
is_valid_credential_val(rf_key)
|
|
49
|
+
and is_valid_credential_val(rf_ws)
|
|
50
|
+
and is_valid_credential_val(rf_proj)
|
|
51
|
+
)
|
|
52
|
+
return {"gee": gee_ready, "roboflow": roboflow_ready}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def init_earth_engine(project_id: str | None = None) -> bool:
|
|
56
|
+
"""Initialize Google Earth Engine using cached OAuth credentials."""
|
|
57
|
+
import ee
|
|
58
|
+
|
|
59
|
+
project_id = project_id or get_ee_project_id()
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
if project_id:
|
|
63
|
+
ee.Initialize(project=project_id)
|
|
64
|
+
print_info(f"Earth Engine initialized (Project: {project_id})")
|
|
65
|
+
else:
|
|
66
|
+
ee.Initialize()
|
|
67
|
+
print_info("Earth Engine initialized (Default Project)")
|
|
68
|
+
return True
|
|
69
|
+
except Exception as exc:
|
|
70
|
+
print_warning(f"Google Earth Engine is not authenticated: {exc}")
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def login_flow(project_id: str | None = None, work_dir: Path | None = None) -> bool:
|
|
75
|
+
"""Trigger browser OAuth authentication for Google Earth Engine."""
|
|
76
|
+
import ee
|
|
77
|
+
|
|
78
|
+
print_step("Google Earth Engine - Browser OAuth Login")
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
print_info("Opening browser for Google authentication...")
|
|
82
|
+
try:
|
|
83
|
+
ee.Authenticate()
|
|
84
|
+
except Exception:
|
|
85
|
+
print_info("Browser auto-open unavailable. Switching to verification-code flow...")
|
|
86
|
+
ee.Authenticate(auth_mode="notebook")
|
|
87
|
+
|
|
88
|
+
print_success("Authentication token saved to local credentials cache.")
|
|
89
|
+
|
|
90
|
+
current_proj = project_id if is_valid_credential_val(project_id) else get_ee_project_id()
|
|
91
|
+
print_info("\nEnter the Google Cloud Project ID linked to your Earth Engine account.")
|
|
92
|
+
print_info("Check your Project ID at: https://console.cloud.google.com/welcome\n")
|
|
93
|
+
project_id = prompt_input(
|
|
94
|
+
"GCP Project ID (e.g., my-gee-project-123)",
|
|
95
|
+
default=current_proj,
|
|
96
|
+
).strip()
|
|
97
|
+
|
|
98
|
+
if project_id:
|
|
99
|
+
save_env_variable("EE_PROJECT_ID", project_id, work_dir=work_dir)
|
|
100
|
+
print_success(f"Project ID '{project_id}' saved.")
|
|
101
|
+
|
|
102
|
+
with spinner("Verifying Earth Engine initialization..."):
|
|
103
|
+
if project_id:
|
|
104
|
+
ee.Initialize(project=project_id)
|
|
105
|
+
else:
|
|
106
|
+
ee.Initialize()
|
|
107
|
+
|
|
108
|
+
print_success("Google Earth Engine is ready to use.")
|
|
109
|
+
return True
|
|
110
|
+
|
|
111
|
+
except Exception as exc:
|
|
112
|
+
print_error(f"Login or initialization failed: {exc}")
|
|
113
|
+
err_str = str(exc).lower()
|
|
114
|
+
if "not registered" in err_str and project_id:
|
|
115
|
+
print_warning(f"\nProject '{project_id}' is not registered for Earth Engine yet:")
|
|
116
|
+
print_info(
|
|
117
|
+
f" 1. Open: https://console.cloud.google.com/earth-engine/configuration?project={project_id}"
|
|
118
|
+
)
|
|
119
|
+
print_info(
|
|
120
|
+
" 2. Select 'Unpaid / Noncommercial' (or your appropriate tier) and confirm."
|
|
121
|
+
)
|
|
122
|
+
else:
|
|
123
|
+
print_info(
|
|
124
|
+
f"Verify Earth Engine API is enabled: "
|
|
125
|
+
f"https://console.cloud.google.com/apis/library/earthengine.googleapis.com?project={project_id or ''}"
|
|
126
|
+
)
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def setup_roboflow_credentials(work_dir: Path | None = None) -> None:
|
|
131
|
+
"""Interactive Roboflow API credentials setup with masked secret input."""
|
|
132
|
+
load_app_env(work_dir)
|
|
133
|
+
print_step("Roboflow Credentials Setup")
|
|
134
|
+
|
|
135
|
+
raw_key = os.getenv("ROBOFLOW_API_KEY", "").strip()
|
|
136
|
+
raw_ws = os.getenv("ROBOFLOW_WORKSPACE", "").strip()
|
|
137
|
+
raw_proj = os.getenv("ROBOFLOW_PROJECT", "").strip()
|
|
138
|
+
|
|
139
|
+
current_key = raw_key if is_valid_credential_val(raw_key) else None
|
|
140
|
+
current_ws = raw_ws if is_valid_credential_val(raw_ws) else None
|
|
141
|
+
current_proj = raw_proj if is_valid_credential_val(raw_proj) else None
|
|
142
|
+
|
|
143
|
+
print_info("How to find your Roboflow credentials:")
|
|
144
|
+
print_info(" 1. Private API Key : app.roboflow.com -> Settings -> Roboflow API")
|
|
145
|
+
print_info(" 2. Workspace Slug : app.roboflow.com/<workspace-slug>")
|
|
146
|
+
print_info(" 3. Project ID : app.roboflow.com/<workspace-slug>/<project-id>\n")
|
|
147
|
+
|
|
148
|
+
api_key = prompt_secret("Roboflow Private API Key", existing_value=current_key)
|
|
149
|
+
raw_workspace = prompt_input("Roboflow Workspace ID / Slug", default=current_ws)
|
|
150
|
+
raw_project = prompt_input("Target Roboflow Project ID", default=current_proj)
|
|
151
|
+
|
|
152
|
+
workspace = extract_roboflow_slug(raw_workspace)
|
|
153
|
+
project = extract_roboflow_slug(raw_project)
|
|
154
|
+
|
|
155
|
+
if raw_workspace and raw_workspace.strip() != workspace:
|
|
156
|
+
print_info(f"Cleaned Workspace URL to slug: '{workspace}'")
|
|
157
|
+
if raw_project and raw_project.strip() != project:
|
|
158
|
+
print_info(f"Cleaned Project URL to slug: '{project}'")
|
|
159
|
+
|
|
160
|
+
if api_key:
|
|
161
|
+
save_env_variable("ROBOFLOW_API_KEY", api_key, work_dir=work_dir)
|
|
162
|
+
if workspace:
|
|
163
|
+
save_env_variable("ROBOFLOW_WORKSPACE", workspace, work_dir=work_dir)
|
|
164
|
+
if project:
|
|
165
|
+
save_env_variable("ROBOFLOW_PROJECT", project, work_dir=work_dir)
|
|
166
|
+
|
|
167
|
+
print_success("Roboflow credentials saved.")
|
|
168
|
+
|
|
169
|
+
if (
|
|
170
|
+
api_key
|
|
171
|
+
and workspace
|
|
172
|
+
and project
|
|
173
|
+
and prompt_confirm("Test Roboflow connection now?", default=True)
|
|
174
|
+
):
|
|
175
|
+
try:
|
|
176
|
+
with spinner("Connecting to Roboflow..."):
|
|
177
|
+
from roboflow import Roboflow
|
|
178
|
+
|
|
179
|
+
rf = Roboflow(api_key=api_key)
|
|
180
|
+
proj_obj = rf.workspace(workspace).project(project)
|
|
181
|
+
print_success(
|
|
182
|
+
f"Connected to Roboflow project '{workspace}/{project}' ({proj_obj.name})."
|
|
183
|
+
)
|
|
184
|
+
except Exception as exc:
|
|
185
|
+
print_error(f"Could not connect to Roboflow: {exc}")
|
|
186
|
+
print_warning("Verify your API key and workspace/project slug.")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def test_all_connections(work_dir: Path | None = None) -> None:
|
|
190
|
+
"""Run a live diagnostic test for Google Earth Engine and Roboflow."""
|
|
191
|
+
load_app_env(work_dir)
|
|
192
|
+
print_step("Diagnostic Connection Test")
|
|
193
|
+
|
|
194
|
+
print_info("Testing Google Earth Engine...")
|
|
195
|
+
if init_earth_engine():
|
|
196
|
+
try:
|
|
197
|
+
with spinner("Running Earth Engine compute check..."):
|
|
198
|
+
import ee
|
|
199
|
+
|
|
200
|
+
test_val = ee.Number(42).getInfo()
|
|
201
|
+
print_success(f"Earth Engine compute check passed (Result: {test_val}).")
|
|
202
|
+
except Exception as exc:
|
|
203
|
+
print_error(f"Earth Engine compute failed: {exc}")
|
|
204
|
+
else:
|
|
205
|
+
print_error("Earth Engine connection failed. Run Google Earth Engine Login.")
|
|
206
|
+
|
|
207
|
+
print("\n" + "-" * 40)
|
|
208
|
+
print_info("Testing Roboflow credentials...")
|
|
209
|
+
rf_key = os.getenv("ROBOFLOW_API_KEY", "").strip()
|
|
210
|
+
rf_ws = extract_roboflow_slug(os.getenv("ROBOFLOW_WORKSPACE", ""))
|
|
211
|
+
rf_proj = extract_roboflow_slug(os.getenv("ROBOFLOW_PROJECT", ""))
|
|
212
|
+
|
|
213
|
+
if not (is_valid_credential_val(rf_key) and rf_ws and rf_proj):
|
|
214
|
+
print_warning(
|
|
215
|
+
"Roboflow credentials are not configured yet (optional for local-only chipping)."
|
|
216
|
+
)
|
|
217
|
+
else:
|
|
218
|
+
try:
|
|
219
|
+
with spinner("Connecting to Roboflow..."):
|
|
220
|
+
from roboflow import Roboflow
|
|
221
|
+
|
|
222
|
+
rf = Roboflow(api_key=rf_key)
|
|
223
|
+
rf.workspace(rf_ws).project(rf_proj)
|
|
224
|
+
print_success(f"Roboflow verified: '{rf_ws}/{rf_proj}'.")
|
|
225
|
+
except Exception as exc:
|
|
226
|
+
print_error(f"Roboflow check failed: {exc}")
|
|
227
|
+
|
|
228
|
+
print("\n" + "=" * 60)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
test_earth_engine_connection = test_all_connections
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def interactive_auth_menu(work_dir: Path | None = None) -> None:
|
|
235
|
+
"""Interactive authentication and credentials submenu."""
|
|
236
|
+
print_step("Credentials & Authentication Setup")
|
|
237
|
+
|
|
238
|
+
auth_choices = [
|
|
239
|
+
{
|
|
240
|
+
"name": "🌐 Google Earth Engine Login (Browser OAuth)",
|
|
241
|
+
"desc": "Sign in with Google via browser and set your GCP Project ID",
|
|
242
|
+
"action": "gee",
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
"name": "🤖 Setup Roboflow API Credentials",
|
|
246
|
+
"desc": "Configure Private API Key, Workspace Slug, and Target Project ID",
|
|
247
|
+
"action": "roboflow",
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
"name": "🔍 Test Connections & Diagnostic Status",
|
|
251
|
+
"desc": "Verify live connectivity to Google Earth Engine and Roboflow",
|
|
252
|
+
"action": "test",
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
"name": "⬅️ Back to Main Menu",
|
|
256
|
+
"desc": "Return to the main GeoChip CLI menu",
|
|
257
|
+
"action": "back",
|
|
258
|
+
},
|
|
259
|
+
]
|
|
260
|
+
|
|
261
|
+
while True:
|
|
262
|
+
idx = select("Select Authentication Action:", auth_choices, default_index=0)
|
|
263
|
+
action = auth_choices[idx]["action"]
|
|
264
|
+
|
|
265
|
+
if action == "gee":
|
|
266
|
+
login_flow(work_dir=work_dir)
|
|
267
|
+
elif action == "roboflow":
|
|
268
|
+
setup_roboflow_credentials(work_dir=work_dir)
|
|
269
|
+
elif action == "test":
|
|
270
|
+
test_all_connections(work_dir=work_dir)
|
|
271
|
+
elif action == "back":
|
|
272
|
+
break
|
|
273
|
+
print("\n")
|
geochip/cli.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""
|
|
2
|
+
GeoChip CLI Controller.
|
|
3
|
+
Provides the interactive GeoChip menu and standard subcommand execution.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .auth import (
|
|
14
|
+
get_connection_status,
|
|
15
|
+
interactive_auth_menu,
|
|
16
|
+
login_flow,
|
|
17
|
+
setup_roboflow_credentials,
|
|
18
|
+
)
|
|
19
|
+
from .config import ensure_workspace_dirs, load_app_env, resolve_work_dir
|
|
20
|
+
from .downloader import interactive_download_workflow
|
|
21
|
+
from .tiler import create_single_raster_chips, interactive_chipping_workflow
|
|
22
|
+
from .ui import (
|
|
23
|
+
print_banner,
|
|
24
|
+
print_error,
|
|
25
|
+
print_info,
|
|
26
|
+
print_status_bar,
|
|
27
|
+
print_warning,
|
|
28
|
+
select,
|
|
29
|
+
)
|
|
30
|
+
from .uploader import interactive_upload_flow, upload_chips_to_roboflow
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def interactive_main_menu(work_dir: Path | None = None) -> None:
|
|
34
|
+
"""Main interactive terminal loop for GeoChip CLI."""
|
|
35
|
+
ws = resolve_work_dir(work_dir)
|
|
36
|
+
load_app_env(ws)
|
|
37
|
+
ensure_workspace_dirs(ws)
|
|
38
|
+
|
|
39
|
+
print_banner()
|
|
40
|
+
|
|
41
|
+
main_menu_choices = [
|
|
42
|
+
{
|
|
43
|
+
"name": "🚀 Quick Start: Full Pipeline (Download -> Chip -> Upload)",
|
|
44
|
+
"desc": "Guided end-to-end flow from AOI imagery download to Roboflow upload",
|
|
45
|
+
"action": "quickstart",
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"name": "📥 Step 1: Download Satellite Imagery (Earth Engine)",
|
|
49
|
+
"desc": "Select AOI (.shp / .geojson), Dataset, Date Range, Cloud Filter, Single/Composite",
|
|
50
|
+
"action": "download",
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"name": "✂️ Step 2: Chipping & Upload to Roboflow",
|
|
54
|
+
"desc": "Slice Raw Raster into Chips (160/320/640/1280 px), Task Batches, Roboflow Upload",
|
|
55
|
+
"action": "chip",
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"name": "🔑 Setup Credentials & Authentication",
|
|
59
|
+
"desc": "Configure Google Earth Engine OAuth and Roboflow API credentials",
|
|
60
|
+
"action": "auth",
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
"name": "❌ Exit",
|
|
64
|
+
"desc": "Exit GeoChip CLI",
|
|
65
|
+
"action": "exit",
|
|
66
|
+
},
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
while True:
|
|
70
|
+
status = get_connection_status()
|
|
71
|
+
print_status_bar(gee_ready=status["gee"], roboflow_ready=status["roboflow"], work_dir=ws)
|
|
72
|
+
|
|
73
|
+
idx = select("Select Action to Execute:", main_menu_choices, default_index=0)
|
|
74
|
+
action = main_menu_choices[idx]["action"]
|
|
75
|
+
|
|
76
|
+
if action == "quickstart":
|
|
77
|
+
try:
|
|
78
|
+
raster_path = interactive_download_workflow(work_dir=ws)
|
|
79
|
+
if raster_path:
|
|
80
|
+
interactive_chipping_workflow(work_dir=ws, preselected_raster=raster_path)
|
|
81
|
+
except KeyboardInterrupt:
|
|
82
|
+
print_warning("\nQuick Start pipeline cancelled by user.")
|
|
83
|
+
except Exception as exc:
|
|
84
|
+
print_error(f"\nError during Quick Start pipeline: {exc}")
|
|
85
|
+
|
|
86
|
+
elif action == "download":
|
|
87
|
+
try:
|
|
88
|
+
interactive_download_workflow(work_dir=ws)
|
|
89
|
+
except KeyboardInterrupt:
|
|
90
|
+
print_warning("\nDownload workflow cancelled by user.")
|
|
91
|
+
except Exception as exc:
|
|
92
|
+
print_error(f"\nError during download: {exc}")
|
|
93
|
+
|
|
94
|
+
elif action == "chip":
|
|
95
|
+
try:
|
|
96
|
+
interactive_chipping_workflow(work_dir=ws)
|
|
97
|
+
except KeyboardInterrupt:
|
|
98
|
+
print_warning("\nChipping workflow cancelled by user.")
|
|
99
|
+
except Exception as exc:
|
|
100
|
+
print_error(f"\nError during chipping: {exc}")
|
|
101
|
+
|
|
102
|
+
elif action == "auth":
|
|
103
|
+
try:
|
|
104
|
+
interactive_auth_menu(work_dir=ws)
|
|
105
|
+
except KeyboardInterrupt:
|
|
106
|
+
print_warning("\nAuthentication setup cancelled by user.")
|
|
107
|
+
except Exception as exc:
|
|
108
|
+
print_error(f"\nError during authentication setup: {exc}")
|
|
109
|
+
|
|
110
|
+
elif action == "exit":
|
|
111
|
+
print_info("Thank you for using GeoChip CLI. Goodbye!")
|
|
112
|
+
sys.exit(0)
|
|
113
|
+
|
|
114
|
+
print("\n" + "-" * 60)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
118
|
+
"""Construct the top-level ArgumentParser for GeoChip CLI."""
|
|
119
|
+
parser = argparse.ArgumentParser(
|
|
120
|
+
prog="GeoChip",
|
|
121
|
+
description="GeoChip CLI: Interactive satellite imagery ingestion, raster chipping, and Roboflow pipeline.",
|
|
122
|
+
)
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
"--version",
|
|
125
|
+
action="version",
|
|
126
|
+
version=f"GeoChip CLI {__version__}",
|
|
127
|
+
)
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--work-dir",
|
|
130
|
+
type=str,
|
|
131
|
+
default=None,
|
|
132
|
+
help="Workspace directory containing data/aoi, data/raw, and data/chips (default: current directory)",
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
|
136
|
+
|
|
137
|
+
auth_parser = subparsers.add_parser("auth", help="Manage Earth Engine and Roboflow credentials")
|
|
138
|
+
auth_parser.add_argument(
|
|
139
|
+
"--login", action="store_true", help="Launch browser OAuth login for Earth Engine"
|
|
140
|
+
)
|
|
141
|
+
auth_parser.add_argument("--project", type=str, default=None, help="Google Cloud Project ID")
|
|
142
|
+
auth_parser.add_argument(
|
|
143
|
+
"--roboflow", action="store_true", help="Configure Roboflow credentials"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
dl_parser = subparsers.add_parser(
|
|
147
|
+
"download", help="Download satellite rasters from Google Earth Engine"
|
|
148
|
+
)
|
|
149
|
+
dl_parser.add_argument(
|
|
150
|
+
"--interactive", action="store_true", help="Launch interactive download UI"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
chip_parser = subparsers.add_parser(
|
|
154
|
+
"chip", help="Slice GeoTIFF raster into chip tiles & manifest.json"
|
|
155
|
+
)
|
|
156
|
+
chip_parser.add_argument(
|
|
157
|
+
"--raster", type=str, default=None, help="Path to input GeoTIFF raster"
|
|
158
|
+
)
|
|
159
|
+
chip_parser.add_argument(
|
|
160
|
+
"--chip-size",
|
|
161
|
+
type=int,
|
|
162
|
+
default=640,
|
|
163
|
+
choices=[160, 320, 640, 1280],
|
|
164
|
+
help="Chip tile size in pixels",
|
|
165
|
+
)
|
|
166
|
+
chip_parser.add_argument(
|
|
167
|
+
"--chips-per-task", type=int, default=5, help="Number of chips per task batch"
|
|
168
|
+
)
|
|
169
|
+
chip_parser.add_argument(
|
|
170
|
+
"--output-dir", type=str, default=None, help="Output base directory for chips"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
upload_parser = subparsers.add_parser("upload", help="Upload task batches to Roboflow")
|
|
174
|
+
upload_parser.add_argument(
|
|
175
|
+
"--chips-dir", type=str, default=None, help="Directory containing chip tasks"
|
|
176
|
+
)
|
|
177
|
+
upload_parser.add_argument("--api-key", type=str, default=None, help="Roboflow Private API Key")
|
|
178
|
+
upload_parser.add_argument(
|
|
179
|
+
"--workspace", type=str, default=None, help="Roboflow Workspace Slug"
|
|
180
|
+
)
|
|
181
|
+
upload_parser.add_argument("--project", type=str, default=None, help="Roboflow Project ID")
|
|
182
|
+
upload_parser.add_argument("--task", type=str, default="all", help="Task folder name or 'all'")
|
|
183
|
+
|
|
184
|
+
return parser
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def main() -> None:
|
|
188
|
+
"""Main CLI entry point supporting interactive menu and subcommands."""
|
|
189
|
+
parser = build_parser()
|
|
190
|
+
args = parser.parse_args()
|
|
191
|
+
ws = resolve_work_dir(args.work_dir)
|
|
192
|
+
load_app_env(ws)
|
|
193
|
+
|
|
194
|
+
if not args.command:
|
|
195
|
+
interactive_main_menu(work_dir=ws)
|
|
196
|
+
return
|
|
197
|
+
|
|
198
|
+
if args.command == "auth":
|
|
199
|
+
if args.login:
|
|
200
|
+
login_flow(project_id=args.project, work_dir=ws)
|
|
201
|
+
elif args.roboflow:
|
|
202
|
+
setup_roboflow_credentials(work_dir=ws)
|
|
203
|
+
else:
|
|
204
|
+
interactive_auth_menu(work_dir=ws)
|
|
205
|
+
|
|
206
|
+
elif args.command == "download":
|
|
207
|
+
interactive_download_workflow(work_dir=ws)
|
|
208
|
+
|
|
209
|
+
elif args.command == "chip":
|
|
210
|
+
if args.raster:
|
|
211
|
+
out_base = args.output_dir or str(ws / "data" / "chips")
|
|
212
|
+
create_single_raster_chips(
|
|
213
|
+
raster_path=args.raster,
|
|
214
|
+
output_base=out_base,
|
|
215
|
+
chip_size=args.chip_size,
|
|
216
|
+
chips_per_task=args.chips_per_task,
|
|
217
|
+
)
|
|
218
|
+
else:
|
|
219
|
+
interactive_chipping_workflow(work_dir=ws)
|
|
220
|
+
|
|
221
|
+
elif args.command == "upload":
|
|
222
|
+
if args.chips_dir:
|
|
223
|
+
upload_chips_to_roboflow(
|
|
224
|
+
chips_dir=args.chips_dir,
|
|
225
|
+
api_key=args.api_key,
|
|
226
|
+
workspace_id=args.workspace,
|
|
227
|
+
project_id=args.project,
|
|
228
|
+
task_name=args.task,
|
|
229
|
+
)
|
|
230
|
+
else:
|
|
231
|
+
interactive_upload_flow(work_dir=ws)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
if __name__ == "__main__":
|
|
235
|
+
main()
|
geochip/config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""
|
|
2
|
+
GeoChip Configuration and Credentials Management.
|
|
3
|
+
Centralizes global credentials (~/.config/geochip/.env), workspace directory resolution,
|
|
4
|
+
secret masking, and Roboflow slug parsing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from urllib.parse import urlparse
|
|
13
|
+
|
|
14
|
+
from dotenv import load_dotenv
|
|
15
|
+
|
|
16
|
+
GLOBAL_CONFIG_DIR = Path.home() / ".config" / "geochip"
|
|
17
|
+
GLOBAL_ENV_FILE = GLOBAL_CONFIG_DIR / ".env"
|
|
18
|
+
|
|
19
|
+
DUMMY_PLACEHOLDERS = {
|
|
20
|
+
"your_gcp_project_id",
|
|
21
|
+
"your_private_api_key_here",
|
|
22
|
+
"your_workspace_id",
|
|
23
|
+
"your_project_id",
|
|
24
|
+
"none",
|
|
25
|
+
"null",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_valid_credential_val(val: str | None) -> bool:
|
|
30
|
+
"""Return True if value is a real credential rather than an empty or placeholder string."""
|
|
31
|
+
if not val:
|
|
32
|
+
return False
|
|
33
|
+
val_clean = str(val).strip().lower()
|
|
34
|
+
return (
|
|
35
|
+
bool(val_clean)
|
|
36
|
+
and val_clean not in DUMMY_PLACEHOLDERS
|
|
37
|
+
and not val_clean.startswith("your_")
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def mask_secret(secret: str | None) -> str:
|
|
42
|
+
"""Mask an API key or secret so raw values are never echoed to the terminal."""
|
|
43
|
+
if not secret:
|
|
44
|
+
return ""
|
|
45
|
+
cleaned = str(secret).strip()
|
|
46
|
+
if len(cleaned) <= 8:
|
|
47
|
+
return "****"
|
|
48
|
+
return f"{cleaned[:4]}****{cleaned[-4:]}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def extract_roboflow_slug(val: str | None) -> str:
|
|
52
|
+
"""Clean a full Roboflow URL or path into a bare workspace/project slug."""
|
|
53
|
+
if not val:
|
|
54
|
+
return ""
|
|
55
|
+
cleaned = str(val).strip().rstrip("/")
|
|
56
|
+
if "://" in cleaned:
|
|
57
|
+
cleaned = urlparse(cleaned).path.strip("/")
|
|
58
|
+
if "/" in cleaned:
|
|
59
|
+
cleaned = cleaned.split("/")[-1]
|
|
60
|
+
return cleaned.strip()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def resolve_work_dir(work_dir: str | Path | None = None) -> Path:
|
|
64
|
+
"""Resolve the active GeoChip workspace root directory."""
|
|
65
|
+
if work_dir is not None:
|
|
66
|
+
return Path(work_dir).expanduser().resolve()
|
|
67
|
+
return Path.cwd().resolve()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def ensure_workspace_dirs(work_dir: Path) -> dict[str, Path]:
|
|
71
|
+
"""Ensure data/aoi, data/raw, and data/chips exist inside the workspace."""
|
|
72
|
+
dirs = {
|
|
73
|
+
"aoi": work_dir / "data" / "aoi",
|
|
74
|
+
"raw": work_dir / "data" / "raw",
|
|
75
|
+
"chips": work_dir / "data" / "chips",
|
|
76
|
+
}
|
|
77
|
+
for d in dirs.values():
|
|
78
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
return dirs
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def load_app_env(work_dir: Path | None = None) -> None:
|
|
83
|
+
"""Load environment variables from local .env (highest priority) and global config."""
|
|
84
|
+
ws = resolve_work_dir(work_dir)
|
|
85
|
+
candidates = [ws / ".env", ws / "data" / ".env", GLOBAL_ENV_FILE]
|
|
86
|
+
for env_path in candidates:
|
|
87
|
+
if env_path.is_file():
|
|
88
|
+
load_dotenv(dotenv_path=str(env_path), override=False)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def save_env_variable(key: str, value: str, work_dir: Path | None = None) -> Path:
|
|
92
|
+
"""Persist an environment variable to global config (and existing local .env if present)."""
|
|
93
|
+
GLOBAL_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
targets = [GLOBAL_ENV_FILE]
|
|
95
|
+
|
|
96
|
+
if work_dir is not None:
|
|
97
|
+
local_env = resolve_work_dir(work_dir) / ".env"
|
|
98
|
+
if local_env.is_file():
|
|
99
|
+
targets.append(local_env)
|
|
100
|
+
|
|
101
|
+
for env_file in targets:
|
|
102
|
+
env_file.parent.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
lines: list[str] = []
|
|
104
|
+
if env_file.is_file():
|
|
105
|
+
for line in env_file.read_text(encoding="utf-8").splitlines():
|
|
106
|
+
if not line.startswith(f"{key}="):
|
|
107
|
+
lines.append(line)
|
|
108
|
+
lines.append(f"{key}={value}")
|
|
109
|
+
env_file.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
110
|
+
if os.name != "nt":
|
|
111
|
+
with contextlib.suppress(OSError):
|
|
112
|
+
env_file.chmod(0o600)
|
|
113
|
+
|
|
114
|
+
os.environ[key] = str(value)
|
|
115
|
+
return GLOBAL_ENV_FILE
|