File size: 7,314 Bytes
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac6b2e
7529108
 
 
 
 
 
8ac6b2e
7529108
 
 
 
8ac6b2e
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac6b2e
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""
GaiaScale Backend Application Server

High-Performance FastAPI Server for Multispectral Satellite Super-Resolution Mapper.
"""

from __future__ import annotations

import argparse
import os
import shutil
import sys
from pathlib import Path

# Ensure backend root is on sys.path
BACKEND_DIR = Path(__file__).resolve().parent
if str(BACKEND_DIR) not in sys.path:
    sys.path.insert(0, str(BACKEND_DIR))
if str(BACKEND_DIR.parent) not in sys.path:
    sys.path.insert(0, str(BACKEND_DIR.parent))

from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.concurrency import run_in_threadpool
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse

try:
    from backend.config import UPLOADS_DIR, DEVICE
    from backend.schemas import InferenceResponse, HealthResponse
    from backend.services.inference import inference_engine, run_gpu_inference
    from backend.services.cleanup import cleanup_worker, cleanup_uploads_now
except ImportError:
    from config import UPLOADS_DIR, DEVICE
    from schemas import InferenceResponse, HealthResponse
    from services.inference import inference_engine, run_gpu_inference
    from services.cleanup import cleanup_worker, cleanup_uploads_now


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan manager that starts the daily 02:00 AM uploads cleanup worker."""
    cleanup_worker.start()
    yield
    cleanup_worker.stop()


app = FastAPI(
    title="GaiaScale Super-Resolution API",
    description="Physics-Consistent 4-Band Sentinel-2 (10 m -> 2.5 m) Super-Resolution Mapper",
    version="3.2.0",
    lifespan=lifespan
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ============================================================================
# 1. HEALTH ENDPOINT
# ============================================================================
@app.get("/health", response_model=HealthResponse, tags=["Health"])
@app.get("/api/health", response_model=HealthResponse, tags=["Health"])
def get_health():
    """Returns system status, active super-resolution model, and compute hardware."""
    return {
        "status": "healthy",
        "models": inference_engine.available_models,
        "device": str(inference_engine.device)
    }


# ============================================================================
# 2. UPLOAD & INFERENCE ENDPOINT
# ============================================================================
@app.post("/upload", response_model=InferenceResponse, tags=["Inference"])
@app.post("/api/upload", response_model=InferenceResponse, tags=["Inference"])
async def upload_file(
    file: UploadFile = File(..., description="Satellite imagery or GeoTIFF (.tif, .tiff, .npz, .png, .jpg, .jpeg)")
):
    """
    Upload a satellite scene or multi-band image for 4x spatial super-resolution (10 m -> 2.5 m).
    Runs tiled sliding-window inference with 2D Hann-window alpha blending using GaiaScale-HAT.
    """
    filename = Path(file.filename).name if file.filename else "upload.tif"
    ext = Path(filename).suffix.lower()
    valid_exts = {".tif", ".tiff", ".ttif", ".npz", ".png", ".jpg", ".jpeg", ".webp"}
    if not filename or ext not in valid_exts:
        raise HTTPException(
            status_code=400,
            detail=f"Invalid file format '{ext}'. Accepted formats: GeoTIFF (.tif, .tiff), NumPy (.npz), and Images (.png, .jpg, .jpeg, .webp)."
        )

    try:
        save_path = UPLOADS_DIR / filename
        with open(save_path, "wb") as f:
            shutil.copyfileobj(file.file, f)

        if save_path.stat().st_size == 0:
            save_path.unlink(missing_ok=True)
            raise HTTPException(
                status_code=400,
                detail="Uploaded file is empty (0 bytes). Please upload a valid image or GeoTIFF."
            )

        result = await run_in_threadpool(run_gpu_inference, save_path)
        return {"status": "success", "data": result}
    except HTTPException:
        raise
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=str(e))


# ============================================================================
# 3. DOWNLOAD ENDPOINTS (GeoTIFF & NPZ)
# ============================================================================
@app.get("/download_geotiff", tags=["Export"])
@app.get("/api/download_geotiff", tags=["Export"])
def download_geotiff(token: str):
    """
    Downloads the super-resolved 2.5 m imagery as an analysis-ready 4-band GeoTIFF
    with EPSG CRS projection and affine transform matrices.
    """
    try:
        out_tif = UPLOADS_DIR / f"GaiaScale_Enhanced_2.5m_{token}.tif"
        exported_path = inference_engine.export_cached_geotiff(token, out_tif)
        return FileResponse(
            exported_path,
            media_type="image/tiff",
            filename=exported_path.name
        )
    except KeyError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/download_npz", tags=["Export"])
@app.get("/api/download_npz", tags=["Export"])
def download_npz(token: str):
    """
    Downloads the super-resolved 2.5 m data as a compressed NumPy tensor (.npz)
    containing high-res and low-res multispectral reflectance channels.
    """
    try:
        out_npz = UPLOADS_DIR / f"GaiaScale_Enhanced_2.5m_{token}.npz"
        exported_path = inference_engine.export_cached_npz(token, out_npz)
        return FileResponse(
            exported_path,
            media_type="application/octet-stream",
            filename=exported_path.name
        )
    except KeyError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


# ============================================================================
# 4. MAINTENANCE ENDPOINTS (CLEANUP)
# ============================================================================
@app.post("/cleanup", tags=["Maintenance"])
@app.post("/api/cleanup", tags=["Maintenance"])
def manual_cleanup(min_age_seconds: int = 0):
    """
    Manually triggers cleanup of temporary uploads and cached files.
    Files modified within min_age_seconds are kept (default 0 deletes all un-protected files).
    """
    return cleanup_uploads_now(min_age_seconds=min_age_seconds)


def main():
    parser = argparse.ArgumentParser(description="GaiaScale Sovereign Super-Resolution Platform")
    parser.add_argument("--host", default="127.0.0.1", help="Host address (default: 127.0.0.1)")
    parser.add_argument("--port", type=int, default=7860, help="Port (default: 7860)")
    args = parser.parse_args()

    print("=" * 76)
    print("  [GAIASCALE] MULTISPECTRAL SATELLITE SUPER-RESOLUTION PLATFORM")
    print(f"  Device: {DEVICE} | Host: {args.host}:{args.port}")
    print("  Endpoints: /health, /upload, /download_geotiff")
    print("=" * 76)

    uvicorn.run("backend.main:app", host=args.host, port=args.port, reload=False)


if __name__ == "__main__":
    main()