prisma-sat 0.1.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.
- prisma_pilot/__init__.py +33 -0
- prisma_pilot/auth.py +260 -0
- prisma_pilot/cli.py +314 -0
- prisma_pilot/config.py +63 -0
- prisma_pilot/downloader.py +339 -0
- prisma_pilot/search.py +373 -0
- prisma_sat/__init__.py +42 -0
- prisma_sat/cli.py +11 -0
- prisma_sat-0.1.0.dist-info/METADATA +341 -0
- prisma_sat-0.1.0.dist-info/RECORD +13 -0
- prisma_sat-0.1.0.dist-info/WHEEL +5 -0
- prisma_sat-0.1.0.dist-info/entry_points.txt +4 -0
- prisma_sat-0.1.0.dist-info/top_level.txt +2 -0
prisma_pilot/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PRISMA Pilot Toolkit
|
|
3
|
+
====================
|
|
4
|
+
Standalone pilot for ASI PRISMA Hyperspectral Satellite data:
|
|
5
|
+
- Authentication & Session Management (WSO2 OAuth2 & Session Caching)
|
|
6
|
+
- Spatial AOI Parsing (GeoJSON files/dicts and Bounding Box arrays/strings)
|
|
7
|
+
- Solr Spatial Catalog Discovery
|
|
8
|
+
- Resilient streaming download pipeline with Range resumption and HDF5 extraction
|
|
9
|
+
- Processing order dispatch and order history tracking
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from prisma_pilot.config import config
|
|
13
|
+
from prisma_pilot.auth import get_authenticated_session, verify_session, ensure_authorized
|
|
14
|
+
from prisma_pilot.search import AOI, parse_aoi, search_prisma, get_user_orders
|
|
15
|
+
from prisma_pilot.downloader import download_product, download_stream, order_processing, validate_file_integrity, extract_prisma_archive
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
__all__ = [
|
|
19
|
+
"config",
|
|
20
|
+
"get_authenticated_session",
|
|
21
|
+
"verify_session",
|
|
22
|
+
"ensure_authorized",
|
|
23
|
+
"AOI",
|
|
24
|
+
"parse_aoi",
|
|
25
|
+
"search_prisma",
|
|
26
|
+
"get_user_orders",
|
|
27
|
+
"download_product",
|
|
28
|
+
"download_stream",
|
|
29
|
+
"order_processing",
|
|
30
|
+
"validate_file_integrity",
|
|
31
|
+
"extract_prisma_archive",
|
|
32
|
+
]
|
|
33
|
+
|
prisma_pilot/auth.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PRISMA Authentication & Session Management
|
|
3
|
+
===========================================
|
|
4
|
+
Handles WSO2 Identity Server authentication, OAuth2 consent, and cookie persistence.
|
|
5
|
+
Supports cached session reuse and automated headless Chrome CDP fallback.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import subprocess
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from urllib.parse import urljoin
|
|
18
|
+
import requests
|
|
19
|
+
|
|
20
|
+
from prisma_pilot.config import config, CACHE_DIR, SESSION_FILE
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("prisma_pilot.auth")
|
|
23
|
+
if not logger.handlers:
|
|
24
|
+
handler = logging.StreamHandler()
|
|
25
|
+
handler.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
|
|
26
|
+
logger.addHandler(handler)
|
|
27
|
+
logger.setLevel(logging.INFO)
|
|
28
|
+
|
|
29
|
+
DOCS_CHECK_URL = "https://prisma.asi.it/missionselect/docs.php"
|
|
30
|
+
CATALOG_CLIENT_URL = "https://prisma.asi.it/js-cat-client-prisma-src/"
|
|
31
|
+
MISSIONSELECT_URL = "https://prisma.asi.it/missionselect/"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def create_base_session(cookies: dict[str, str] | None = None) -> requests.Session:
|
|
35
|
+
"""Create a configured requests.Session with standard browser headers and cookies."""
|
|
36
|
+
session = requests.Session()
|
|
37
|
+
session.headers.update({
|
|
38
|
+
"User-Agent": (
|
|
39
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
40
|
+
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
|
41
|
+
),
|
|
42
|
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,application/json,*/*;q=0.8",
|
|
43
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
44
|
+
})
|
|
45
|
+
if cookies:
|
|
46
|
+
for name, value in cookies.items():
|
|
47
|
+
session.cookies.set(name, value, domain="prisma.asi.it", path="/")
|
|
48
|
+
return session
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def ensure_authorized(session: requests.Session, target_url: str) -> bool:
|
|
52
|
+
"""
|
|
53
|
+
Follows OAuth 302 redirect chains to exchange authorization codes and establish
|
|
54
|
+
session cookies (such as pastr-*). Rewrites any internal http:// redirects to https://
|
|
55
|
+
to ensure Secure-flagged cookies are not dropped by the client.
|
|
56
|
+
Returns True if target_url resolved successfully (HTTP 200) without redirecting to login.do.
|
|
57
|
+
"""
|
|
58
|
+
curr_url = target_url
|
|
59
|
+
for _ in range(6):
|
|
60
|
+
try:
|
|
61
|
+
r = session.get(curr_url, allow_redirects=False, timeout=15)
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logger.debug(f"Error checking authorization at {curr_url}: {e}")
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
if r.status_code in (301, 302, 303, 307):
|
|
67
|
+
loc = r.headers.get("Location")
|
|
68
|
+
if not loc:
|
|
69
|
+
break
|
|
70
|
+
if "login.do" in loc:
|
|
71
|
+
return False
|
|
72
|
+
# Upgrade redirect URL to https if server sent http
|
|
73
|
+
if loc.startswith("http://prisma.asi.it"):
|
|
74
|
+
loc = "https://prisma.asi.it" + loc[20:]
|
|
75
|
+
elif loc.startswith("http://"):
|
|
76
|
+
loc = "https://" + loc[7:]
|
|
77
|
+
curr_url = urljoin(curr_url, loc)
|
|
78
|
+
elif r.status_code == 200:
|
|
79
|
+
if "login.do" in curr_url or "loginForm" in r.text[:2000]:
|
|
80
|
+
return False
|
|
81
|
+
return True
|
|
82
|
+
else:
|
|
83
|
+
return False
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def verify_session(session: requests.Session) -> bool:
|
|
88
|
+
"""
|
|
89
|
+
Verify whether the current session cookies are authenticated and active.
|
|
90
|
+
Validates by ensuring access to both missionselect and catalog services.
|
|
91
|
+
"""
|
|
92
|
+
return ensure_authorized(session, DOCS_CHECK_URL) and ensure_authorized(session, CATALOG_CLIENT_URL)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def load_cached_session() -> dict[str, str] | None:
|
|
96
|
+
"""Load cached session cookies from disk if available."""
|
|
97
|
+
if config.phpsessid:
|
|
98
|
+
return {"PHPSESSID": config.phpsessid}
|
|
99
|
+
|
|
100
|
+
if SESSION_FILE.exists():
|
|
101
|
+
try:
|
|
102
|
+
with open(SESSION_FILE, "r") as f:
|
|
103
|
+
data = json.load(f)
|
|
104
|
+
if isinstance(data, dict) and "PHPSESSID" in data:
|
|
105
|
+
return data
|
|
106
|
+
except Exception as e:
|
|
107
|
+
logger.debug(f"Failed to read session file: {e}")
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def save_cached_session(cookies: dict[str, str]) -> None:
|
|
112
|
+
"""Persist session cookies to session.json."""
|
|
113
|
+
SESSION_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
with open(SESSION_FILE, "w") as f:
|
|
115
|
+
json.dump(cookies, f, indent=2)
|
|
116
|
+
logger.info(f"Saved active session cookies to {SESSION_FILE}")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def _run_chrome_cdp_login(username: str, password: str, port: int = 9222) -> dict[str, str]:
|
|
120
|
+
"""Automates headless Chrome CDP to submit credentials and extract session cookies."""
|
|
121
|
+
import shutil
|
|
122
|
+
import tempfile
|
|
123
|
+
import websockets
|
|
124
|
+
|
|
125
|
+
# Clean up any orphan chrome test processes
|
|
126
|
+
subprocess.run(
|
|
127
|
+
["pkill", "-f", f"remote-debugging-port={port}"],
|
|
128
|
+
stdout=subprocess.DEVNULL,
|
|
129
|
+
stderr=subprocess.DEVNULL,
|
|
130
|
+
)
|
|
131
|
+
time.sleep(1)
|
|
132
|
+
|
|
133
|
+
user_data_dir = tempfile.mkdtemp(prefix="chrome_prisma_")
|
|
134
|
+
chrome_proc = subprocess.Popen([
|
|
135
|
+
"google-chrome",
|
|
136
|
+
"--headless=new",
|
|
137
|
+
"--disable-gpu",
|
|
138
|
+
f"--remote-debugging-port={port}",
|
|
139
|
+
f"--user-data-dir={user_data_dir}",
|
|
140
|
+
"https://prisma.asi.it/missionselect/",
|
|
141
|
+
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
142
|
+
|
|
143
|
+
time.sleep(2)
|
|
144
|
+
try:
|
|
145
|
+
tabs = requests.get(f"http://localhost:{port}/json", timeout=5).json()
|
|
146
|
+
pages = [t for t in tabs if t.get("type") == "page"]
|
|
147
|
+
if not pages:
|
|
148
|
+
raise RuntimeError("No active page tab found in Chrome")
|
|
149
|
+
ws_url = pages[0].get("webSocketDebuggerUrl")
|
|
150
|
+
if not ws_url:
|
|
151
|
+
raise RuntimeError("Failed to obtain Chrome CDP WebSocket URL")
|
|
152
|
+
|
|
153
|
+
async with websockets.connect(ws_url) as ws:
|
|
154
|
+
msg_id = 1
|
|
155
|
+
|
|
156
|
+
async def cmd(method: str, params: dict | None = None) -> dict:
|
|
157
|
+
nonlocal msg_id
|
|
158
|
+
cid = msg_id
|
|
159
|
+
msg_id += 1
|
|
160
|
+
await ws.send(json.dumps({"id": cid, "method": method, "params": params or {}}))
|
|
161
|
+
while True:
|
|
162
|
+
raw = await ws.recv()
|
|
163
|
+
data = json.loads(raw)
|
|
164
|
+
if data.get("id") == cid:
|
|
165
|
+
return data.get("result", {})
|
|
166
|
+
|
|
167
|
+
await cmd("Page.enable")
|
|
168
|
+
await cmd("Network.enable")
|
|
169
|
+
logger.info("Connecting to PRISMA login page via Chrome CDP...")
|
|
170
|
+
|
|
171
|
+
submitted = False
|
|
172
|
+
approved = False
|
|
173
|
+
reached_portal = False
|
|
174
|
+
|
|
175
|
+
for _ in range(35):
|
|
176
|
+
await asyncio.sleep(1)
|
|
177
|
+
curr_url = (await cmd("Runtime.evaluate", {"expression": "window.location.href"})).get("result", {}).get("value", "")
|
|
178
|
+
if "login.do" in curr_url and not submitted:
|
|
179
|
+
logger.info("Submitting login credentials to WSO2 Identity Server...")
|
|
180
|
+
js_fill = f"""
|
|
181
|
+
document.getElementById('username').value = {json.dumps(username)};
|
|
182
|
+
document.getElementById('password').value = {json.dumps(password)};
|
|
183
|
+
document.getElementById('loginForm').submit();
|
|
184
|
+
"""
|
|
185
|
+
await cmd("Runtime.evaluate", {"expression": js_fill})
|
|
186
|
+
submitted = True
|
|
187
|
+
elif "oauth2_consent.do" in curr_url and not approved:
|
|
188
|
+
logger.info("Approving OAuth consent dialog...")
|
|
189
|
+
await cmd("Runtime.evaluate", {"expression": "approvedAlways()"})
|
|
190
|
+
approved = True
|
|
191
|
+
elif "missionselect" in curr_url and "login.do" not in curr_url and submitted:
|
|
192
|
+
logger.info("Successfully reached PRISMA portal in browser.")
|
|
193
|
+
reached_portal = True
|
|
194
|
+
break
|
|
195
|
+
|
|
196
|
+
if not reached_portal:
|
|
197
|
+
raise RuntimeError(f"Chrome login timed out waiting for redirect to PRISMA portal. Final URL: {curr_url}")
|
|
198
|
+
|
|
199
|
+
# Extract cookies for prisma.asi.it
|
|
200
|
+
cookies_res = await cmd("Network.getCookies", {
|
|
201
|
+
"urls": ["https://prisma.asi.it", "http://prisma.asi.it"]
|
|
202
|
+
})
|
|
203
|
+
cookie_dict = {}
|
|
204
|
+
for c in cookies_res.get("cookies", []):
|
|
205
|
+
domain = c.get("domain", "")
|
|
206
|
+
if "prisma.asi.it" in domain:
|
|
207
|
+
cookie_dict[c["name"]] = c["value"]
|
|
208
|
+
|
|
209
|
+
logger.info(f"Captured {len(cookie_dict)} authentication cookies from browser")
|
|
210
|
+
return cookie_dict
|
|
211
|
+
finally:
|
|
212
|
+
chrome_proc.terminate()
|
|
213
|
+
try:
|
|
214
|
+
chrome_proc.wait(timeout=3)
|
|
215
|
+
except subprocess.TimeoutExpired:
|
|
216
|
+
chrome_proc.kill()
|
|
217
|
+
shutil.rmtree(user_data_dir, ignore_errors=True)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def perform_catalog_handshake(session: requests.Session) -> requests.Session:
|
|
221
|
+
"""
|
|
222
|
+
Performs the secondary OAuth authorization handshake required by the PRISMA Catalog
|
|
223
|
+
client (/js-cat-client-prisma-src/) to establish the pastr-* session cookie.
|
|
224
|
+
"""
|
|
225
|
+
ensure_authorized(session, CATALOG_CLIENT_URL)
|
|
226
|
+
return session
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def get_authenticated_session(force_refresh: bool = False) -> requests.Session:
|
|
230
|
+
"""
|
|
231
|
+
Retrieves a fully authenticated requests.Session for PRISMA.
|
|
232
|
+
Uses cached session if valid; otherwise launches headless Chrome CDP to re-authenticate.
|
|
233
|
+
"""
|
|
234
|
+
if not force_refresh:
|
|
235
|
+
cached = load_cached_session()
|
|
236
|
+
if cached:
|
|
237
|
+
session = create_base_session(cached)
|
|
238
|
+
if verify_session(session):
|
|
239
|
+
logger.info("Reusing valid cached PRISMA session")
|
|
240
|
+
save_cached_session({c.name: c.value for c in session.cookies})
|
|
241
|
+
return session
|
|
242
|
+
logger.info("Cached PRISMA session expired. Re-authenticating...")
|
|
243
|
+
|
|
244
|
+
if not config.has_credentials:
|
|
245
|
+
raise ValueError(
|
|
246
|
+
"PRISMA credentials not found. Please set PRISMA_USER (or PRISMA_USERNAME) and "
|
|
247
|
+
"PRISMA_PASS (or PRISMA_PASSWORD) in .env"
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
logger.info(f"Authenticating as {config.username}...")
|
|
251
|
+
cookies = asyncio.run(_run_chrome_cdp_login(config.username, config.password))
|
|
252
|
+
|
|
253
|
+
session = create_base_session(cookies)
|
|
254
|
+
perform_catalog_handshake(session)
|
|
255
|
+
if not verify_session(session):
|
|
256
|
+
raise RuntimeError("Authentication completed but session verification failed.")
|
|
257
|
+
|
|
258
|
+
save_cached_session({c.name: c.value for c in session.cookies})
|
|
259
|
+
logger.info("Authentication successful and verified.")
|
|
260
|
+
return session
|
prisma_pilot/cli.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PRISMA Command Line Interface
|
|
3
|
+
=============================
|
|
4
|
+
Interactive and automated CLI tool to search, order, and download
|
|
5
|
+
ASI PRISMA hyperspectral satellite data by AOI (GeoJSON or Bounding Box).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from dotenv import load_dotenv
|
|
16
|
+
|
|
17
|
+
from prisma_pilot.config import config, SESSION_FILE
|
|
18
|
+
from prisma_pilot.auth import get_authenticated_session, verify_session
|
|
19
|
+
from prisma_pilot.search import AOI, parse_aoi, search_prisma, get_user_orders
|
|
20
|
+
from prisma_pilot.downloader import download_product, order_processing, format_size
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def print_banner():
|
|
24
|
+
print(r"""
|
|
25
|
+
=============================================================================
|
|
26
|
+
____ ____ ___ ____ __ __ _ ____ _ _____
|
|
27
|
+
| _ \| _ \|_ _/ ___|| \/ | / \ / ___| / \|_ _|
|
|
28
|
+
| |_) | |_) || |\___ \| |\/| | / _ \ \___ \ / _ \ | |
|
|
29
|
+
| __/| _ < | | ___) | | | |/ ___ \ ___) / ___ \| |
|
|
30
|
+
|_| |_| \_\___|____/|_| |_/_/ \_\ |____/_/ \_\_|
|
|
31
|
+
Automated PRISMA Hyperspectral Data Acquisition Pipeline (CLI)
|
|
32
|
+
=============================================================================
|
|
33
|
+
""")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def display_results_table(results: list[dict]):
|
|
37
|
+
"""Print results in a clean formatted ASCII table."""
|
|
38
|
+
if not results:
|
|
39
|
+
print("\n [!] No acquisitions found matching your criteria.")
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
print(f"\nFound {len(results)} matching PRISMA acquisitions:\n")
|
|
43
|
+
header = f"{'#':<3} | {'Product Clean ID':<46} | {'Acquisition Date':<20} | {'Cloud%':<6} | {'Size':<10}"
|
|
44
|
+
print("-" * len(header))
|
|
45
|
+
print(header)
|
|
46
|
+
print("-" * len(header))
|
|
47
|
+
|
|
48
|
+
for idx, r in enumerate(results, 1):
|
|
49
|
+
clean_id = r["clean_id"]
|
|
50
|
+
date_str = r["start_time"][:19].replace("T", " ") if r["start_time"] else "N/A"
|
|
51
|
+
cloud = f"{r['cloud_cover']:.1f}%"
|
|
52
|
+
size = format_size(r["data_size_bytes"]) if r["data_size_bytes"] else "N/A"
|
|
53
|
+
print(f"{idx:<3} | {clean_id:<46} | {date_str:<20} | {cloud:<6} | {size:<10}")
|
|
54
|
+
|
|
55
|
+
print("-" * len(header))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def display_orders_table(orders: list[dict]):
|
|
59
|
+
"""Print user orders in a clean formatted ASCII table."""
|
|
60
|
+
if not orders:
|
|
61
|
+
print("\n [i] No past orders found for this user account.")
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
print(f"\nUser Order History ({len(orders)} total orders):\n")
|
|
65
|
+
header = f"{'Order ID':<16} | {'Processor':<9} | {'Status':<11} | {'Acquisition Date':<20} | {'Production Date':<20}"
|
|
66
|
+
print("-" * len(header))
|
|
67
|
+
print(header)
|
|
68
|
+
print("-" * len(header))
|
|
69
|
+
|
|
70
|
+
for o in orders:
|
|
71
|
+
order_id = o.get("externalOrderId", "N/A")
|
|
72
|
+
proc = o.get("processorName", "N/A")
|
|
73
|
+
status = o.get("status", "N/A")
|
|
74
|
+
start = o.get("startTime", "N/A")
|
|
75
|
+
prod_stop = o.get("productionStopTime", "N/A")
|
|
76
|
+
print(f"{order_id:<16} | {proc:<9} | {status:<11} | {start:<20} | {prod_stop:<20}")
|
|
77
|
+
|
|
78
|
+
print("-" * len(header))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _add_aoi_args(p: argparse.ArgumentParser):
|
|
82
|
+
group = p.add_argument_group("Area of Interest (AOI)")
|
|
83
|
+
group.add_argument("--geojson", "-g", help="Path to GeoJSON file or GeoJSON string")
|
|
84
|
+
group.add_argument(
|
|
85
|
+
"--bbox", "-b", nargs=4, type=float, metavar=("MIN_LON", "MIN_LAT", "MAX_LON", "MAX_LAT"),
|
|
86
|
+
help="Bounding box coordinates in WGS84: min_lon min_lat max_lon max_lat"
|
|
87
|
+
)
|
|
88
|
+
group.add_argument("--aoi", help="Flexible AOI: GeoJSON path, JSON string, or 'min_lon,min_lat,max_lon,max_lat'")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _add_filter_args(p: argparse.ArgumentParser):
|
|
92
|
+
group = p.add_argument_group("Search & Filter Options")
|
|
93
|
+
group.add_argument("--start-date", "-s", help="Start acquisition date (e.g. 2021-01-01 or ISO format)")
|
|
94
|
+
group.add_argument("--end-date", "-e", help="End acquisition date (e.g. 2026-12-31)")
|
|
95
|
+
group.add_argument("--max-cloud", "-c", type=float, default=30.0, help="Maximum cloud coverage percentage (default: 30%%)")
|
|
96
|
+
group.add_argument("--limit", "-l", type=int, default=20, help="Max results to fetch (default: 20)")
|
|
97
|
+
group.add_argument("--http", action="store_true", help="Try HTTP protocol instead of HTTPS as well")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_args(args_list: list[str] | None = None) -> argparse.Namespace:
|
|
101
|
+
parser = argparse.ArgumentParser(
|
|
102
|
+
prog="prisma-sat",
|
|
103
|
+
description="Automated PRISMA Hyperspectral Data Acquisition Tool (GeoJSON & Bounding Box)",
|
|
104
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
105
|
+
epilog="""
|
|
106
|
+
Examples:
|
|
107
|
+
# Search with bounding box [min_lon, min_lat, max_lon, max_lat]
|
|
108
|
+
prisma-sat search --bbox 72.2 22.8 72.8 23.2 --max-cloud 20
|
|
109
|
+
|
|
110
|
+
# Search with a GeoJSON file
|
|
111
|
+
prisma-sat search --geojson sample_aoi.geojson --start-date 2021-01-01
|
|
112
|
+
|
|
113
|
+
# Search using HTTP fallback protocol
|
|
114
|
+
prisma-sat search --bbox 72.2 22.8 72.8 23.2 --http
|
|
115
|
+
|
|
116
|
+
# List existing user orders and processing statuses
|
|
117
|
+
prisma-sat orders
|
|
118
|
+
|
|
119
|
+
# Download a product directly
|
|
120
|
+
prisma-sat download --id PRS_L1_STD_OFFL_20260130060212_20260130060216_0001 --output ./downloads
|
|
121
|
+
|
|
122
|
+
# Full pipeline: Search AOI and automatically download best scene
|
|
123
|
+
prisma-sat run --geojson sample_aoi.geojson --max-cloud 15 --download-first --output ./downloads
|
|
124
|
+
""",
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
parser.add_argument("--env-file", help="Path to custom .env file for credentials")
|
|
128
|
+
|
|
129
|
+
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
|
|
130
|
+
|
|
131
|
+
# Command: search
|
|
132
|
+
search_parser = subparsers.add_parser("search", help="Search PRISMA catalog for matching AOI")
|
|
133
|
+
_add_aoi_args(search_parser)
|
|
134
|
+
_add_filter_args(search_parser)
|
|
135
|
+
|
|
136
|
+
# Command: orders
|
|
137
|
+
orders_parser = subparsers.add_parser("orders", help="List user processing orders and statuses")
|
|
138
|
+
orders_parser.add_argument("--http", action="store_true", help="Try HTTP protocol instead of HTTPS")
|
|
139
|
+
|
|
140
|
+
# Command: download
|
|
141
|
+
dl_parser = subparsers.add_parser("download", help="Download a PRISMA product by ID or URL")
|
|
142
|
+
dl_parser.add_argument("--id", "-i", dest="product_id", required=True, help="Product ID or direct URL")
|
|
143
|
+
dl_parser.add_argument("--output", "-o", default="./downloads", help="Output directory (default: ./downloads)")
|
|
144
|
+
dl_parser.add_argument("--no-extract", action="store_true", help="Do not extract .he5 from downloaded .zip")
|
|
145
|
+
dl_parser.add_argument("--http", action="store_true", help="Try HTTP protocol instead of HTTPS")
|
|
146
|
+
|
|
147
|
+
# Command: run (Default full pipeline)
|
|
148
|
+
run_parser = subparsers.add_parser("run", help="Search AOI and download products")
|
|
149
|
+
_add_aoi_args(run_parser)
|
|
150
|
+
_add_filter_args(run_parser)
|
|
151
|
+
run_parser.add_argument("--output", "-o", default="./downloads", help="Output directory (default: ./downloads)")
|
|
152
|
+
run_parser.add_argument("--download-first", action="store_true", help="Automatically download the first (best) matching product")
|
|
153
|
+
run_parser.add_argument("--download-all", action="store_true", help="Download all matching products")
|
|
154
|
+
run_parser.add_argument("--order-if-needed", action="store_true", help="Submit processing order if scene is not yet processed")
|
|
155
|
+
run_parser.add_argument("--processor", default="L2D", choices=["L1", "L2B", "L2C", "L2D"], help="Processor level for orders (default: L2D)")
|
|
156
|
+
run_parser.add_argument("--no-extract", action="store_true", help="Do not extract .he5 from downloaded .zip")
|
|
157
|
+
|
|
158
|
+
# Top-level fallback arguments if no subcommand given
|
|
159
|
+
_add_aoi_args(parser)
|
|
160
|
+
_add_filter_args(parser)
|
|
161
|
+
parser.add_argument("--output", "-o", default="./downloads", help="Output directory (default: ./downloads)")
|
|
162
|
+
parser.add_argument("--download-first", action="store_true", help="Automatically download the first (best) matching product")
|
|
163
|
+
parser.add_argument("--download-all", action="store_true", help="Download all matching products")
|
|
164
|
+
|
|
165
|
+
return parser.parse_args(args_list)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def main(args_list: list[str] | None = None) -> int:
|
|
169
|
+
print_banner()
|
|
170
|
+
args = parse_args(args_list)
|
|
171
|
+
|
|
172
|
+
if args.env_file and Path(args.env_file).is_file():
|
|
173
|
+
load_dotenv(args.env_file, override=True)
|
|
174
|
+
|
|
175
|
+
command = args.command
|
|
176
|
+
if not command:
|
|
177
|
+
if hasattr(args, "product_id") and args.product_id:
|
|
178
|
+
command = "download"
|
|
179
|
+
elif args.geojson or args.bbox or args.aoi:
|
|
180
|
+
command = "run"
|
|
181
|
+
else:
|
|
182
|
+
command = "search"
|
|
183
|
+
|
|
184
|
+
# Verify credentials
|
|
185
|
+
if not config.has_credentials:
|
|
186
|
+
print("[!] Error: PRISMA credentials not found.")
|
|
187
|
+
print(" Please set PRISMA_USER / PRISMA_PASS in .env, ~/.config/prisma_sat/.env, or environment variables.")
|
|
188
|
+
return 1
|
|
189
|
+
|
|
190
|
+
print(f"[*] Account: {config.username}")
|
|
191
|
+
print(f"[*] Session cache: {SESSION_FILE}")
|
|
192
|
+
|
|
193
|
+
# Authenticate
|
|
194
|
+
session = get_authenticated_session()
|
|
195
|
+
|
|
196
|
+
# 1. Handle Orders Command
|
|
197
|
+
if command == "orders":
|
|
198
|
+
print("[*] Fetching user order history...")
|
|
199
|
+
orders = get_user_orders(session=session, use_http=args.http)
|
|
200
|
+
display_orders_table(orders)
|
|
201
|
+
return 0
|
|
202
|
+
|
|
203
|
+
# 2. Handle Direct Download Command
|
|
204
|
+
if command == "download":
|
|
205
|
+
product_id = getattr(args, "product_id", None)
|
|
206
|
+
if not product_id:
|
|
207
|
+
print("[!] Error: Must specify --id <product_id_or_url>")
|
|
208
|
+
return 1
|
|
209
|
+
extract = not getattr(args, "no_extract", False)
|
|
210
|
+
print(f"[*] Downloading product: {product_id} to {args.output}...")
|
|
211
|
+
try:
|
|
212
|
+
res = download_product(
|
|
213
|
+
product_id,
|
|
214
|
+
output_dir=args.output,
|
|
215
|
+
session=session,
|
|
216
|
+
use_http=args.http,
|
|
217
|
+
extract=extract,
|
|
218
|
+
)
|
|
219
|
+
print("\n[+] Download completed successfully!")
|
|
220
|
+
print(f" ZIP Archive: {res.get('zip_path')}")
|
|
221
|
+
if res.get("he5_path"):
|
|
222
|
+
print(f" Extracted HDF5: {res.get('he5_path')}")
|
|
223
|
+
print(f" Total Size: {format_size(res.get('file_size_bytes', 0))}")
|
|
224
|
+
return 0
|
|
225
|
+
except Exception as e:
|
|
226
|
+
print(f"\n[-] Download error: {e}")
|
|
227
|
+
return 1
|
|
228
|
+
|
|
229
|
+
# 3. Handle Search and Run Commands
|
|
230
|
+
target_aoi = getattr(args, "aoi", None) or getattr(args, "geojson", None) or getattr(args, "bbox", None)
|
|
231
|
+
if not target_aoi:
|
|
232
|
+
sample_p = Path("sample_aoi.geojson")
|
|
233
|
+
if sample_p.is_file():
|
|
234
|
+
print(f"[*] No AOI specified. Defaulting to sample AOI: {sample_p.resolve()}")
|
|
235
|
+
target_aoi = sample_p
|
|
236
|
+
else:
|
|
237
|
+
print("[!] Error: Please provide an AOI via --geojson <file> or --bbox <min_lon> <min_lat> <max_lon> <max_lat>")
|
|
238
|
+
return 1
|
|
239
|
+
|
|
240
|
+
parsed_aoi = parse_aoi(target_aoi)
|
|
241
|
+
print(f"[*] Parsed AOI: bbox=[{parsed_aoi.min_lon:.4f}, {parsed_aoi.min_lat:.4f}, {parsed_aoi.max_lon:.4f}, {parsed_aoi.max_lat:.4f}]")
|
|
242
|
+
|
|
243
|
+
print("[*] Searching PRISMA Catalog...")
|
|
244
|
+
results = search_prisma(
|
|
245
|
+
aoi=parsed_aoi,
|
|
246
|
+
start_date=args.start_date,
|
|
247
|
+
end_date=args.end_date,
|
|
248
|
+
max_cloud=args.max_cloud,
|
|
249
|
+
rows=args.limit,
|
|
250
|
+
session=session,
|
|
251
|
+
use_http=args.http,
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
display_results_table(results)
|
|
255
|
+
|
|
256
|
+
# Check if user wanted to download matching results
|
|
257
|
+
should_download = getattr(args, "download_first", False) or getattr(args, "download_all", False)
|
|
258
|
+
if should_download and results:
|
|
259
|
+
items_to_download = results if args.download_all else [results[0]]
|
|
260
|
+
print(f"\n[*] Proceeding to download {len(items_to_download)} acquisition(s)...")
|
|
261
|
+
|
|
262
|
+
orders = get_user_orders(session=session, use_http=args.http)
|
|
263
|
+
completed_orders = {
|
|
264
|
+
o.get("startTime", "")[:19]: o for o in orders if o.get("status") == "COMPLETED"
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
out_dir = Path(args.output)
|
|
268
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
269
|
+
extract = not getattr(args, "no_extract", False)
|
|
270
|
+
|
|
271
|
+
for item in items_to_download:
|
|
272
|
+
clean_id = item["clean_id"]
|
|
273
|
+
start_key = item["start_time"][:19].replace("T", " ")
|
|
274
|
+
print(f"\n--> Processing Acquisition: {clean_id} ({item['start_time']})")
|
|
275
|
+
|
|
276
|
+
if start_key in completed_orders:
|
|
277
|
+
ord_info = completed_orders[start_key]
|
|
278
|
+
proc = ord_info.get("processorName", "L2D")
|
|
279
|
+
print(f" [i] Matching processed order found: {ord_info.get('externalOrderId')} (Level: {proc})")
|
|
280
|
+
|
|
281
|
+
try:
|
|
282
|
+
res = download_product(
|
|
283
|
+
clean_id,
|
|
284
|
+
output_dir=out_dir,
|
|
285
|
+
session=session,
|
|
286
|
+
use_http=args.http,
|
|
287
|
+
extract=extract,
|
|
288
|
+
)
|
|
289
|
+
print(f" [+] Successfully acquired: {res.get('zip_path')}")
|
|
290
|
+
if res.get("he5_path"):
|
|
291
|
+
print(f" [+] HDF5 Data Cube: {res.get('he5_path')}")
|
|
292
|
+
except Exception as e:
|
|
293
|
+
print(f" [-] Direct download notice: {e}")
|
|
294
|
+
if getattr(args, "order_if_needed", False):
|
|
295
|
+
proc = getattr(args, "processor", "L2D")
|
|
296
|
+
print(f" [*] Submitting processing order for Level {proc}...")
|
|
297
|
+
try:
|
|
298
|
+
order_res = order_processing(clean_id, processor=proc, session=session, use_http=args.http)
|
|
299
|
+
print(f" [+] Order submitted: {order_res}")
|
|
300
|
+
except Exception as order_err:
|
|
301
|
+
print(f" [-] Order submission error: {order_err}")
|
|
302
|
+
else:
|
|
303
|
+
print(" [!] Tip: If this Level 0 scene is not yet packaged, run with --order-if-needed to submit a processing order.")
|
|
304
|
+
|
|
305
|
+
return 0
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def run_cli():
|
|
309
|
+
"""Main CLI entrypoint for console_scripts."""
|
|
310
|
+
sys.exit(main())
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
if __name__ == "__main__":
|
|
314
|
+
run_cli()
|
prisma_pilot/config.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PRISMA Configuration & Credentials
|
|
3
|
+
==================================
|
|
4
|
+
Manages environment variables, authentication credentials, and cache directories.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from dotenv import load_dotenv
|
|
12
|
+
|
|
13
|
+
# Check explicit env file override if specified
|
|
14
|
+
env_file_override = os.getenv("PRISMA_ENV_FILE")
|
|
15
|
+
|
|
16
|
+
# Search candidate locations portable across OS/environments
|
|
17
|
+
CANDIDATE_DOTENVS = [
|
|
18
|
+
Path.home() / ".config" / "prisma_sat" / ".env",
|
|
19
|
+
Path.home() / ".prisma_sat" / ".env",
|
|
20
|
+
Path.home() / ".config" / "prisma_pilot" / ".env",
|
|
21
|
+
Path.home() / ".prisma_pilot" / ".env",
|
|
22
|
+
Path(__file__).resolve().parent.parent / ".env",
|
|
23
|
+
Path(__file__).resolve().parent / ".env",
|
|
24
|
+
Path.cwd() / ".env",
|
|
25
|
+
Path.cwd() / "prisma_pilot" / ".env",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
if env_file_override and Path(env_file_override).is_file():
|
|
29
|
+
load_dotenv(env_file_override, override=True)
|
|
30
|
+
else:
|
|
31
|
+
for p in CANDIDATE_DOTENVS:
|
|
32
|
+
if p.is_file():
|
|
33
|
+
load_dotenv(p, override=True)
|
|
34
|
+
|
|
35
|
+
CACHE_DIR = Path(os.getenv("PRISMA_CACHE_DIR", str(Path.home() / ".cache" / "prisma_pilot")))
|
|
36
|
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
|
|
38
|
+
SESSION_FILE = CACHE_DIR / "session.json"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PrismaConfig:
|
|
42
|
+
@property
|
|
43
|
+
def username(self) -> str:
|
|
44
|
+
return (os.getenv("PRISMA_USER") or os.getenv("PRISMA_USERNAME") or "").strip()
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def password(self) -> str:
|
|
48
|
+
return (os.getenv("PRISMA_PASS") or os.getenv("PRISMA_PASSWORD") or "").strip()
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def phpsessid(self) -> str:
|
|
52
|
+
return os.getenv("PRISMA_PHPSESSID", os.getenv("PRISMA_COOKIE", "")).strip()
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def has_credentials(self) -> bool:
|
|
56
|
+
return bool(self.username and self.password)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def has_session(self) -> bool:
|
|
60
|
+
return bool(self.phpsessid or SESSION_FILE.exists())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
config = PrismaConfig()
|