File size: 7,053 Bytes
7529108
 
 
 
 
 
 
 
 
478ede0
 
 
059bf81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac6b2e
7529108
 
 
 
8ac6b2e
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56da09b
 
8ac6b2e
 
 
 
56da09b
7529108
 
fd73401
7529108
 
8ac6b2e
7529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a385053
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7529108
 
478ede0
 
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
"""
GaiaScale Gradio Space Application Server
Serves both the REST API for the Static Frontend and an interactive Gradio diagnostic interface.
"""

from __future__ import annotations

import os

# Disable Gradio 5 SSR (Server-Side Rendering) mode to prevent it from spawning an internal Node.js server on port 7861
os.environ["GRADIO_SSR_MODE"] = "false"

# IMPORTANT FOR HUGGING FACE ZEROGPU:
# `spaces` must be imported before any CUDA-related package (e.g. torch, torchvision, backend modules)
try:
    import spaces
except ImportError:
    class _MockSpaces:
        @staticmethod
        def GPU(func=None, **kwargs):
            if func is not None:
                return func
            def decorator(f):
                return f
            return decorator
    spaces = _MockSpaces()

import base64
from io import BytesIO
from pathlib import Path
import sys

# Ensure backend root and project root are on sys.path
CURRENT_DIR = Path(__file__).resolve().parent
if str(CURRENT_DIR) not in sys.path:
    sys.path.insert(0, str(CURRENT_DIR))
if str(CURRENT_DIR.parent) not in sys.path:
    sys.path.insert(0, str(CURRENT_DIR.parent))

from PIL import Image
import gradio as gr
import uvicorn
from fastapi.middleware.cors import CORSMiddleware

try:
    from backend.main import app as fastapi_app
    from backend.services.inference import inference_engine, run_gpu_inference
    from backend.services.cleanup import cleanup_uploads_now, cleanup_worker
    from backend.config import DEVICE
except ImportError:
    from main import app as fastapi_app
    from services.inference import inference_engine, run_gpu_inference
    from services.cleanup import cleanup_uploads_now, cleanup_worker
    from config import DEVICE


def b64_to_pil(b64_str: str) -> Image.Image:
    """Decode a data URI base64 string to a PIL Image."""
    if "," in b64_str:
        _, encoded = b64_str.split(",", 1)
    else:
        encoded = b64_str
    data = base64.b64decode(encoded)
    return Image.open(BytesIO(data))


def run_gradio_inference(image_file):
    """Gradio handler for interactive testing.

    Calls the shared run_gpu_inference() entrypoint (not inference_engine
    directly) so the ZeroGPU schedule/allocation is only ever done once,
    in one place, from a plain picklable-args function. See
    services/inference.py for why this can't be a bound method.
    """
    if image_file is None:
        return None, None, "Please provide an image or GeoTIFF file."

    file_path = Path(image_file)
    try:
        result = run_gpu_inference(file_path)
        lr_img = b64_to_pil(result["images"]["lr_rgb"])
        sr_img = b64_to_pil(result["images"]["sr_rgb"])
        
        metrics = result.get("metrics", {})
        info = (
            f"✅ Inference Complete\n"
            f"• Model: {result.get('model_name', 'HAT')}\n"
            f"• Latency: {result.get('latency_ms', 0):.1f} ms\n"
            f"• PSNR: {metrics.get('psnr', 0.0):.2f} dB | SSIM: {metrics.get('ssim', 0.0):.4f}\n"
            f"• Input Shape: {result.get('input_shape')}\n"
            f"• Output Shape: {result.get('output_shape')}"
        )
        return lr_img, sr_img, info
    except Exception as e:
        return None, None, f"❌ Error during inference: {str(e)}"


def gradio_trigger_cleanup():
    res = cleanup_uploads_now(min_age_seconds=0)
    return f"🧹 Cleanup complete: {res['files_deleted']} files deleted ({res['mb_freed']} MB freed) at {res['timestamp']}."


# Define Gradio diagnostic and documentation dashboard
with gr.Blocks(title="GaiaScale Super-Resolution API") as demo:
    gr.Markdown("# 🛰️ GaiaScale Satellite Super-Resolution Engine")
    gr.Markdown(
        "**Multi-band 4x spatial super-resolution (Sentinel-2 10 m → 2.5 m).**\n\n"
        "⚡ **API Status**: Active & Listening\n"
        f"• **Hardware Device**: `{DEVICE}`\n"
        f"• **Available Models**: `{', '.join(inference_engine.available_models)}`\n"
        "• **Daily Maintenance**: Background worker active (purges `uploads/` daily at 02:00 AM)\n\n"
        "This Hugging Face Space hosts the REST API endpoints (`/api/health`, `/api/upload`, `/api/download_geotiff`, `/api/download_npz`, `/api/cleanup`) "
        "consumed by the GaiaScale Static Web Frontend."
    )
    
    with gr.Accordion("🔍 Interactive Diagnostic & Test Runner", open=False):
        gr.Markdown("Upload a satellite scene, GeoTIFF, or sample image to test model inference directly:")
        with gr.Row():
            file_input = gr.File(label="Upload Satellite Image / GeoTIFF (.tif, .png, .npz)", type="filepath")
        run_btn = gr.Button("Run Super-Resolution", variant="primary")
        with gr.Row():
            lr_output = gr.Image(label="Input (10 m Bicubic)", type="pil")
            sr_output = gr.Image(label="Output (2.5 m GaiaScale-HAT)", type="pil")
        metrics_output = gr.Textbox(label="Telemetry & Metrics", lines=4)
        
        run_btn.click(
            fn=run_gradio_inference,
            inputs=[file_input],
            outputs=[lr_output, sr_output, metrics_output]
        )

    with gr.Accordion("🛠️ Storage Maintenance (Daily 02:00 AM Worker)", open=False):
        gr.Markdown(
            "An automated daemon worker runs every day at **02:00 AM** local time to purge temporary "
            "uploaded files and generated GeoTIFF/NPZ cache products to conserve storage on Hugging Face free tier."
        )
        cleanup_btn = gr.Button("🧹 Trigger Clean Uploads Now (Test/Admin)", variant="secondary")
        cleanup_output = gr.Textbox(label="Worker Output", lines=1)
        cleanup_btn.click(fn=gradio_trigger_cleanup, inputs=[], outputs=[cleanup_output])

# Mount Gradio into the FastAPI application at root
# All FastAPI routes (/api/health, /api/upload, etc.) take priority!
app = gr.mount_gradio_app(fastapi_app, demo, path="/")


def _report_zerogpu_startup():
    """Manually fire the ZeroGPU registration handshake.

    The `spaces` SDK normally reports @spaces.GPU functions to the ZeroGPU
    scheduler from inside gr.Blocks.launch() (it monkey-patches launch()).
    Since this app mounts Gradio into FastAPI and serves it via a bare
    uvicorn.run() instead of calling demo.launch(), that hook never fires
    and HF reports "No @spaces.GPU function detected". Trigger it here
    instead, once the @spaces.GPU-decorated function above is registered.
    """
    try:
        from spaces.config import Config as _SpacesConfig
        if _SpacesConfig.zero_gpu:
            import spaces.zero as _spaces_zero
            _spaces_zero.startup()
            print("[GaiaScale Server] ZeroGPU startup report sent.")
    except Exception as e:
        print(f"[GaiaScale Server] ZeroGPU startup report skipped: {e}")


_report_zerogpu_startup()


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    print(f"[GaiaScale Server] Starting server on 0.0.0.0:{port} (PORT env={os.environ.get('PORT')})")
    uvicorn.run(app, host="0.0.0.0", port=port, reload=False)