""" Snow Detection CNN Inference API Hugging Face Space for running snow detection inference """ import gradio as gr import tensorflow as tf import numpy as np from PIL import Image import io import requests import os import base64 from pathlib import Path from fastapi import Request from fastapi.responses import JSONResponse # Global model variable model = None def load_model(): """Load the TensorFlow SavedModel""" global model if model is None: print("Loading SavedModel...") # Try to load from the space's files # The SavedModel should be uploaded to this space savedmodel_path = Path("savedmodel") if savedmodel_path.exists() and (savedmodel_path / "saved_model.pb").exists(): print(f"Loading model from {savedmodel_path}") model = tf.saved_model.load(str(savedmodel_path)) else: # Try loading from models directory (if uploaded separately) models_path = Path("models/snow-detection-cnn") if models_path.exists(): print(f"Loading model from {models_path}") model = tf.saved_model.load(str(models_path)) else: raise FileNotFoundError( "SavedModel not found. Please upload your SavedModel files to this Space. " "The directory should contain saved_model.pb and variables/" ) print("✅ Model loaded successfully!") return model def predict(image_input): """ Run inference on an image Args: image_input: Can be: - PIL Image - numpy array - file path (str) - URL (str) Returns: dict with hasSnow, confidence, and raw_score """ try: # Load model if needed model = load_model() # Handle different input types if isinstance(image_input, str): # Check for base64 data URL first if image_input.startswith('data:image'): # Extract base64 data from data URL # Format: data:image/jpeg;base64,/9j/4AAQSkZJRg... header, encoded = image_input.split(',', 1) image_data = base64.b64decode(encoded) image = Image.open(io.BytesIO(image_data)).convert('RGB') elif image_input.startswith('http://') or image_input.startswith('https://'): # Download from URL response = requests.get(image_input, timeout=10) image = Image.open(io.BytesIO(response.content)).convert('RGB') else: # File path image = Image.open(image_input).convert('RGB') elif isinstance(image_input, np.ndarray): # Numpy array image = Image.fromarray(image_input).convert('RGB') else: # Assume PIL Image image = image_input.convert('RGB') # Preprocess image (same as training) image = image.resize((224, 224)) image_array = np.array(image, dtype=np.float32) / 255.0 # Normalize to [0, 1] image_array = np.expand_dims(image_array, axis=0) # Add batch dimension # Run inference # Get the serving signature infer = model.signatures["serving_default"] # Convert to TensorFlow tensor input_tensor = tf.constant(image_array) # Run inference output = infer(input_tensor) # Extract prediction # The output key might vary - try common ones if 'output_0' in output: prediction = float(output['output_0'][0][0]) elif 'dense_1' in output: prediction = float(output['dense_1'][0][0]) elif len(output) == 1: # Single output, get first value prediction = float(list(output.values())[0][0][0]) else: raise ValueError(f"Unexpected output format: {output.keys()}") # Interpret result (binary classification: >0.5 = snow) has_snow = prediction > 0.5 confidence = prediction if has_snow else (1 - prediction) return { "hasSnow": bool(has_snow), "confidence": float(confidence), "raw_score": float(prediction) } except Exception as e: import traceback error_msg = str(e) traceback.print_exc() return { "error": error_msg, "hasSnow": False, "confidence": 0.0 } # Create Gradio interface using Blocks so we can add custom routes with gr.Blocks(title="❄️ Snow Detection CNN") as demo: gr.Markdown("# ❄️ Snow Detection CNN") gr.Markdown("Detect snow in webcam images using a custom CNN model.") with gr.Row(): image_input = gr.Image(type="pil", label="Upload or paste image URL") output = gr.JSON(label="Prediction Result") submit_btn = gr.Button("Predict") submit_btn.click(fn=predict, inputs=image_input, outputs=output) # Expose as API demo.api_name = "predict" # Add FastAPI route using load event (must be inside Blocks context) from fastapi import Request from fastapi.responses import JSONResponse @demo.load() def setup_api_routes(): """Add custom API routes when Gradio app loads""" if hasattr(demo, 'app') and demo.app: @demo.app.post("/api/predict") async def api_predict(request: Request): """Custom API endpoint that matches our Node.js app's expectations""" try: body = await request.json() # Extract image URL from request image_url = None if isinstance(body, dict): if 'data' in body and isinstance(body['data'], list) and len(body['data']) > 0: image_input = body['data'][0] if isinstance(image_input, dict) and 'url' in image_input: image_url = image_input['url'] elif isinstance(image_input, str): image_url = image_input elif 'imageUrl' in body: image_url = body['imageUrl'] elif 'url' in body: image_url = body['url'] if not image_url: response = JSONResponse( status_code=400, content={"error": "No image URL provided", "hasSnow": False, "confidence": 0.0} ) # Add CORS headers manually response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Methods"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" return response # Call predict function result = predict(image_url) response = JSONResponse(content=result) # Add CORS headers manually response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Methods"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" return response except Exception as e: import traceback traceback.print_exc() response = JSONResponse( status_code=500, content={"error": str(e), "hasSnow": False, "confidence": 0.0} ) # Add CORS headers manually response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-Methods"] = "*" response.headers["Access-Control-Allow-Headers"] = "*" return response print("[App] FastAPI /api/predict route added") if __name__ == "__main__": # Launch Gradio app # Disable SSR to enable API endpoints demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)