File size: 10,947 Bytes
c82cafe
6a49d1a
c82cafe
4855bb3
c82cafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4855bb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c82cafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a49d1a
 
 
 
 
 
 
 
c82cafe
c9690f3
c82cafe
 
 
c9690f3
6a49d1a
c82cafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# main.py
from huggingface_hub import hf_hub_download
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, HTMLResponse
import tensorflow as tf
import numpy as np
import base64
import logging
import os
import sys
import time
from datetime import datetime
from logging.handlers import RotatingFileHandler

from inference.forest import predict_forest, build_input_tensor
from schemas import PredictRequest, PredictResponse

# =============================================================================
# LOGGING CONFIGURATION
# =============================================================================

os.makedirs("logs", exist_ok=True)

logger = logging.getLogger("forest_segmentation")
logger.setLevel(logging.DEBUG)

console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(
    logging.Formatter(
        "%(asctime)s | %(levelname)-8s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
)

file_handler = RotatingFileHandler(
    "logs/server.log", maxBytes=10_000_000, backupCount=5, encoding="utf-8"
)
file_handler.setFormatter(console_handler.formatter)

logger.addHandler(console_handler)
logger.addHandler(file_handler)

logger.info("=" * 80)
logger.info("FOREST SEGMENTATION SERVER STARTING")
logger.info("=" * 80)

# =============================================================================
# INVERSION DETECTION
# =============================================================================

def detect_inversion(image_stack, confidence_map, ndvi_threshold=0.3):
    """
    Detect if model output is inverted using NDVI correlation.
    image_stack: (H, W, 9)
    confidence_map: (H, W)
    """
    ndvi = image_stack[:, :, 6]  # NDVI channel

    vegetation_mask = ndvi > ndvi_threshold

    veg_conf = (
        confidence_map[vegetation_mask].mean()
        if vegetation_mask.any() else 0.5
    )

    non_veg_conf = (
        confidence_map[~vegetation_mask].mean()
        if (~vegetation_mask).any() else 0.5
    )

    is_inverted = non_veg_conf > veg_conf
    correlation = veg_conf - non_veg_conf

    return bool(is_inverted), float(correlation)

# =============================================================================
# FASTAPI APP
# =============================================================================

app = FastAPI(
    title="Forest Segmentation API",
    description="Landsat 8 Forest Segmentation",
    version="1.0.0"
)

IMG_SIZE = 256
LANDSAT_BANDS = [
    "Blue", "Green", "Red",
    "NIR", "SWIR1", "SWIR2",
    "NDVI", "NDWI", "NBR"
]

# =============================================================================
# MIDDLEWARE
# =============================================================================

@app.middleware("http")
async def log_requests(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start
    logger.info(
        f"{request.method} {request.url.path} | "
        f"{response.status_code} | {duration:.3f}s"
    )
    return response

# =============================================================================
# ROOT ENDPOINT
# =============================================================================

@app.get("/", response_class=HTMLResponse)
def root():
    """Serve a simple HTML page with API info."""
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Forest Segmentation API</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 40px; background-color: #f5f5f5; }
            .container { background-color: white; padding: 20px; border-radius: 8px; max-width: 800px; }
            h1 { color: #333; }
            .endpoint { background-color: #f0f0f0; padding: 10px; margin: 10px 0; border-left: 4px solid #4CAF50; }
            code { background-color: #f9f9f9; padding: 2px 6px; border-radius: 3px; }
            .status { color: #4CAF50; font-weight: bold; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>🌲 Forest Segmentation API</h1>
            <p>Landsat 8 Forest Segmentation Model</p>
            
            <h2>API Endpoints</h2>
            <div class="endpoint">
                <strong>Health Check</strong><br>
                <code>GET /health</code><br>
                Returns API status
            </div>
            
            <div class="endpoint">
                <strong>Predict</strong><br>
                <code>POST /predict</code><br>
                Send Landsat bands for forest segmentation
            </div>
            
            <div class="endpoint">
                <strong>API Docs</strong><br>
                <code>GET /docs</code><br>
                Interactive Swagger UI
            </div>
            
            <h2>Status</h2>
            <p><span class="status">✓ API is running</span></p>
        </div>
    </body>
    </html>
    """

# =============================================================================
# HEALTH
# =============================================================================

@app.get("/health")
def health():
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat()
    }

# =============================================================================
# PREDICT ENDPOINT (FIXED - CONTINUOUS VALUES)
# =============================================================================

@app.post("/predict", response_model=PredictResponse)
def predict(payload: PredictRequest):

    try:
        logger.info("[PREDICT] Request received")

        if not payload.bands:
            raise ValueError("No bands provided")

        # ---------------------------------------------------------------------
        # Decode bands
        # ---------------------------------------------------------------------
        decoded_bands = {}

        for band, data in payload.bands.items():
            if isinstance(data, str):
                raw = base64.b64decode(data)
                arr = np.frombuffer(raw, dtype=np.float32)
                side = int(np.sqrt(arr.size))
                decoded_bands[band] = arr.reshape((side, side))
            else:
                decoded_bands[band] = np.array(data, dtype=np.float32)

        logger.info(f"[PREDICT] Decoded {len(decoded_bands)} bands")

        # ---------------------------------------------------------------------
        # Build input tensor
        # ---------------------------------------------------------------------
        input_tensor = build_input_tensor(decoded_bands)  # (1, H, W, 9)
        input_stack = input_tensor[0]                     # (H, W, 9)

        # ---------------------------------------------------------------------
        # Run model (raw confidence)
        # ---------------------------------------------------------------------
        MODEL_REPO = "prshntdxt/Forest_Segmentation_Best"
        MODEL_FILE = "Forest_Segmentation_Best.keras"
        
        MODEL_PATH = hf_hub_download(
            repo_id=MODEL_REPO,
            filename=MODEL_FILE,
        )
        
        model = tf.keras.models.load_model(
            MODEL_PATH,
            compile=False
        )



        confidence_map = model.predict(
            input_tensor, verbose=0
        )[0, :, :, 0]

        # Log raw model output stats
        logger.info(
            f"[MODEL OUTPUT] Raw confidence: min={confidence_map.min():.4f}, "
            f"max={confidence_map.max():.4f}, mean={confidence_map.mean():.4f}"
        )

        # ---------------------------------------------------------------------
        # Inversion detection & correction
        # ---------------------------------------------------------------------
        is_inverted, corr = detect_inversion(
            input_stack, confidence_map
        )

        if is_inverted:
            logger.warning(
                f"[INVERSION] Detected | NDVI correlation={corr:.4f} | FIX APPLIED"
            )
            corrected_conf = 1.0 - confidence_map
        else:
            logger.info(
                f"[INVERSION] Not detected | NDVI correlation={corr:.4f}"
            )
            corrected_conf = confidence_map

        # ---------------------------------------------------------------------
        # Create masks (CONTINUOUS values for density visualization)
        # ---------------------------------------------------------------------
        # Use continuous confidence scaled to 0-255 (NOT binary!)
        mask_255 = (corrected_conf * 255).astype(np.uint8)
        inverted_mask_255 = (255 - mask_255).astype(np.uint8)

        # Calculate stats using threshold for percentage
        forest_percentage = float((corrected_conf > 0.5).sum() / corrected_conf.size * 100)
        forest_confidence = float(corrected_conf.mean())

        # Log mask stats to verify continuous values
        logger.info(
            f"[MASK] Range: [{mask_255.min()}, {mask_255.max()}] | "
            f"Unique values: {len(np.unique(mask_255))}"
        )

        logger.info(
            f"[PREDICT] Forest={forest_percentage:.2f}% | "
            f"Confidence={forest_confidence:.4f}"
        )

        # ---------------------------------------------------------------------
        # Response
        # ---------------------------------------------------------------------
        return {
            "mask": mask_255.flatten().tolist(),
            "inverted_mask": inverted_mask_255.flatten().tolist(),
            "forest_percentage": forest_percentage,
            "forest_confidence": forest_confidence,
            "mean_prediction": forest_confidence,
            "classes": {"forest": 1, "non_forest": 0},
            "model_info": {
                "name": "Forest_Segmentation_Best",
                "bands": LANDSAT_BANDS
            },
            "debug": {
                "was_inverted": is_inverted,
                "inversion_correlation": corr,
                "mask_min": int(mask_255.min()),
                "mask_max": int(mask_255.max()),
                "unique_values": int(len(np.unique(mask_255)))
            }
        }

    except ValueError as e:
        logger.error(f"[PREDICT] Validation error: {e}")
        raise HTTPException(status_code=400, detail=str(e))

    except Exception as e:
        logger.exception("[PREDICT] Inference failed")
        raise HTTPException(status_code=500, detail=str(e))

# =============================================================================
# STARTUP / SHUTDOWN
# =============================================================================

@app.on_event("startup")
async def startup():
    logger.info("=" * 80)
    logger.info("SERVER READY")
    logger.info("=" * 80)

@app.on_event("shutdown")
async def shutdown():
    logger.info("=" * 80)
    logger.info("SERVER SHUTDOWN")
    logger.info("=" * 80)