forked from linkong/planet
release: bump version to 0.84.2
This commit is contained in:
1 parent
5e6352f524
commit
30b44ec00d
77 files changed
+3312
-1039
No files matched your search
@@ -3,14 +3,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
import gc
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
@@ -43,6 +44,7 @@ CLOUD_CONFIG_CATEGORY = "earth_cloud_map"
|
||||
DEFAULT_STATIC_CLOUD_URL = "./assets/earth_clouds_2048.png"
|
||||
ANALYSIS_GRID_WIDTH = 720
|
||||
ANALYSIS_GRID_HEIGHT = 360
|
||||
LOW_MEMORY_CGROUP_THRESHOLD_MB = 1024
|
||||
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$")
|
||||
|
||||
NASA_GIBS_WMS_URL = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
|
||||
@@ -377,6 +379,49 @@ def parse_resolution(resolution: str) -> tuple[int, int]:
|
||||
return (4096, 2048) if resolution == "4096x2048" else (2048, 1024)
|
||||
|
||||
|
||||
def detect_container_memory_limit_mb() -> int | None:
|
||||
"""Return cgroup memory limit in MiB when bounded inside a container, else None."""
|
||||
for path in (
|
||||
Path("/sys/fs/cgroup/memory.max"),
|
||||
Path("/sys/fs/cgroup/memory/memory.limit_in_bytes"),
|
||||
):
|
||||
try:
|
||||
raw = path.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
continue
|
||||
if not raw or raw == "max":
|
||||
continue
|
||||
try:
|
||||
limit_bytes = int(raw)
|
||||
except ValueError:
|
||||
continue
|
||||
if limit_bytes <= 0 or limit_bytes >= (1 << 50):
|
||||
continue
|
||||
return int(limit_bytes // (1024 * 1024))
|
||||
return None
|
||||
|
||||
|
||||
def resolve_effective_cloud_config(config: CloudMapConfig) -> CloudMapConfig:
|
||||
"""Clamp working resolution to 2048x1024 in bounded low-memory containers."""
|
||||
env_max = str(os.environ.get("PLANET_CLOUD_MAX_RESOLUTION") or "").strip().lower()
|
||||
mem_limit_mb = detect_container_memory_limit_mb()
|
||||
if config.resolution == "4096x2048" and (
|
||||
env_max == "2048x1024"
|
||||
or (mem_limit_mb is not None and mem_limit_mb <= LOW_MEMORY_CGROUP_THRESHOLD_MB)
|
||||
):
|
||||
logger.warning_event(
|
||||
"Clamped cloud map working resolution to 2048x1024 for low-memory environment",
|
||||
event="earth.cloud_map.resolution_clamped_low_memory",
|
||||
context={
|
||||
"configured_resolution": config.resolution,
|
||||
"effective_resolution": "2048x1024",
|
||||
"container_memory_limit_mb": mem_limit_mb,
|
||||
},
|
||||
)
|
||||
return config.model_copy(update={"resolution": "2048x1024"})
|
||||
return config
|
||||
|
||||
|
||||
def _get_gibs_3d_lut() -> np.ndarray:
|
||||
"""Build a quantized 5-bit/channel RGB -> Brightness Temperature (°C) lookup table."""
|
||||
global _GIBS_3D_LUT
|
||||
@@ -460,29 +505,33 @@ def _disambiguate_dvorak_cold_gray(
|
||||
if np.any(ultra_wrap):
|
||||
result[ultra_wrap] = -91.5
|
||||
|
||||
del not_ring, labels, stats
|
||||
return result, updated_valid
|
||||
|
||||
|
||||
def decode_gibs_band13_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Invert GIBS Band13 Clean IR RGBA pixels into Brightness Temperature (°C) and valid mask."""
|
||||
rgb = rgba_arr[:, :, :3].astype(np.int32)
|
||||
r_u8 = rgba_arr[:, :, 0]
|
||||
g_u8 = rgba_arr[:, :, 1]
|
||||
b_u8 = rgba_arr[:, :, 2]
|
||||
alpha = rgba_arr[:, :, 3]
|
||||
valid = alpha > 12
|
||||
|
||||
r_ch = rgb[:, :, 0]
|
||||
g_ch = rgb[:, :, 1]
|
||||
b_ch = rgb[:, :, 2]
|
||||
chroma = np.maximum(np.maximum(r_ch, g_ch), b_ch) - np.minimum(np.minimum(r_ch, g_ch), b_ch)
|
||||
gray = ((r_ch + g_ch + b_ch) // 3).astype(np.float32)
|
||||
chroma = np.maximum(np.maximum(r_u8, g_u8), b_u8) - np.minimum(np.minimum(r_u8, g_u8), b_u8)
|
||||
gray_sum = r_u8.astype(np.uint16)
|
||||
gray_sum += g_u8
|
||||
gray_sum += b_u8
|
||||
gray = (gray_sum // 3).astype(np.float32)
|
||||
del gray_sum
|
||||
|
||||
temp_c = 57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4
|
||||
temp_c = (57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4).astype(np.float32)
|
||||
color_mask = valid & (chroma >= 12)
|
||||
if np.any(color_mask):
|
||||
lut = _get_gibs_3d_lut()
|
||||
temp_c[color_mask] = lut[
|
||||
r_ch[color_mask] >> 3,
|
||||
g_ch[color_mask] >> 3,
|
||||
b_ch[color_mask] >> 3,
|
||||
r_u8[color_mask] >> 3,
|
||||
g_u8[color_mask] >> 3,
|
||||
b_u8[color_mask] >> 3,
|
||||
]
|
||||
|
||||
temp_c, valid = _disambiguate_dvorak_cold_gray(valid, gray, chroma, temp_c)
|
||||
@@ -599,6 +648,7 @@ def synthesize_multi_sat_ir(
|
||||
temp_accum += safe_temp * pixel_weight
|
||||
weight_accum += pixel_weight
|
||||
active_satellites.append(str(sat["id"]))
|
||||
del rgba_arr, sat_temp, valid, pixel_weight, safe_temp
|
||||
|
||||
if not active_satellites or not np.any(weight_accum > 0.0):
|
||||
raise RuntimeError("No valid geostationary IR satellite frames could be decoded")
|
||||
@@ -1190,6 +1240,7 @@ async def collect_latest_cloud_frame(
|
||||
envelope = await read_cloud_map_configuration(db)
|
||||
merged_cfg = {**envelope["config"], **(override_config or {})}
|
||||
config = CloudMapConfig.model_validate(merged_cfg)
|
||||
effective_config = resolve_effective_cloud_config(config)
|
||||
|
||||
manifest = _read_manifest()
|
||||
prev_frames = manifest.get("frames", [])
|
||||
@@ -1207,42 +1258,43 @@ async def collect_latest_cloud_frame(
|
||||
density: np.ndarray | None = None
|
||||
temp_c: np.ndarray | None = None
|
||||
visual_payloads: list[tuple[dict[str, Any], bytes]] = []
|
||||
source_used = config.primary_source
|
||||
source_used = effective_config.primary_source
|
||||
satellites: list[str] = []
|
||||
degraded = False
|
||||
|
||||
if config.primary_source == "multi_sat_ir":
|
||||
if config.geocolor_enabled:
|
||||
payloads, visual_payloads = await asyncio.gather(
|
||||
_fetch_multi_sat_payloads(config, layer_field="layer"),
|
||||
_fetch_multi_sat_payloads(config, layer_field="visual_layer"),
|
||||
)
|
||||
else:
|
||||
payloads = await _fetch_multi_sat_payloads(config, layer_field="layer")
|
||||
if effective_config.primary_source == "multi_sat_ir":
|
||||
payloads = await _fetch_multi_sat_payloads(effective_config, layer_field="layer")
|
||||
if payloads:
|
||||
density, temp_c, satellites = await asyncio.to_thread(
|
||||
synthesize_multi_sat_ir,
|
||||
payloads,
|
||||
config=config,
|
||||
config=effective_config,
|
||||
)
|
||||
payloads.clear()
|
||||
del payloads
|
||||
if len(satellites) < len(SATELLITE_SOURCES):
|
||||
degraded = True
|
||||
elif config.fallback_source == "matteason_live":
|
||||
raw = await _fetch_matteason_bytes(config)
|
||||
if effective_config.geocolor_enabled:
|
||||
visual_payloads = await _fetch_multi_sat_payloads(
|
||||
effective_config,
|
||||
layer_field="visual_layer",
|
||||
)
|
||||
elif effective_config.fallback_source == "matteason_live":
|
||||
raw = await _fetch_matteason_bytes(effective_config)
|
||||
density, temp_c = await asyncio.to_thread(
|
||||
decode_matteason_cloud_bytes,
|
||||
raw,
|
||||
config=config,
|
||||
config=effective_config,
|
||||
)
|
||||
source_used = "matteason_live"
|
||||
satellites = ["eumetsat_nasa_mosaic"]
|
||||
degraded = True
|
||||
else:
|
||||
raw = await _fetch_matteason_bytes(config)
|
||||
raw = await _fetch_matteason_bytes(effective_config)
|
||||
density, temp_c = await asyncio.to_thread(
|
||||
decode_matteason_cloud_bytes,
|
||||
raw,
|
||||
config=config,
|
||||
config=effective_config,
|
||||
)
|
||||
source_used = "matteason_live"
|
||||
satellites = ["eumetsat_nasa_mosaic"]
|
||||
@@ -1257,88 +1309,80 @@ async def collect_latest_cloud_frame(
|
||||
def _finalize() -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
from app.services.earth_clouds_fx import (
|
||||
compute_dis_optical_flow_webp,
|
||||
decode_visual_payloads,
|
||||
fuse_daytime_visible_into_density,
|
||||
synthesize_geocolor_visual_webp,
|
||||
fuse_and_synthesize_visual_layers,
|
||||
)
|
||||
|
||||
width, height = parse_resolution(config.resolution)
|
||||
decoded_visuals = (
|
||||
decode_visual_payloads(visual_payloads, width, height)
|
||||
if (config.geocolor_enabled and visual_payloads)
|
||||
else []
|
||||
)
|
||||
fused_density = (
|
||||
fuse_daytime_visible_into_density(
|
||||
density,
|
||||
temp_c,
|
||||
decoded_visuals,
|
||||
width=width,
|
||||
height=height,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
if decoded_visuals
|
||||
else density
|
||||
)
|
||||
try:
|
||||
width, height = parse_resolution(effective_config.resolution)
|
||||
if effective_config.geocolor_enabled and visual_payloads:
|
||||
fused_density, visual_webp_bytes = fuse_and_synthesize_visual_layers(
|
||||
density,
|
||||
temp_c,
|
||||
visual_payloads,
|
||||
width=width,
|
||||
height=height,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
else:
|
||||
fused_density, visual_webp_bytes = density, None
|
||||
visual_payloads.clear()
|
||||
|
||||
analysis = analyze_cloud_density_grid(
|
||||
fused_density,
|
||||
temp_c,
|
||||
config=config,
|
||||
previous_snapshot=prev_snapshot,
|
||||
previous_regions=prev_regions,
|
||||
)
|
||||
webp_bytes = _encode_cloud_webp(fused_density)
|
||||
visual_webp_bytes = (
|
||||
synthesize_geocolor_visual_webp(
|
||||
decoded_visuals,
|
||||
analysis = analyze_cloud_density_grid(
|
||||
fused_density,
|
||||
width=width,
|
||||
height=height,
|
||||
temp_c,
|
||||
config=effective_config,
|
||||
previous_snapshot=prev_snapshot,
|
||||
previous_regions=prev_regions,
|
||||
)
|
||||
if decoded_visuals
|
||||
else None
|
||||
)
|
||||
flow_webp_bytes: bytes | None = None
|
||||
flow_prev_version: str | None = None
|
||||
flow_max_uv = 0.0
|
||||
if config.optical_flow_enabled and isinstance(prev_entry, dict) and prev_entry.get("version"):
|
||||
prev_ver = str(prev_entry["version"])
|
||||
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
|
||||
if prev_ver != version and prev_frame_file.exists():
|
||||
try:
|
||||
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
|
||||
prev_density = prev_rgba[:, :, 3]
|
||||
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
|
||||
if flow_res is not None:
|
||||
flow_webp_bytes, flow_max_uv = flow_res
|
||||
flow_prev_version = prev_ver
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Cloud optical flow calculation failed",
|
||||
event="earth.cloud_map.optical_flow_failed",
|
||||
context={"prev_version": prev_ver, "error": str(exc)},
|
||||
)
|
||||
webp_bytes = _encode_cloud_webp(fused_density)
|
||||
flow_webp_bytes: bytes | None = None
|
||||
flow_prev_version: str | None = None
|
||||
flow_max_uv = 0.0
|
||||
if (
|
||||
effective_config.optical_flow_enabled
|
||||
and isinstance(prev_entry, dict)
|
||||
and prev_entry.get("version")
|
||||
):
|
||||
prev_ver = str(prev_entry["version"])
|
||||
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
|
||||
if prev_ver != version and prev_frame_file.exists():
|
||||
try:
|
||||
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
|
||||
prev_density = prev_rgba[:, :, 3]
|
||||
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
|
||||
del prev_rgba, prev_density
|
||||
if flow_res is not None:
|
||||
flow_webp_bytes, flow_max_uv = flow_res
|
||||
flow_prev_version = prev_ver
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Cloud optical flow calculation failed",
|
||||
event="earth.cloud_map.optical_flow_failed",
|
||||
context={"prev_version": prev_ver, "error": str(exc)},
|
||||
)
|
||||
|
||||
entry = _save_frame_artifacts_sync(
|
||||
version=version,
|
||||
captured_at=captured_at,
|
||||
source_used=source_used,
|
||||
satellites=satellites,
|
||||
degraded=degraded,
|
||||
config=config,
|
||||
webp_bytes=webp_bytes,
|
||||
visual_webp_bytes=visual_webp_bytes,
|
||||
flow_webp_bytes=flow_webp_bytes,
|
||||
flow_prev_version=flow_prev_version,
|
||||
flow_max_uv=flow_max_uv,
|
||||
grid_density=analysis["grid_density"],
|
||||
grid_temp_i8=analysis["grid_temp_i8"],
|
||||
global_summary=analysis["global_summary"],
|
||||
regions=analysis["regions"],
|
||||
clusters=analysis["convective_clusters"],
|
||||
)
|
||||
return entry, analysis
|
||||
entry = _save_frame_artifacts_sync(
|
||||
version=version,
|
||||
captured_at=captured_at,
|
||||
source_used=source_used,
|
||||
satellites=satellites,
|
||||
degraded=degraded,
|
||||
config=effective_config,
|
||||
webp_bytes=webp_bytes,
|
||||
visual_webp_bytes=visual_webp_bytes,
|
||||
flow_webp_bytes=flow_webp_bytes,
|
||||
flow_prev_version=flow_prev_version,
|
||||
flow_max_uv=flow_max_uv,
|
||||
grid_density=analysis["grid_density"],
|
||||
grid_temp_i8=analysis["grid_temp_i8"],
|
||||
global_summary=analysis["global_summary"],
|
||||
regions=analysis["regions"],
|
||||
clusters=analysis["convective_clusters"],
|
||||
)
|
||||
return entry, analysis
|
||||
finally:
|
||||
visual_payloads.clear()
|
||||
gc.collect()
|
||||
|
||||
async with _CLOUD_WRITE_LOCK:
|
||||
frame_entry, analysis = await asyncio.to_thread(_finalize)
|
||||
@@ -1348,7 +1392,7 @@ async def collect_latest_cloud_frame(
|
||||
"global_summary": analysis["global_summary"],
|
||||
"regions": analysis["regions"],
|
||||
"convective_clusters": analysis["convective_clusters"],
|
||||
"config": config.model_dump(mode="json"),
|
||||
"config": effective_config.model_dump(mode="json"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import gc
|
||||
import io
|
||||
import math
|
||||
from typing import Any, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Iterator, Sequence
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -35,18 +36,40 @@ def decode_visual_payloads(
|
||||
height: int,
|
||||
) -> list[tuple[dict[str, Any], np.ndarray]]:
|
||||
"""Decode and resize visible satellite payloads once so density & GeoColor share buffers."""
|
||||
decoded: list[tuple[dict[str, Any], np.ndarray]] = []
|
||||
return list(_iter_decoded_visuals(visual_payloads, width, height))
|
||||
|
||||
|
||||
def _iter_decoded_visuals(
|
||||
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
|
||||
width: int,
|
||||
height: int,
|
||||
) -> Iterator[tuple[dict[str, Any], np.ndarray]]:
|
||||
"""Yield one decoded RGBA visual frame at a time to bound peak heap usage."""
|
||||
for sat, payload in visual_payloads:
|
||||
if isinstance(payload, np.ndarray):
|
||||
if payload.shape[:2] == (height, width) and payload.shape[2] == 4:
|
||||
decoded.append((sat, payload))
|
||||
yield sat, payload
|
||||
continue
|
||||
try:
|
||||
rgba = _decode_rgba_resized(payload, width, height)
|
||||
decoded.append((sat, rgba))
|
||||
yield sat, rgba
|
||||
except Exception:
|
||||
continue
|
||||
return decoded
|
||||
|
||||
|
||||
def _rgba_channels_and_luma(
|
||||
rgba: np.ndarray,
|
||||
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
||||
red = rgba[:, :, 0]
|
||||
green = rgba[:, :, 1]
|
||||
blue = rgba[:, :, 2]
|
||||
alpha = rgba[:, :, 3]
|
||||
luma = (
|
||||
0.299 * red.astype(np.float32)
|
||||
+ 0.587 * green.astype(np.float32)
|
||||
+ 0.114 * blue.astype(np.float32)
|
||||
)
|
||||
return red, green, blue, alpha, luma
|
||||
|
||||
|
||||
def _solar_cosine_grid(width: int, height: int, now_utc: datetime) -> tuple[np.ndarray, np.ndarray]:
|
||||
@@ -87,10 +110,6 @@ def fuse_daytime_visible_into_density(
|
||||
if not np.any(day_weight > 0.01):
|
||||
return density_u8
|
||||
|
||||
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
|
||||
if not decoded_visuals:
|
||||
return density_u8
|
||||
|
||||
cos_safe = np.clip(cos_sza, 0.30, 1.0)
|
||||
safe_temp = np.where(np.isfinite(temp_c), temp_c, 15.0).astype(np.float32)
|
||||
# Band-pass gate: peaks on -2C..+16C warm low clouds while suppressing hot deserts (>+24C) and sub-zero snow (<-8C).
|
||||
@@ -102,25 +121,24 @@ def fuse_daytime_visible_into_density(
|
||||
vis_accum = np.zeros((height, width), dtype=np.float32)
|
||||
weight_accum = np.zeros((height, width), dtype=np.float32)
|
||||
|
||||
for sat, rgba in decoded_visuals:
|
||||
rgb = rgba[:, :, :3].astype(np.float32)
|
||||
alpha = rgba[:, :, 3].astype(np.float32)
|
||||
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
|
||||
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
|
||||
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
|
||||
not_clipped = ~(
|
||||
(rgb[:, :, 0] >= 254.0)
|
||||
& (rgb[:, :, 1] >= 254.0)
|
||||
& (rgb[:, :, 2] >= 254.0)
|
||||
(r_u8 >= 254)
|
||||
& (g_u8 >= 254)
|
||||
& (b_u8 >= 254)
|
||||
& (safe_temp > -10.0)
|
||||
)
|
||||
valid = (alpha > 12.0) & (luma > 8.0) & not_clipped
|
||||
valid = (alpha_u8 > 12) & (luma > 8.0) & not_clipped
|
||||
if not np.any(valid):
|
||||
continue
|
||||
|
||||
chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0
|
||||
max_u8 = np.maximum(np.maximum(r_u8, g_u8), b_u8)
|
||||
min_u8 = np.minimum(np.minimum(r_u8, g_u8), b_u8)
|
||||
chroma = (max_u8 - min_u8).astype(np.float32) / 255.0
|
||||
is_color = float(np.nanpercentile(chroma[valid], 95)) > 0.08
|
||||
if is_color:
|
||||
min_rgb = np.min(rgb, axis=2)
|
||||
albedo = min_rgb / cos_safe
|
||||
albedo = min_u8.astype(np.float32) / cos_safe
|
||||
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
|
||||
sat_cloud = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * warm_low_cloud_gate
|
||||
else:
|
||||
@@ -131,6 +149,7 @@ def fuse_daytime_visible_into_density(
|
||||
pix_w = np.where(valid, lon_w[None, :], 0.0)
|
||||
vis_accum += sat_cloud * pix_w
|
||||
weight_accum += pix_w
|
||||
del rgba, luma, chroma, sat_cloud, pix_w
|
||||
|
||||
covered = weight_accum > 0.0
|
||||
if not np.any(covered):
|
||||
@@ -156,37 +175,33 @@ def synthesize_geocolor_visual_webp(
|
||||
if not visual_payloads or density_u8.shape != (height, width):
|
||||
return None
|
||||
|
||||
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
|
||||
if not decoded_visuals:
|
||||
return None
|
||||
|
||||
rgb_accum = np.zeros((height, width, 3), dtype=np.float32)
|
||||
weight_accum = np.zeros((height, width), dtype=np.float32)
|
||||
valid_sources = 0
|
||||
|
||||
for sat, rgba in decoded_visuals:
|
||||
rgb = rgba[:, :, :3].astype(np.float32)
|
||||
alpha = rgba[:, :, 3].astype(np.float32)
|
||||
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
|
||||
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
|
||||
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
|
||||
|
||||
# EUMETView/GIBS return opaque black over night hemispheres or pure-white clipped wedges.
|
||||
# Mask out dark night pixels and non-dense pure-white [255,255,255] fill artifacts.
|
||||
not_clipped = ~(
|
||||
(rgb[:, :, 0] >= 254.0)
|
||||
& (rgb[:, :, 1] >= 254.0)
|
||||
& (rgb[:, :, 2] >= 254.0)
|
||||
(r_u8 >= 254)
|
||||
& (g_u8 >= 254)
|
||||
& (b_u8 >= 254)
|
||||
& (density_u8 < 180)
|
||||
)
|
||||
valid = (alpha > 12.0) & (luma > 22.0) & not_clipped
|
||||
valid = (alpha_u8 > 12) & (luma > 22.0) & not_clipped
|
||||
if not np.any(valid):
|
||||
continue
|
||||
|
||||
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
|
||||
# Emphasize cloud-rich pixels from daytime channels so dark ocean reflectance doesn't darken clouds.
|
||||
pix_w = np.where(valid, lon_w[None, :], 0.0)
|
||||
rgb_accum += rgb * pix_w[:, :, None]
|
||||
for ch in range(3):
|
||||
rgb_accum[:, :, ch] += rgba[:, :, ch].astype(np.float32) * pix_w
|
||||
weight_accum += pix_w
|
||||
valid_sources += 1
|
||||
del rgba, luma, pix_w
|
||||
|
||||
if valid_sources == 0 or not np.any(weight_accum > 0.0):
|
||||
return None
|
||||
@@ -274,3 +289,34 @@ def compute_dis_optical_flow_webp(
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="WEBP", quality=92, method=1)
|
||||
return buf.getvalue(), round(float(max_uv), 6)
|
||||
|
||||
|
||||
def fuse_and_synthesize_visual_layers(
|
||||
density_u8: np.ndarray,
|
||||
temp_c: np.ndarray,
|
||||
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
now_utc: datetime | None = None,
|
||||
) -> tuple[np.ndarray, bytes | None]:
|
||||
"""Stream visible payloads one at a time for low-cloud density fusion and GeoColor WebP."""
|
||||
if not visual_payloads:
|
||||
return density_u8, None
|
||||
fused_density = fuse_daytime_visible_into_density(
|
||||
density_u8,
|
||||
temp_c,
|
||||
visual_payloads,
|
||||
width=width,
|
||||
height=height,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
gc.collect()
|
||||
visual_webp_bytes = synthesize_geocolor_visual_webp(
|
||||
visual_payloads,
|
||||
fused_density,
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
gc.collect()
|
||||
return fused_density, visual_webp_bytes
|
||||
@@ -3,13 +3,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
import weakref
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -57,6 +58,41 @@ BASEMAP_TILE_SOURCES: tuple[str, ...] = (
|
||||
"earth_imagery_viirs_daily",
|
||||
)
|
||||
|
||||
# A contended semaphore holds its event loop, so the cache also keeps values weakly.
|
||||
_TILE_ENCODE_SEMAPHORES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, weakref.ReferenceType[asyncio.Semaphore]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
_INFLIGHT_TILE_FETCHES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
|
||||
|
||||
def _tile_encode_concurrency() -> int:
|
||||
raw = str(os.environ.get("PLANET_TILE_ENCODE_CONCURRENCY") or "2").strip()
|
||||
try:
|
||||
return max(1, min(8, int(raw)))
|
||||
except ValueError:
|
||||
return 2
|
||||
|
||||
|
||||
def _get_tile_encode_semaphore() -> asyncio.Semaphore:
|
||||
loop = asyncio.get_running_loop()
|
||||
semaphore_ref = _TILE_ENCODE_SEMAPHORES.get(loop)
|
||||
semaphore = semaphore_ref() if semaphore_ref is not None else None
|
||||
if semaphore is None:
|
||||
semaphore = asyncio.Semaphore(_tile_encode_concurrency())
|
||||
_TILE_ENCODE_SEMAPHORES[loop] = weakref.ref(semaphore)
|
||||
return semaphore
|
||||
|
||||
|
||||
def _get_inflight_tile_fetches() -> dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]:
|
||||
loop = asyncio.get_running_loop()
|
||||
inflight = _INFLIGHT_TILE_FETCHES.get(loop)
|
||||
if inflight is None:
|
||||
inflight = {}
|
||||
_INFLIGHT_TILE_FETCHES[loop] = inflight
|
||||
return inflight
|
||||
|
||||
DEFAULT_TILE_TEMPLATES: dict[str, str] = {
|
||||
"cloud_hd_tiles": (
|
||||
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
|
||||
@@ -589,29 +625,31 @@ async def _fetch_and_encode_tile(
|
||||
)
|
||||
ir_bytes = ir_res.content if _is_valid_image_response(ir_res) else None
|
||||
if _is_valid_image_response(primary_res):
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
primary_res.content,
|
||||
provider=provider,
|
||||
ir_bytes=ir_bytes,
|
||||
ir_provider=ir_provider,
|
||||
cos_sza=cos_sza,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
ir_z_src=ir_z_src,
|
||||
)
|
||||
async with _get_tile_encode_semaphore():
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
primary_res.content,
|
||||
provider=provider,
|
||||
ir_bytes=ir_bytes,
|
||||
ir_provider=ir_provider,
|
||||
cos_sza=cos_sza,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
ir_z_src=ir_z_src,
|
||||
)
|
||||
if ir_bytes is not None:
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
ir_bytes,
|
||||
provider=ir_provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
async with _get_tile_encode_semaphore():
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
ir_bytes,
|
||||
provider=ir_provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
if isinstance(primary_res, Exception) and raise_on_error:
|
||||
raise primary_res
|
||||
if isinstance(primary_res, httpx.Response) and primary_res.status_code not in (200, 404) and raise_on_error:
|
||||
@@ -632,15 +670,16 @@ async def _fetch_and_encode_tile(
|
||||
response.raise_for_status()
|
||||
if not _is_valid_image_response(response):
|
||||
return None
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
response.content,
|
||||
provider=provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
async with _get_tile_encode_semaphore():
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
response.content,
|
||||
provider=provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
|
||||
|
||||
async def get_or_fetch_tile(
|
||||
@@ -667,15 +706,39 @@ async def get_or_fetch_tile(
|
||||
pass
|
||||
return target.read_bytes(), True
|
||||
|
||||
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
|
||||
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
|
||||
webp_bytes = await _fetch_and_encode_tile(client, source_key, template, z, x, y)
|
||||
tile_key = (source_key, int(z), int(x), int(y))
|
||||
inflight = _get_inflight_tile_fetches()
|
||||
existing_task = inflight.get(tile_key)
|
||||
if existing_task is None or existing_task.done():
|
||||
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
|
||||
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
|
||||
|
||||
async def _load_and_persist() -> bytes | None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=timeout,
|
||||
follow_redirects=True,
|
||||
headers=headers,
|
||||
) as client:
|
||||
loaded = await _fetch_and_encode_tile(
|
||||
client, source_key, template, z, x, y
|
||||
)
|
||||
if loaded is not None:
|
||||
await asyncio.to_thread(_atomic_write_bytes, target, loaded)
|
||||
return loaded
|
||||
|
||||
existing_task = asyncio.create_task(_load_and_persist())
|
||||
inflight[tile_key] = existing_task
|
||||
existing_task.add_done_callback(
|
||||
lambda done_task: (
|
||||
inflight.pop(tile_key, None)
|
||||
if inflight.get(tile_key) is done_task
|
||||
else None
|
||||
)
|
||||
)
|
||||
|
||||
webp_bytes = await asyncio.shield(existing_task)
|
||||
if webp_bytes is None:
|
||||
return None, True
|
||||
|
||||
await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes)
|
||||
return webp_bytes, True
|
||||
|
||||
|
||||
|
||||
@@ -444,26 +444,36 @@ async def run_collector_task(collector_name: str):
|
||||
)
|
||||
|
||||
|
||||
async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
|
||||
async def cleanup_stale_running_tasks(
|
||||
max_age_hours: int = 2,
|
||||
*,
|
||||
include_all_running: bool = False,
|
||||
) -> int:
|
||||
"""Mark stale running tasks as failed after restarts or collector hangs."""
|
||||
cutoff = datetime.now(UTC) - timedelta(hours=max_age_hours)
|
||||
|
||||
async with async_session_factory() as db:
|
||||
result = await db.execute(
|
||||
select(CollectionTask).where(
|
||||
CollectionTask.status == JobStatus.RUNNING.value,
|
||||
conditions = [CollectionTask.status == JobStatus.RUNNING.value]
|
||||
if not include_all_running:
|
||||
conditions.extend(
|
||||
[
|
||||
CollectionTask.started_at.is_not(None),
|
||||
CollectionTask.started_at < cutoff,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async with async_session_factory() as db:
|
||||
result = await db.execute(select(CollectionTask).where(*conditions))
|
||||
stale_tasks = result.scalars().all()
|
||||
|
||||
cleanup_error = (
|
||||
"Marked failed automatically after backend restart"
|
||||
if include_all_running
|
||||
else "Marked failed automatically after stale running task cleanup"
|
||||
)
|
||||
for task in stale_tasks:
|
||||
task.status = JobStatus.FAILED.value
|
||||
task.phase = "failed"
|
||||
task.completed_at = datetime.now(UTC)
|
||||
existing_error = (task.error_message or "").strip()
|
||||
cleanup_error = "Marked failed automatically after stale running task cleanup"
|
||||
task.error_message = (
|
||||
f"{existing_error}\n{cleanup_error}".strip() if existing_error else cleanup_error
|
||||
)
|
||||
@@ -473,7 +483,10 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
|
||||
logger.warning_event(
|
||||
"Cleaned up stale running collection tasks",
|
||||
event="collector.cleanup.stale_tasks_cleaned",
|
||||
context={"count": len(stale_tasks)},
|
||||
context={
|
||||
"count": len(stale_tasks),
|
||||
"include_all_running": include_all_running,
|
||||
},
|
||||
)
|
||||
|
||||
return len(stale_tasks)
|
||||
|
||||
Reference in new issue
Block a user