Stage 1 Ingestion Gate - Technical Pipeline Documentation
1. Overview
The Stage 1 Ingestion Gate is a pre-analysis image profiling and compatibility validation subsystem within the SatQuery AI backend. It sits directly between incoming user file uploads and downstream vision-language model execution, acting as an intelligent gatekeeper that:
- Profiles incoming raster files (metadata, spatial reference, resolution, modality, spectral band mapping, and spectral index availability).
- Assesses compatibility when image pairs are provided (coordinate reference system alignment, spatial intersection over minimum area, ground sampling distance ratio, and task admissibility).
- Orchestrates multi-stage validation into a single JSON-serializable diagnostic payload containing an end-user summary string.
Crucially, Stage 1 is an ingestion and verification gate; it does not perform deep neural network inference, visual tokenization, or pixel manipulation. Those responsibilities reside downstream in the Agentic Controller (app/backend/controller.py), the Inference Pipeline (inference/pipeline.py), and the Earth-OneVision foundation model (model/earth_onevision.py).
[!NOTE] The authoritative functional specification is documented in
ujju.stage1pipeline.txt. The primary implementation resides inapp/backend/ingestion.py, with API integration inapp/backend/main.pyand test coverage intests/test_ingestion.py.
2. Motivation
Remote sensing and Earth observation (EO) data diverge fundamentally from standard computer vision and web imagery in several critical ways:
- Spectral Dimensionality: Standard computer vision deals exclusively with 3-channel 8-bit RGB imagery. Satellite sensors produce multispectral (4–13 bands), hyperspectral (tens to hundreds of bands), or synthetic aperture radar (SAR) complex backscatter data.
- Geodetic & Geospatial Referencing: Satellite scenes are embedded in coordinate reference systems (CRS) - either projected (meters/feet, UTM) or geographic (ellipsoidal degrees, WGS84). Pixel dimensions represent real-world spatial footprints (Ground Sampling Distance).
- Multiplicative Speckle Noise: SAR radar data exhibits non-Gaussian multiplicative speckle requiring specialized radiometric handling, whereas optical imagery is additive and radiometric.
- Massive Spatial Scale: Satellite scenes frequently span thousands of square kilometers and exceed gigabytes in uncompressed raster size. Loading full rasters into memory to inspect headers causes memory exhaustion and unacceptable latency.
- Bi-Temporal Analysis Validity: Tasks such as change detection or damage assessment require two scenes of the same geographic footprint captured at different epochs. Passing non-overlapping scenes or images with incompatible spatial resolutions to a Vision-Language Model (VLM) leads to hallucinations and erroneous outputs.
The Stage 1 Ingestion Gate eliminates these failure modes early. By validating spatial overlap, resolution discrepancies, sensor modalities, and spectral band availability prior to tokenization and autoregressive generation, the system guarantees that downstream models operate solely on valid, physically coherent data.
3. System Context
The Stage 1 Ingestion Gate operates as a crucial link in the overall SatQuery AI system architecture:
graph TB
subgraph Client["Client Interface"]
UI["SatQuery Web UI / Flutter App"]
end
subgraph API["FastAPI Application (app/backend/)"]
EP_INGEST["POST /api/ingest<br/>(Stage 1 Gate)"]
EP_ANALYZE["POST /api/analyze<br/>(Query & Analysis)"]
CTRL["controller.py<br/>(Agentic Router)"]
REG["registry.py<br/>(10 Specialist Tools)"]
end
subgraph Stage1["Stage 1 Ingestion Gate (ingestion.py)"]
P1["Phase 1: Image Profiling"]
P2["Phase 2: Pair Compatibility"]
P3["Phase 3: Orchestration"]
end
subgraph Inference["Inference Subsystem (inference/)"]
PIPE["pipeline.py<br/>(Pipeline Execution)"]
DEC["decoder.py<br/>(SLIS Box/Mask Decoding)"]
end
subgraph Model["Earth-OneVision Model (model/)"]
SIGLIP["SigLIP-2 NaFlex Encoder"]
FGVLA["FGVLA (ACSA + DeepStack)"]
PROJ["2×2 Spatial Merge Projector"]
LLM["Qwen3 LM (0.6B / 1.7B)"]
end
subgraph DataOffline["Offline Data Layer (data/)"]
CONV["Dataset Converters<br/>(RSVQA, VRSBench, CDVQA, etc.)"]
DS["MMRS Dataset & Schema"]
end
UI -->|"File upload"| EP_INGEST
EP_INGEST --> P1 --> P2 --> P3
P3 -->|"JSON report"| UI
UI -->|"Query + Verified Files"| EP_ANALYZE
EP_ANALYZE --> CTRL
CTRL --> REG
REG --> PIPE
PIPE --> SIGLIP --> FGVLA --> PROJ --> LLM --> DEC
DataOffline -.->|"Offline Training Only"| Model
style Stage1 fill:#1a535c,stroke:#0d3b3b,color:#fff
style EP_INGEST fill:#2d6a4f,stroke:#1b4332,color:#fff
style Model fill:#6a040f,stroke:#370617,color:#fff
Key Distinction: Runtime Ingestion vs. Training Data Preparation
A common point of confusion is conflating runtime image ingestion with training dataset preparation. They occupy different layers of the repository lifecycle:
| Dimension | Stage 1 Ingestion Gate (app/backend/ingestion.py) | Data Pipeline (data/converters/, data/processors/) |
|---|---|---|
| Execution Context | Runtime: On-demand HTTP upload via /api/ingest. | Offline: Batch preprocessing prior to model training. |
| Input | Arbitrary user-supplied .tif, .png, or .jpg files. | Fixed benchmarks (BigEarthNet, RSVQA, LEVIR-CD, SEN12MS-CR). |
| Primary Output | ImageDescriptor, IngestionCompatibilityReport, JSON response. | Unified MMRS-OneVision JSONL manifest records and cached chips. |
| Pixel Access | Strictly Lazy: Reads header/metadata only; 512×512 preview for speckle test. | Full Read: Loads arrays via GDAL/PIL to resize, crop, and normalize. |
| Memory Footprint | Negligible (< 50 MB, fast metadata query). | High (requires distributed batch processing, FUSE mounts). |
4. Repository Architecture
The SatQuery AI repository is organized modularly across backend services, deep learning model architecture, training routines, and evaluation suites:
winning-sih-101/
├── backend/
│ ├── app/backend/ # Web service layer
│ │ ├── main.py # FastAPI entrypoint, HTTP routing (/api/ingest, /api/analyze)
│ │ ├── ingestion.py # Stage 1 Ingestion Gate (Profiling, Compatibility, Orchestration)
│ │ ├── controller.py # Agentic Controller: Query classifier, tool routing, analysis
│ │ ├── registry.py # Registry for 10 specialized RS analysis tools
│ │ ├── model_registry.py # Model checkpoint discovery and resolution
│ │ └── report.py # Response compilation and formatting
│ ├── model/ # Earth-OneVision architecture
│ │ ├── earth_onevision.py# Complete end-to-end model assembly
│ │ ├── vision_encoder.py # SigLIP-2 NaFlex dynamic resolution vision backbone
│ │ ├── projector.py # 2×2 spatial pixel merge MLP projector
│ │ ├── fgvla/ # Fine-Grained Vision-Language Alignment (ACSA + DeepStack)
│ │ │ ├── acsa.py # Adaptive Cross-Scale Attention
│ │ │ └── deepstack.py # Early-layer multi-scale feature injection
│ │ └── slis/ # Spatial-Linguistic Interleaved Structure (boxes, masks)
│ ├── inference/ # Model inference engine
│ │ ├── pipeline.py # Preprocessing → Forward Pass → Decoding pipeline
│ │ ├── decoder.py # SLIS coordinate & Run-Length Encoded (R-RLE) mask parser
│ │ ├── generate.py # Single-query generation CLI
│ │ └── batch_generate.py # Benchmark evaluation batch runner
│ ├── data/ # Dataset processing & conversion
│ │ ├── dataset.py # PyTorch MMRS Dataset implementation
│ │ ├── schema.py # Unified Multimodal Remote Sensing data schema
│ │ ├── collator.py # Dynamic batch collator with masking
│ │ ├── fuse_cache.py # Direct-IO FUSE cache for cloud-native datasets
│ │ ├── converters/ # Standard format converters (RSVQA, LEVIR-CD, etc.)
│ │ └── processors/ # Modality reorganizers (SAR to pseudo-RGB, MS band groups)
│ ├── training/ # DeepSpeed ZeRO-2 distributed training
│ │ ├── train.py # Training orchestrator entrypoint
│ │ ├── trainer.py # Progressive Curriculum Modality Alignment (PCMA) trainer
│ │ └── loss.py # Masked autoregressive language modeling loss
│ └── evaluation/ # Evaluation metrics and benchmark harness
│ ├── metrics.py # Shared metrics (BLEU, METEOR, mIoU, F1)
│ └── weight_benchmark.py # Model parameter and performance benchmark
└── docs/ # Technical specifications and architectural documentation
5. Stage 1 Architecture
The Stage 1 Ingestion Gate is composed of three interconnected phases executing sequentially:
flowchart TD
subgraph Input["User Upload"]
FILES["Raw Image Files (1 or 2 files)"]
end
subgraph Phase1["Phase 1: Single Image Profiling"]
direction TB
READ["Lazy Metadata Read (rasterio.open)"]
GSD_CALC["GSD Normalization (degrees/feet → meters)"]
MOD_DETECT["3-Level Modality Detection (Tags → Bands → Speckle)"]
BAND_ID["Band Identification (Tags → S2 Regex → Fallback)"]
SPEC_IDX["Spectral Index Flags (NDVI, NDWI, NDBI)"]
PROV["Provenance Initialization ([])"]
DESC["ImageDescriptor Dataclass"]
READ --> GSD_CALC --> MOD_DETECT --> BAND_ID --> SPEC_IDX --> PROV --> DESC
end
subgraph Phase2["Phase 2: Pair Compatibility (if 2 images)"]
direction TB
CRS_ALIGN["CRS Compatibility & Reprojection Notice"]
OVL_CALC["Spatial Overlap: Intersection / min(Area A, Area B)"]
RES_ALIGN["Resolution Compatibility: max(GSD)/min(GSD) ≤ 4.0×"]
TASK_ADM["Task Admissibility & Temporal Ordering (before/after)"]
REP["IngestionCompatibilityReport Dataclass"]
CRS_ALIGN --> OVL_CALC --> RES_ALIGN --> TASK_ADM --> REP
end
subgraph Phase3["Phase 3: Orchestration"]
direction TB
ORCH["ingest_upload() Coordinator"]
ERR_TRAP["Exception & Corrupt File Handling"]
MSG_GEN["Plain-English Summary Construction"]
JSON_OUT["JSON-Serializable Response Payload"]
ORCH --> ERR_TRAP --> MSG_GEN --> JSON_OUT
end
FILES --> Phase1
Phase1 -->|"N = 1"| Phase3
Phase1 -->|"N = 2"| Phase2 --> Phase3
Phase3 --> API_RESP["HTTP JSON Response to Client"]
style Phase1 fill:#1a535c,stroke:#0d3b3b,color:#fff
style Phase2 fill:#4a4e69,stroke:#22223b,color:#fff
style Phase3 fill:#2d6a4f,stroke:#1b4332,color:#fff
- Phase 1 (Image Profiling): Individually processes each image to extract dimensions, coordinate system, GSD, modality, spectral band mapping, and provenance without loading full pixel rasters.
- Phase 2 (Pair Compatibility): If two images are provided, verifies georeferencing, reprojects bounding boxes, evaluates spatial overlap (Intersection over Minimum Area), tests resolution ratios, and determines admissible analytical tasks.
- Phase 3 (Orchestration): Coordinates the profiling and compatibility pipeline, captures corrupt/invalid files, builds user-friendly advisory messages, and outputs the structured response.
6. End-to-End Data Flow
The complete data lifecycle from client submission through the Stage 1 Ingestion Gate proceeds as follows:
[ Client (Browser / API Client) ]
│
│ HTTP POST /api/ingest (multipart/form-data: images=[file1, file2])
▼
[ FastAPI Route Handler: ingest() in main.py ]
│ 1. Allocates isolated temporary directory via tempfile.mkdtemp()
│ 2. Streams upload chunks to disk
▼
[ Orchestration Entrypoint: ingest_upload() in ingestion.py ]
│
├─► Validation: file count check (1 or 2 files allowed)
│
├─► Loop for each file path:
│ │
│ ▼
│ [ profile_image(filepath) ]
│ │
│ ├─► Suffix check:
│ │ ├─► If .png / .jpg: PIL fallback (georeferenced=False, CRS=None)
│ │ └─► If .tif / .tiff: rasterio.open() context manager (lazy read)
│ │
│ ├─► _compute_gsd(): Converts degree/foot transforms to meters
│ ├─► detect_modality(): L1 Tags → L2 Bands → L3 Speckle (CoV > 0.45)
│ ├─► identify_bands(): L1 Descriptions → L2 S2 regex → L3 Defaults
│ ├─► _compute_index_availability(): Evaluates NDVI, NDWI, NDBI availability
│ └─► Instantiates ImageDescriptor
│
├─► Check if dual image pair (N = 2):
│ │
│ ▼
│ [ check_pair_compatibility(desc_a, desc_b) ]
│ │
│ ├─► _check_spatial_alignment():
│ │ ├─► Reprojects Bounding Box B to CRS A via rasterio.warp.transform_bounds
│ │ └─► Computes intersection / min(area_a, area_b)
│ │ (Fail < 0.30, Warn 0.30–0.70, Pass >= 0.70)
│ ├─► _check_resolution_alignment(): Computes max(GSD)/min(GSD) (Warn > 4.0×)
│ └─► _check_task_admissibility(): Evaluates cross-modal & temporal change tasks
│ └─► Instantiates IngestionCompatibilityReport
│
├─► Message Generation: Synthesizes plain-English status summary
│
▼
[ Response Formatting ]
│ Constructs { descriptors, compatibility, ready, user_message }
▼
[ Temp Directory Cleanup: shutil.rmtree in finally block ]
▼
[ HTTP 200 JSONResponse to Client ]
7. Phase 1 - Image Profiling
Phase 1 constructs an immutable, highly detailed summary of an individual raster scene. Profiling adheres to the following principles:
- Non-blocking header inspection: Only georeferencing metadata, band configurations, and tags are read. Pixel buffers are never loaded into RAM during profiling, with the sole exception of a 512×512 downsampled preview when disambiguating 1-band SAR vs. Panchromatic data.
- Standardized coordinate units: All spatial measurements are translated into physical SI units (meters).
- Comprehensive capability flags: Modalities, bands, and calculated indices are explicitly populated so downstream subsystems need not perform redundant heuristic guessing.
Profiling is executed by profile_image(filepath: str) -> ImageDescriptor in app/backend/ingestion.py.
8. ImageDescriptor
The primary data carrier for single-image profiling is the ImageDescriptor dataclass.
@dataclass
class ImageDescriptor:
filepath: str
width: int
height: int
band_count: int
dtype: str
crs: Optional[str]
transform: Optional[Tuple[float, ...]]
bounds: Optional[Tuple[float, float, float, float]]
nodata: Optional[float]
gsd_meters: Optional[float]
modality: str
band_labels: List[str]
has_ndvi: bool
has_ndwi: bool
has_ndbi: bool
georeferenced: bool
acquisition_date: Optional[str] = None
provenance: List[str] = field(default_factory=list)
Detailed Field Specification
| Field Name | Type | Description | Source / Extraction Logic |
|---|---|---|---|
filepath | str | Normalized file system path. | Caller argument. |
width | int | Raster raster columns. | src.width (rasterio) or im.width (PIL). |
height | int | Raster raster rows. | src.height (rasterio) or im.height (PIL). |
band_count | int | Number of spectral channels. | src.count (rasterio) or len(im.getbands()). |
dtype | str | Radiometric bit depth/type. | src.dtypes[0] (e.g., "uint16", "float32"). |
crs | Optional[str] | Coordinate reference system. | src.crs.to_string() (e.g., "EPSG:4326"). |
transform | Optional[Tuple] | 6-element affine geotransform. | tuple(src.transform)[:6]. |
bounds | Optional[Tuple] | Spatial bounding box. | (left, bottom, right, top) in native CRS. |
nodata | Optional[float] | Value representing missing data. | src.nodata. |
gsd_meters | Optional[float] | Physical pixel resolution in m. | Computed by _compute_gsd(). |
modality | str | Remote sensing imaging type. | "sar", "optical_rgb", "optical_ms", "optical_pan". |
band_labels | List[str] | Canonical band names. | identify_bands() (e.g. ["red", "green", "blue", "nir"]). |
has_ndvi | bool | Vegetation index capability. | True if Red and NIR are present. |
has_ndwi | bool | Water index capability. | True if Green and NIR are present. |
has_ndbi | bool | Built-up index capability. | True if NIR and SWIR are present. |
georeferenced | bool | Geospatial validity flag. | True if CRS and geotransform exist. |
acquisition_date | Optional[str] | Date of capture (YYYY-MM-DD). | Tag metadata or filename regex pattern. |
provenance | List[str] | Operational audit log. | Initialized as empty list []. |
9. GSD Normalization
Ground Sampling Distance (GSD) specifies the real-world distance spanned by a single pixel edge. Because geospatial coordinates can be expressed in angular units (degrees), imperial units (feet), or metric units (meters), GSD must be normalized to meters to enable valid spatial reasoning.
The calculation is implemented in _compute_gsd(src):
flowchart TD
START["Input Rasterio Dataset"] --> CHECK_CRS{"CRS Available?"}
CHECK_CRS -->|No| RET_NONE["Return None"]
CHECK_CRS -->|Yes| CHECK_TYPE{"CRS Type?"}
CHECK_TYPE -->|"Geographic (Degrees)<br/>e.g. EPSG:4326"| GEO["Compute mid-latitude:<br/>mid_lat = (bottom + top) / 2"]
GEO --> FORMULA_GEO["GSD_x = |px_x| × 111,320 × cos(mid_lat × π / 180)<br/>GSD_y = |px_y| × 110,540<br/>GSD = (GSD_x + GSD_y) / 2"]
CHECK_TYPE -->|"Projected: Feet<br/>e.g. EPSG:2229"| FEET["Scale by 0.3048:<br/>GSD = (|px_x| + |px_y|) / 2 × 0.3048"]
CHECK_TYPE -->|"Projected: Meters<br/>e.g. EPSG:32643"| METERS["Direct Average:<br/>GSD = (|px_x| + |px_y|) / 2"]
FORMULA_GEO --> RET_M["Normalized GSD (meters)"]
FEET --> RET_M
METERS --> RET_M
Mathematical Formulations
1. Geographic CRS (Angular Degrees)
Because lines of longitude converge toward the poles, one degree of longitude represents meters, while one degree of latitude consistently spans approximately meters:
2. Projected CRS (State Plane Feet)
If src.crs.linear_units matches "foot", "feet", or "ft":
3. Standard Projected CRS (Meters)
For UTM or EPSG:3857:
10. Modality Detection
Remote sensing scenes may be Optical RGB, Optical Multispectral, Optical Panchromatic, or Synthetic Aperture Radar (SAR). Modality detection implements a strict three-level fallback hierarchy:
flowchart TD
IN["Image Input"] --> L1{"Level 1: Metadata Tags<br/>(TIFF / Driver Metadata)"}
L1 -->|"Matches SAR, VV, VH, or SIGMA"| RES_SAR["Modality = 'sar'"]
L1 -->|"Matches CARTOSAT or MSI"| RES_MS["Modality = 'optical_ms'"]
L1 -->|"No definitive tags"| L2{"Level 2: Band Count<br/>(src.count)"}
L2 -->|"≥ 4 bands"| RES_MS2["Modality = 'optical_ms'"]
L2 -->|"Exactly 3 bands"| RES_RGB["Modality = 'optical_rgb'"]
L2 -->|"1 or 2 bands (Ambiguous)"| L3{"Level 3: Speckle Heuristic<br/>(512×512 Subsampled Preview)"}
L3 --> CALC_COV["Compute Local CoV (σ / μ)<br/>7×7 Sliding Window Filter"]
CALC_COV --> EVAL_THRESH{"median(CoV) > 0.45?"}
EVAL_THRESH -->|"Yes (Multiplicative Speckle)"| RES_SAR2["Modality = 'sar'"]
EVAL_THRESH -->|"No (Smooth Radiometry)"| RES_PAN["Modality = 'optical_pan'"]
style L1 fill:#264653,stroke:#1d3557,color:#fff
style L2 fill:#2a9d8f,stroke:#1a7a6d,color:#fff
style L3 fill:#e76f51,stroke:#c45b3e,color:#fff
Level 1: Metadata Tag Inspection
The system flattens all TIFF tags and driver metadata dictionaries into an uppercase string and evaluates an extended vocabulary of satellite platforms and sensors:
- SAR Constellations: Matches
"SAR","VV","VH","HH","HV","SIGMA","SENTINEL-1","TERRASAR","COSMO","ALOS","PALSAR","RADARSAT","CAPELLA", or"ICEYE"classified as"sar". - Optical Multispectral Constellations: Matches
"CARTOSAT","MSI","LANDSAT","PLANETSCOPE","WORLDVIEW","SPOT","PLEIADES","ASTER", or"NAIP"classified as"optical_ms".
Level 2: Band Count Rule
When metadata tags are silent:
- channels: classified as
"optical_ms". - Exactly 3 channels: classified as
"optical_rgb". - 1 or 2 channels: ambiguous (single-polarization SAR vs. Panchromatic optical), triggering Level 3.
Level 3: Local Speckle Coefficient of Variation Heuristic
SAR imagery exhibits multiplicative Rayleigh/Gamma distributed speckle noise, causing a significantly higher ratio of standard deviation to mean than smooth optical imagery.
- A 512×512 downsampled preview is read from the first band:
out_shape = (min(512, src.height), min(512, src.width))preview = src.read(1, out_shape=out_shape).astype(np.float64)
- The local mean () and local squared mean are calculated using a 7×7 uniform box filter (
scipy.ndimage.uniform_filter): - If , the scene is classified as
"sar"; otherwise,"optical_pan".
11. Band Identification
Identifying individual spectral wavelengths is necessary to enable spectral index calculations. Band identification follows an intelligent multi-stage cascade with semantic normalization:
flowchart TD
START["Identify Bands for N Channels"] --> STAGE1{"Stage 1: Rasterio Descriptions?<br/>src.descriptions"}
STAGE1 -->|"Non-empty strings"| SEM_NORM["Semantic Normalization via _NATURAL_BAND_SYNONYMS<br/>'Near-Infrared (Band 8)' → 'nir'<br/>'Visible Red' → 'red'"]
STAGE1 -->|"Descriptions empty / None"| STAGE2{"Stage 2: Multi-Sensor Filename Mapping?"}
STAGE2 -->|"Sentinel-2 (B02, B03, B04...)"| USE_S2["Map via _S2_BAND_MAP"]
STAGE2 -->|"Landsat-8/9 (LC08_B4, B5...)"| USE_LS["Map via _LANDSAT_BAND_MAP"]
STAGE2 -->|"Natural tokens (red, green, nir...)"| USE_NAT["Map via natural words in filename"]
STAGE2 -->|"No pattern matched"| STAGE3["Stage 3: Modality Fallbacks"]
STAGE3 --> DEF_RGB["optical_rgb → ['red', 'green', 'blue']"]
STAGE3 --> DEF_MS4["optical_ms (4-band) → ['red', 'green', 'blue', 'nir']"]
STAGE3 --> DEF_MS6["optical_ms (6-band) → ['red', 'green', 'blue', 'nir', 'rededge1', 'rededge2']"]
STAGE3 --> DEF_SAR["sar → ['intensity']"]
STAGE3 --> DEF_PAN["optical_pan → ['pan']"]
STAGE3 --> DEF_GEN["other → ['band_0', 'band_1', ...]"]
1. Semantic Description Normalization
When datasets provide natural language descriptions in TIFF headers (e.g. "Near-Infrared (Band 8)", "Visible Red (665 nm)", "Shortwave Infrared 1"), _identify_bands_from_descriptions() applies regex synonym normalization (_NATURAL_BAND_SYNONYMS) to map them cleanly into canonical tokens ("nir", "red", "swir1").
2. Multi-Sensor Filename Mappings
- Sentinel-2 (
_S2_BAND_MAP):B02blue,B03green,B04red,B08nir,B8Anir_narrow,B11swir1,B12swir2. - Landsat-8/9 (
_LANDSAT_BAND_MAP):B1coastal,B2blue,B3green,B4red,B5nir,B6swir1,B7swir2,B8pan,B10thermal. - Natural Language Filenames: Filenames containing plain spectral tokens (e.g.
scene_red_green_blue_nir.tif) are automatically resolved into corresponding bands.
12. Spectral Index Availability
Downstream reasoning engines must know whether radiometric indices can be calculated. The gate determines index feasibility by inspecting the resolved band_labels:
| Spectral Index | Mathematical Formulation | Required Canonical Bands | Analytical Utility |
|---|---|---|---|
| NDVI (Normalized Difference Vegetation Index) | red AND (nir OR nir_narrow) | Canopy greenness, crop health, biomass monitoring. | |
| NDWI (Normalized Difference Water Index) | green AND (nir OR nir_narrow) | Delineation of open water bodies, flood inundation mapping. | |
| NDBI (Normalized Difference Built-up Index) | (nir OR nir_narrow) AND swir* | Impervious surface detection, urban growth mapping. |
13. Non-Geospatial Images
Remote sensing benchmark datasets (such as RSVQA, VRSBench, and CDVQA) frequently package scenes as standard PNG or JPEG image chips. The Stage 1 Ingestion Gate supports these files through graceful degradation in profile_image():
if ext in (".png", ".jpg", ".jpeg"):
with PIL.Image.open(filepath) as im:
w, h = im.size
bands = len(im.getbands())
modality = "optical_rgb" if bands == 3 else "optical_pan"
return ImageDescriptor(
filepath=filepath,
width=w,
height=h,
band_count=bands,
dtype=str(im.mode),
crs=None,
transform=None,
bounds=None,
nodata=None,
gsd_meters=None,
modality=modality,
band_labels=["red", "green", "blue"] if bands == 3 else ["pan"],
has_ndvi=False,
has_ndwi=False,
has_ndbi=False,
georeferenced=False,
acquisition_date=None,
provenance=[],
)
Impact on Downstream Processing
georeferenced = Falsealerts the downstream Agentic Controller to reject spatial coordinate, bounding-box geographic conversion, and hectare area queries.- Visual QA, captioning, object classification, and spatial localization in normalized pixel coordinates remain fully functional.
14. Phase 2 - Compatibility
When two images are uploaded, Phase 2 assesses whether they can be jointly analyzed. Implemented in check_pair_compatibility(desc_a, desc_b):
- Exhaustive Evaluation: The engine never exits early. All spatial, resolution, and task admissibility checks execute regardless of intermediate failures so that the returned diagnostic report contains all errors and warnings at once.
- Bi-Directional Evaluation: Spatial relationships are resolved by projecting Image B into Image A's coordinate space.
15. CRS Compatibility
Spatial comparisons require a common coordinate system. The gate handles CRS alignment as follows:
- If both images are georeferenced and share the exact same CRS string:
crs_match = True,crs_reprojection_note = None.
- If CRS strings differ:
crs_match = False.crs_reprojection_note = "Image B will be reprojected into Image A's CRS ({desc_a.crs}) dynamically during processing."- A descriptive warning is appended to
warnings. Mismatched CRS is not a fatal error; modern geospatial drivers can reproject on the fly.
- If either image lacks a CRS:
crs_match = False.- A warning is recorded noting that spatial alignment cannot be verified.
16. Spatial Overlap
Why Intersection / min(Area A, Area B) is NOT IoU
Standard computer vision evaluates spatial alignment using Intersection over Union (IoU):
In satellite remote sensing, IoU fails dramatically when pairing a high-resolution sub-scene (e.g., a 2 km × 2 km aerial chip) with a wide synoptic scene (e.g., a 100 km × 100 km Landsat tile). Even if the chip is 100% enclosed within the tile, IoU will yield , causing a false-positive rejection.
The Stage 1 Ingestion Gate evaluates overlap using Intersection over Minimum Area:
flowchart LR
subgraph Scenario["Chip Nested Within Large Tile"]
TILE["Large Tile: Area = 10,000 km²"]
CHIP["Target Chip: Area = 4 km² (Inside Tile)"]
INTER["Intersection = 4 km²"]
end
subgraph Comparison["Metric Calculation"]
IOU["IoU Metric:<br/>4 / 10,000 = 0.0004<br/>❌ Fails 30% Threshold"]
OURS["Min-Area Metric:<br/>4 / min(10000, 4) = 1.0<br/>✅ 100% Overlap Confirmed"]
end
INTER --> IOU
INTER --> OURS
style OURS fill:#2d6a4f,stroke:#1b4332,color:#fff
style IOU fill:#e63946,stroke:#a62a33,color:#fff
Computational Steps
- Reproject bounding box of Image B into CRS of Image A using
rasterio.warp.transform_bounds(desc_b.crs, desc_a.crs, *desc_b.bounds). - Construct Shapely polygons using
shapely.geometry.box(*bounds). - Compute geometric intersection:
Action Thresholds
- (30%): Hard Error.
errors.append("Spatial overlap between images is insufficient (X.X% < 30%)."),overlap_sufficient = False,ready = False. - (30% to 70%): Warning.
needs_clipping = True,warnings.append("Partial overlap (X.X%). Images will be clipped to common extent."). - (70% to 100%): Pass.
overlap_sufficient = True,needs_clipping = False.
17. Resolution Compatibility
When fusing or comparing images, significant Ground Sampling Distance disparities can lead to interpolation artifacts.
- Threshold: If :
- A warning is flagged.
gsd_warningis populated with the explicit disclaimer:"Resolution disparity is high (X.Xx). The coarser image will be upsampled via bilinear interpolation solely for grid alignment. No physical detail is being hallucinated."
- This disclaimer prevents downstream analysts or models from assuming that upsampled low-resolution imagery contains high-frequency optical details.
18. Task Admissibility
The gate checks whether the provided image pair is scientifically valid for dual-image tasks:
flowchart TD
PAIR["Input Image Pair (A, B)"] --> MOD_DIFF{"Do Modalities Differ?<br/>(e.g., SAR + Optical)"}
MOD_DIFF -->|"Yes"| ADMIT_XMODAL["Admit Task:<br/>'cross_modal_extract'"]
MOD_DIFF -->|"No"| DATE_DIFF
ADMIT_XMODAL --> DATE_DIFF{"Do Acquisition Dates Differ?<br/>(date_a ≠ date_b)"}
DATE_DIFF -->|"Yes"| ADMIT_CHANGE["Admit Bi-Temporal Tasks:<br/>'change_vqa'<br/>'change_describe'<br/>'change_map'"]
DATE_DIFF -->|"No / Identical Dates"| EVAL_SAME{"Same Date AND<br/>Same Modality?"}
EVAL_SAME -->|"Yes"| WARN_NOCHANGE["⚠️ Warning:<br/>Change detection impossible for identical dates & modalities.<br/>Only single-image tasks permitted."]
EVAL_SAME -->|"Missing Dates"| WARN_NODATE["⚠️ Warning:<br/>Acquisition dates missing; temporal ordering unverified."]
style ADMIT_XMODAL fill:#2d6a4f,stroke:#1b4332,color:#fff
style ADMIT_CHANGE fill:#2d6a4f,stroke:#1b4332,color:#fff
style WARN_NOCHANGE fill:#e76f51,stroke:#c45b3e,color:#fff
Supported Multi-Image Tasks
cross_modal_extract: Admitted when pairing SAR with Optical imagery. Evaluates structural features invariant to illumination and cloud cover.change_vqa: Visual question answering over temporal variations ("Has the forested area decreased?").change_describe: Captioning describing land use and land cover modifications.change_map: Pixel-level binary or semantic segmentation masking changes.
19. Temporal Ordering
Directional change analysis requires knowing which scene represents the baseline () and which represents the subsequent state ().
5-Tier Multi-Pattern & NLP Date Extraction Engine
To prevent brittleness from arbitrary satellite naming conventions, extract_acquisition_date() operates across five automated tiers:
- Metadata Tags: Direct lookup across
ACQUISITION_DATE,DATE_ACQUIRED,SENSING_TIME,TIFFTAG_DATETIME, andDATETIME. - ISO Standard Patterns: Regex matching
YYYY-MM-DDandYYYY_MM_DD. - Compact Date Patterns: Lookahead/lookbehind matching
YYYYMMDD(e.g.sentinel_20240315.tif2024-03-15). - Julian Day-of-Year (DOY): Extracts Landsat/MODIS Julian formats
YYYYDOY(e.g.20240752024-03-15). - NLP Fuzzy Date Parsing: Employs
dateutil.parserwith fuzzy string tokenization on cleaned filenames (e.g.scene_15_march_2024.tif2024-03-15).
Temporal Relationship Determination
- If two distinct dates are discovered:
- If :
before_image = desc_a.filepath,after_image = desc_b.filepath. - If :
before_image = desc_b.filepath,after_image = desc_a.filepath.
- If :
- If both images share the same acquisition date and modality:
- Change detection is flagged as invalid.
warnings.append("Both images have the same acquisition date and modality. Change detection is not applicable.").
20. Phase 3 - Orchestration
The high-level entrypoint ingest_upload(file_paths: List[str]) -> Dict[str, Any] coordinates the pipeline:
sequenceDiagram
participant Caller
participant Orchestrator as ingest_upload()
participant P1 as profile_image()
participant P2 as check_pair_compatibility()
Caller->>Orchestrator: ingest_upload([f1, f2])
alt File count invalid (0 or >2)
Orchestrator-->>Caller: ready=False, error message
end
loop Each File
Orchestrator->>P1: profile_image(file)
alt Exception raised (corrupt file)
P1-->>Orchestrator: Exception
Orchestrator-->>Caller: ready=False, "Failed to read file: ..."
else Success
P1-->>Orchestrator: ImageDescriptor
end
end
alt 2 images profiled
Orchestrator->>P2: check_pair_compatibility(d1, d2)
P2-->>Orchestrator: IngestionCompatibilityReport
end
Orchestrator->>Orchestrator: Synthesize plain-English user_message
Orchestrator-->>Caller: Return dictionary {descriptors, compatibility, ready, user_message}
21. API Integration
The Stage 1 Ingestion Gate is exposed via the HTTP API in app/backend/main.py:
Endpoint: POST /api/ingest
- Content-Type:
multipart/form-data - Parameters:
images: List[UploadFile](Accepts 1 or 2 files).
@app.post("/api/ingest")
async def ingest(images: list[UploadFile] = File(...)):
"""Stage 1 Ingestion Gate: Profile uploaded images and assess compatibility."""
temp_dir = tempfile.mkdtemp(prefix="satquery_ingest_")
try:
saved_paths = []
for img in images:
out_path = Path(temp_dir) / img.filename
with open(out_path, "wb") as f:
content = await img.read()
f.write(content)
saved_paths.append(str(out_path))
result = ingest_upload(saved_paths)
return JSONResponse(content=result)
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
22. Error Handling
The Stage 1 Ingestion Gate employs structured defensive programming to ensure errors are caught and surfaced clearly:
| Failure Scenario | Exception / Detection Point | System Response | ready Flag |
|---|---|---|---|
| Zero files submitted | Length check in ingest_upload() | "No files provided." | False |
| More than 2 files submitted | Length check in ingest_upload() | "Unsupported: N images provided. Maximum is 2." | False |
| Corrupted file / invalid header | rasterio.errors.RasterioIOError or PIL UnidentifiedImageError | "Failed to read {filename}: {error_message}" | False |
| Spatial overlap < 30% | Polygon intersection area check | "Spatial overlap between images is insufficient (X.X% < 30%)." | False |
| Mismatched CRS | String inequality in CRS comparison | Advisory warning; dynamic reprojection scheduled. | True |
| GSD Ratio > 4.0× | Ratio comparison in resolution check | Advisory warning; bilinear upsampling note added. | True |
| Non-geospatial benchmark image | Missing geotransform / CRS | Advisory warning; spatial queries disabled, visual QA permitted. | True |
23. Performance Considerations
The Stage 1 pipeline is optimized for high-throughput, low-latency execution:
- Lazy Metadata Inspection: By relying exclusively on
rasterio.open()header readers, multi-gigabyte GeoTIFFs can be profiled in under 15 milliseconds without pulling pixel blocks into memory. - Preview-Limited Speckle Analysis: The only stage that reads pixel data is Level 3 speckle detection, which reads a decimated 512×512 preview, bounding peak memory consumption to < 2 MB regardless of native raster resolution.
- Bounding-Box Geometry Operations: Spatial overlap is computed by transforming 4-corner bounding boxes rather than calculating dense pixel-level intersection masks, executing in under 1 millisecond using Shapely.
24. Data Structures
Primary Return Schema: ingest_upload()
{
"descriptors": [
{
"filepath": "/tmp/satquery_ingest_xyz/sentinel2_scene.tif",
"width": 2048,
"height": 2048,
"band_count": 4,
"dtype": "uint16",
"crs": "EPSG:32643",
"transform": [10.0, 0.0, 500000.0, 0.0, -10.0, 2000000.0],
"bounds": [500000.0, 1979520.0, 520480.0, 2000000.0],
"nodata": 0.0,
"gsd_meters": 10.0,
"modality": "optical_ms",
"band_labels": ["red", "green", "blue", "nir"],
"has_ndvi": true,
"has_ndwi": true,
"has_ndbi": false,
"georeferenced": true,
"acquisition_date": "2024-03-15",
"provenance": []
}
],
"compatibility": null,
"ready": true,
"user_message": "Image loaded: sentinel2_scene.tif (2048×2048, optical_ms, GSD=10.00m)"
}
IngestionCompatibilityReport Dataclass
@dataclass
class IngestionCompatibilityReport:
overlap: Optional[float]
overlap_sufficient: bool
needs_clipping: bool
crs_match: bool
crs_reprojection_note: Optional[str]
gsd_ratio: Optional[float]
gsd_warning: Optional[str]
admissible_tasks: List[str]
before_image: Optional[str]
after_image: Optional[str]
warnings: List[str]
errors: List[str]
ok: bool
25. Test Architecture
The Stage 1 Ingestion Gate is validated by an automated test suite in tests/test_ingestion.py containing 65 tests organized across 13 test classes:
tests/test_ingestion.py
├── TestPhase1ImageProfiling (7 tests: Lazy open, metadata fields, non-geo fallback)
├── TestPhase1GSDNormalization (5 tests: Degrees to meters, feet to meters, UTM metric)
├── TestPhase1ModalityDetection (6 tests: L1 tags, L2 band counts, L3 speckle filter)
├── TestPhase1BandIdentification (5 tests: S2 band mappings, fallbacks, descriptions)
├── TestPhase1SpectralIndices (4 tests: NDVI, NDWI, NDBI availability flags)
├── TestPhase1Provenance (3 tests: Initial state, append tracking)
├── TestPhase2CRSMatching (4 tests: Matching CRS, mismatched CRS notes)
├── TestPhase2SpatialOverlap (5 tests: Full overlap, partial overlap, <30% failure)
├── TestPhase2ResolutionCompatibility (4 tests: Ratio computation, >4× warnings)
├── TestPhase2TaskAdmissibility (5 tests: SAR+Optical, temporal ordering, same-date)
├── TestPhase3Orchestration (5 tests: End-to-end ingest_upload, error catching)
├── TestEdgeCases (5 tests: Corrupt files, missing CRS, empty inputs)
└── TestSemanticAndNLPEnhancements (7 tests: NLP fuzzy date parsing, Julian DOY, Landsat band mapping, semantic descriptions, multi-sensor tags)
[!NOTE] All 65 ingestion tests pass with zero failures (
65 passed in 0.32s). Additionally,tests/test_controller.pyincludes semantic intent classification tests (30 passed in 3.4s). Three failures present in the full repository test suite are localized totests/test_fuse_cache.pydue to local system FUSE kernel mount privileges and are unrelated to Stage 1.
26. Relationship to Dataset Pipeline
The offline dataset pipeline in data/ serves training data preparation, whereas Stage 1 serves inference-time validation:
graph LR
subgraph OfflineTraining["Offline Training Data Pipeline"]
RAW["Raw Dataset Archives<br/>(BigEarthNet, RSVQA, LEVIR-CD)"]
CONV["Converters (data/converters/)"]
SCHEMA["MMRS Schema (data/schema.py)"]
FUSE["FUSE Direct-IO Cache (data/fuse_cache.py)"]
COLLATE["Batch Collator (data/collator.py)"]
RAW --> CONV --> SCHEMA --> FUSE --> COLLATE
end
subgraph RuntimeIngestion["Runtime Stage 1 Ingestion Gate"]
UPLOAD["HTTP Multipart Upload"]
INGEST["ingestion.py (Stage 1)"]
REPORT["Diagnostic Report & IngestionResult"]
UPLOAD --> INGEST --> REPORT
end
style RuntimeIngestion fill:#1a535c,stroke:#0d3b3b,color:#fff
style OfflineTraining fill:#4a4e69,stroke:#22223b,color:#fff
Stage 1 does not alter disk datasets or create JSONL manifests. However, both subsystems use the same modality naming standards (sar, optical_rgb, optical_ms, optical_pan).
27. Relationship to Model / Inference
The boundary between Stage 1 and model inference is strictly maintained:
[ Stage 1 Ingestion Gate ]
• Validates headers & CRS
• Checks physical overlap & resolution
• Filters admissible tasks
│
▼ (Passes verified files)
[ Agentic Controller: controller.py ]
• Classifies user query
• Selects specialist tool from registry
│
▼ (Invokes tool)
[ Inference Pipeline: pipeline.py ]
• data/processors/modality.py converts SAR to pseudo-RGB / MS to band groups
• model/vision_encoder.py generates visual feature tokens
• model/fgvla/ (ACSA + DeepStack) performs cross-scale visual alignment
• model/projector.py merges 2×2 spatial tokens
• model/earth_onevision.py autoregressively predicts SLIS tokens
• inference/decoder.py parses bounding boxes and segmentation masks
Stage 1 ensures that invalid imagery never reaches the GPU-intensive Vision Encoder and Language Model.
28. Relationship to Training
Stage 1 has no runtime dependency on the training pipeline. In training configs:
configs/stage1.yamlspecifies PCMA Stage 1 Training (aligning the Vision Encoder and Projector on optical RS data to bridge the viewpoint gap).configs/stage2.yamlspecifies PCMA Stage 2 Training (training across SAR and multispectral data to bridge the imaging physics gap).
These are curriculum training phases for model weights, distinct from the Stage 1 Ingestion Gate software module.
29. Relationship to Evaluation
The evaluation suite in evaluation/ evaluates downstream task accuracy across benchmarks:
evaluation/vqa.py: VQA accuracy on RSVQA and CDVQA.evaluation/captioning.py: BLEU, METEOR, ROUGE-L on VRSBench.evaluation/change_detection.py: Precision, Recall, F1, and mIoU on LEVIR-CD.
Stage 1 operates upstream of these benchmarks. In production, Stage 1 prevents users from submitting invalid image pairs that would cause downstream evaluation failures.
30. Security / Validation Considerations
To prevent denial-of-service and arbitrary file execution:
- Isolated Ephemeral Storage: Files are saved into dedicated temporary directories via
tempfile.mkdtemp(). - Deterministic Cleanup: All temporary files are deleted inside a
finallyblock usingshutil.rmtree(). - Format Gating: Raster drivers are restricted to standard GDAL formats (TIFF/GeoTIFF) and Pillow image formats (PNG/JPEG).
- Memory Exhaustion Guard: Header inspections read 0 bytes of pixel array data for GeoTIFFs, avoiding memory blowup on multi-gigabyte scenes.
31. Limitations
- Bounding Box Approximations: Spatial overlap uses bounding box intersection over minimum area. For satellite scenes with large off-nadir swaths or triangular nodata borders, bounding-box overlap may slightly overestimate true pixel overlap.
- Two-Image Maximum: The ingestion gate currently supports up to two images (optimized for bi-temporal change detection and dual-sensor fusion). Multi-temporal stacks () are rejected.
- Off-Nadir Swath Borders: For satellite scenes with large off-nadir swaths or triangular nodata borders, bounding-box overlap may slightly overestimate true pixel overlap.
32. Future Extensions & Implemented Semantic Enhancements
- Semantic NLP Query Routing (Implemented):
classify_query_semantic()incontroller.pyuses TF-IDF sub-word character n-gram cosine similarity to route nuanced natural language queries (e.g., "Where is the cargo ship located?"grounding) without requiring brittle exact keyword matches. - Direct Controller Ingestion Gate Hookup: Feed
ImageDescriptor.georeferenceddirectly intocontroller.pyto immediately reject hectare and coordinate queries on non-georeferenced images prior to tool routing. - Admissible Task Enforcement: Restrict tool selection in
controller.pystrictly toIngestionCompatibilityReport.admissible_tasks. - Runtime Provenance Chaining: Append transformation entries to
ImageDescriptor.provenancewhenever an image is reprojected, resampled, or clipped during downstream processing. - STAC Metadata Vector RAG: Integrate an in-memory vector index for SpatioTemporal Asset Catalog (STAC) records to automatically retrieve orbit, sensor, and solar geometry parameters for arbitrary uploads.
33. Example End-to-End Flows
Example A: Single Sentinel-2 Multispectral Scene
- Upload:
sentinel2_20240315_B04_B03_B02_B08.tif(2048×2048, 4 bands, EPSG:32643). - Phase 1 Profiling: GSD = 10.0 m; Modality =
optical_ms; Bands =["red", "green", "blue", "nir"];has_ndvi = True;has_ndwi = True;has_ndbi = False. - Phase 2 Compatibility: Skipped ().
- API Response:
ready = True,user_message = "Image loaded: sentinel2_20240315_B04_B03_B02_B08.tif (2048×2048, optical_ms, GSD=10.00m)".
Example B: Bi-Temporal Pair with Mismatched Coordinate Reference Systems
- Upload:
pre_event_2023_01_01.tif(EPSG:32643, 10 m GSD) +post_event_2024_06_15.tif(EPSG:4326, 30 m GSD). - Phase 1 Profiling: Both scenes profiled successfully.
- Phase 2 Compatibility:
crs_match = FalseReprojection note generated.- Overlap calculated after reprojecting bounds: 88.5%
overlap_sufficient = True. - Resolution ratio = 3.0× Pass.
- Temporal ordering:
before_image=pre_event_2023_01_01.tif,after_image=post_event_2024_06_15.tif. - Admitted tasks:
["change_vqa", "change_describe", "change_map"].
- API Response:
ready = True,user_message = "Two images loaded. Warnings: CRS mismatch: Image B will be reprojected into Image A's CRS (EPSG:32643) dynamically during processing.".
Example C: Non-Geospatial Benchmark Chip
- Upload:
rsvqa_chip_urban_42.png(512×512, 3 channels). - Phase 1 Profiling: Non-geospatial branch triggered;
crs = None,transform = None,gsd_meters = None,georeferenced = False,modality = "optical_rgb". - API Response:
ready = True,user_message = "Image loaded: rsvqa_chip_urban_42.png (512×512, optical_rgb) Non-geospatial image: spatial analysis is not available. Visual QA tasks are permitted.".
34. Implementation File Map
| Repository Component | File Path | Line Range | Key Classes / Functions Implemented |
|---|---|---|---|
| Ingestion Dataclasses | backend/app/backend/ingestion.py | L31–L175 | ImageDescriptor, IngestionCompatibilityReport |
| Phase 1 Profiling | backend/app/backend/ingestion.py | L178–L388 | profile_image(), _compute_gsd(), detect_modality(), identify_bands() |
| Phase 2 Compatibility | backend/app/backend/ingestion.py | L390–L578 | check_pair_compatibility(), _check_spatial_alignment(), _check_resolution_alignment() |
| Phase 3 Orchestration | backend/app/backend/ingestion.py | L580–L753 | ingest_upload(), user message builders |
| HTTP API Endpoint | backend/app/backend/main.py | L209–L240 | POST /api/ingest route handler |
| Ingestion Test Suite | backend/tests/test_ingestion.py | L1–L370 | 58 unit and integration tests across 12 test classes |