""" 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)