Spaces:
Running
Running
# The Complete and Final app.py with both a UI and an API | |
from fastapi import FastAPI | |
from fastapi.responses import JSONResponse | |
from pydantic import BaseModel | |
import gradio as gr | |
import tensorflow as tf | |
from huggingface_hub import hf_hub_download | |
import numpy as np | |
from PIL import Image | |
import os | |
import base64 | |
import io | |
# --- 1. Load the Model --- | |
model = None | |
try: | |
model_path = hf_hub_download( | |
repo_id="skibi11/leukolook-eye-detector", | |
filename="MobileNetV1_best.keras" | |
) | |
model = tf.keras.models.load_model(model_path) | |
print("--- MODEL LOADED SUCCESSFULLY! ---") | |
except Exception as e: | |
print(f"--- ERROR LOADING MODEL: {e} ---") | |
model = None | |
# --- 2. Core Prediction Logic --- | |
def preprocess_image(img_pil): | |
img = img_pil.resize((224, 224)) | |
img_array = np.array(img) | |
if img_array.ndim == 2: img_array = np.stack((img_array,)*3, axis=-1) | |
if img_array.shape[-1] == 4: img_array = img_array[..., :3] | |
img_array = img_array / 255.0 | |
img_array = np.expand_dims(img_array, axis=0) | |
return img_array | |
def run_prediction(pil_image): | |
if model is None: | |
return {"error": "Model is not loaded on the server."} | |
processed_image = preprocess_image(pil_image) | |
prediction = model.predict(processed_image) | |
labels = [f"Class_{i}" for i in range(prediction.shape[1])] | |
confidences = {label: float(score) for label, score in zip(labels, prediction[0])} | |
return confidences | |
# --- 3. Create the FastAPI app --- | |
app = FastAPI() | |
# --- 4. Define the input data structure for our API endpoint --- | |
class PredictionRequest(BaseModel): | |
data: list[str] | |
# --- 5. Create our reliable API endpoint for the Render backend --- | |
async def handle_api_prediction(request: PredictionRequest): | |
try: | |
base64_string = request.data[0].split(',', 1)[1] | |
image_bytes = base64.b64decode(base64_string) | |
pil_image = Image.open(io.BytesIO(image_bytes)) | |
result_dict = run_prediction(pil_image) | |
return JSONResponse(content={"data": [result_dict]}) | |
except Exception as e: | |
return JSONResponse(status_code=500, content={"error": str(e)}) | |
# --- 6. Create the Gradio UI for the homepage --- | |
gradio_ui = gr.Interface( | |
fn=run_prediction, | |
inputs=gr.Image(type="pil", label="Upload an eye image to test"), | |
outputs=gr.JSON(label="Prediction Results"), | |
title="LeukoLook Eye Detector", | |
description="A demonstration of the LeukoLook detection model. This UI can be used for direct testing." | |
) | |
# --- 7. Mount the Gradio UI onto the FastAPI app's root --- | |
app = gr.mount_gradio_app(app, gradio_ui, path="/") | |
# --- 8. To run the server --- | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=7860) |