Upload app.py with huggingface_hub
Browse files8 unmodified lines9101112131415163 unmodified lines2021222324252627282930313233342 unmodified lines373839404142434 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949513 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921938 unmodified linesfrom PIL import Imageimport ioimport requestsimport base64from pathlib import Path# Global model variablemodel = None3 unmodified linesglobal modelif model is None:print("Loading SavedModel...")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:raise FileNotFoundError("SavedModel not found. Please upload your SavedModel files to this Space.")print("✅ Model loaded successfully!")return model2 unmodified linesRun inference on an imageArgs:image_input: Can be PIL Image, numpy array, file path (str), or URL (str)Returns:dict with hasSnow, confidence, and raw_score4 unmodified lines# Handle different input typesif isinstance(image_input, str):# Base64 data URLif image_input.startswith('data:image'):if ',' in image_input:header, encoded = image_input.split(',', 1)image_data = base64.b64decode(encoded)image = Image.open(io.BytesIO(image_data)).convert('RGB')else:raise ValueError("Invalid data URL format")# HTTP/HTTPS URLelif image_input.startswith('http://') or image_input.startswith('https://'):response = requests.get(image_input, timeout=10)image = Image.open(io.BytesIO(response.content)).convert('RGB')else:# File pathimage = Image.open(image_input).convert('RGB')elif isinstance(image_input, np.ndarray):image = Image.fromarray(image_input).convert('RGB')else:# Assume PIL Imageimage = image_input.convert('RGB')# Preprocess imageimage = image.resize((224, 224))image_array = np.array(image, dtype=np.float32) / 255.0image_array = np.expand_dims(image_array, axis=0)# Run inferenceinfer = model.signatures["serving_default"]input_tensor = tf.constant(image_array)output = infer(input_tensor)# Extract predictionif '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:prediction = float(list(output.values())[0][0][0])else:raise ValueError(f"Unexpected output format: {output.keys()}")# Interpret resulthas_snow = prediction > 0.5confidence = prediction if has_snow else (1 - prediction)13 unmodified lines"confidence": 0.0}# Create Gradio interface using Blocks so we can add custom routeswith 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 APIdemo.api_name = "predict"# Add FastAPI route using load event (must be inside Blocks context)from fastapi import Requestfrom 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 requestimage_url = Noneif 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_inputelif '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 manuallyresponse.headers["Access-Control-Allow-Origin"] = "*"response.headers["Access-Control-Allow-Methods"] = "*"response.headers["Access-Control-Allow-Headers"] = "*"return response# Call predict functionresult = predict(image_url)response = JSONResponse(content=result)# Add CORS headers manuallyresponse.headers["Access-Control-Allow-Origin"] = "*"response.headers["Access-Control-Allow-Methods"] = "*"response.headers["Access-Control-Allow-Headers"] = "*"return responseexcept Exception as e:import tracebacktraceback.print_exc()response = JSONResponse(status_code=500,content={"error": str(e), "hasSnow": False, "confidence": 0.0})# Add CORS headers manuallyresponse.headers["Access-Control-Allow-Origin"] = "*"response.headers["Access-Control-Allow-Methods"] = "*"response.headers["Access-Control-Allow-Headers"] = "*"return responseprint("[App] FastAPI /api/predict route added")if __name__ == "__main__":# Launch Gradio app# Disable SSR to enable API endpointsdemo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)8 unmodified lines9101112131415161718193 unmodified lines2324252627282930313233343536373839404142434445462 unmodified lines49505152535455565758594 unmodified lines64656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111213 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112128 unmodified linesfrom PIL import Imageimport ioimport requestsimport osfrom pathlib import Pathfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import JSONResponsefrom fastapi.middleware.cors import CORSMiddleware# Global model variablemodel = None3 unmodified linesglobal modelif model is None:print("Loading SavedModel...")# Try to load from the space's files# The SavedModel should be uploaded to this spacesavedmodel_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 model2 unmodified linesRun inference on an imageArgs:image_input: Can be:- PIL Image- numpy array- file path (str)- URL (str)Returns:dict with hasSnow, confidence, and raw_score4 unmodified lines# Handle different input typesif isinstance(image_input, str):# URL or file pathif image_input.startswith('http://') or image_input.startswith('https://'):# Download from URLresponse = requests.get(image_input, timeout=10)image = Image.open(io.BytesIO(response.content)).convert('RGB')else:# File pathimage = Image.open(image_input).convert('RGB')elif isinstance(image_input, np.ndarray):# Numpy arrayimage = Image.fromarray(image_input).convert('RGB')else:# Assume PIL Imageimage = 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 signatureinfer = model.signatures["serving_default"]# Convert to TensorFlow tensorinput_tensor = tf.constant(image_array)# Run inferenceoutput = infer(input_tensor)# Extract prediction# The output key might vary - try common onesif '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 valueprediction = 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.5confidence = prediction if has_snow else (1 - prediction)13 unmodified lines"confidence": 0.0}# Create Gradio interface# This provides both a UI and an API endpointdemo = gr.Interface(fn=predict,inputs=gr.Image(type="pil", label="Upload or paste image URL"),outputs=gr.JSON(label="Prediction Result"),api_name="predict", # Explicitly name the API endpointtitle="❄️ Snow Detection CNN",description="""Detect snow in webcam images using a custom CNN model.**How to use:**1. Upload an image or paste an image URL2. Get prediction with confidence score**API Usage:**This Space provides a REST API endpoint. Use it in your app with:```POST https://lutztalk-development-isitsnowingthere-com.hf.space/api/predict```""",# Removed examples - they were causing 404 errors# examples=[# "https://images.unsplash.com/photo-1511884642898-4c92249e20b1", # Snow example# "https://images.unsplash.com/photo-1506905925346-21bda4d32df4", # No snow example# ])# Create FastAPI app for direct HTTP API accessapi_app = FastAPI()# Add CORS middlewareapi_app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)@api_app.post("/api/predict")async def api_predict_endpoint(data: dict):"""Direct HTTP API endpoint for predictions"""try:# Extract image URL or data from requestimage_input = Noneif isinstance(data, dict):if 'data' in data and isinstance(data['data'], list) and len(data['data']) > 0:image_input = data['data'][0]elif 'imageUrl' in data:image_input = data['imageUrl']elif 'url' in data:image_input = data['url']if not image_input:raise HTTPException(status_code=400, detail="No image provided")# Handle ImageData object or direct URLif isinstance(image_input, dict) and 'url' in image_input:image_url = image_input['url']elif isinstance(image_input, str):image_url = image_inputelse:raise HTTPException(status_code=400, detail="Invalid image format")# Run predictionresult = predict(image_url)return JSONResponse(content=result)except Exception as e:return JSONResponse(status_code=500,content={"error": str(e), "hasSnow": False, "confidence": 0.0})if __name__ == "__main__":# Mount Gradio app into FastAPI so both UI and API work# This makes FastAPI the main app with Gradio UI mounted at rootgr.mount_gradio_app(api_app, demo, path="/")# Run FastAPI app (which now includes Gradio UI)import uvicornuvicorn.run(api_app, host="0.0.0.0", port=7860)
app.py+116-97