Spaces:
Running
Running
included the Roboflow calls and image manipulation logic
Browse files
app.py
CHANGED
@@ -1,82 +1,147 @@
|
|
1 |
-
# The Complete and Final app.py
|
2 |
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
from fastapi.responses import JSONResponse
|
5 |
-
from pydantic import BaseModel
|
6 |
import gradio as gr
|
7 |
import tensorflow as tf
|
8 |
from huggingface_hub import hf_hub_download
|
9 |
-
import numpy as np
|
10 |
-
from PIL import Image
|
11 |
-
import os
|
12 |
-
import base64
|
13 |
-
import io
|
14 |
|
15 |
-
# --- 1.
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
model = None
|
17 |
try:
|
18 |
-
model_path = hf_hub_download(
|
19 |
-
repo_id="skibi11/leukolook-eye-detector",
|
20 |
-
filename="MobileNetV1_best.keras"
|
21 |
-
)
|
22 |
model = tf.keras.models.load_model(model_path)
|
23 |
print("--- MODEL LOADED SUCCESSFULLY! ---")
|
24 |
except Exception as e:
|
25 |
-
print(f"--- ERROR LOADING MODEL: {e} ---")
|
26 |
-
model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
img = img_pil.resize((224, 224))
|
31 |
-
img_array = np.array(img)
|
32 |
-
if img_array.ndim == 2: img_array = np.stack((img_array,)*3, axis=-1)
|
33 |
-
if img_array.shape[-1] == 4: img_array = img_array[..., :3]
|
34 |
-
img_array = img_array / 255.0
|
35 |
img_array = np.expand_dims(img_array, axis=0)
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
return {"error": "Model is not loaded on the server."}
|
41 |
-
|
42 |
-
processed_image = preprocess_image(pil_image)
|
43 |
-
prediction = model.predict(processed_image)
|
44 |
-
labels = [f"Class_{i}" for i in range(prediction.shape[1])]
|
45 |
-
confidences = {label: float(score) for label, score in zip(labels, prediction[0])}
|
46 |
-
return confidences
|
47 |
-
|
48 |
-
# --- 3. Create the FastAPI app ---
|
49 |
app = FastAPI()
|
50 |
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
-
# ---
|
56 |
-
|
57 |
-
|
|
|
58 |
try:
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
except Exception as e:
|
65 |
-
return
|
66 |
|
67 |
-
# --- 6. Create the Gradio UI for the homepage ---
|
68 |
gradio_ui = gr.Interface(
|
69 |
-
fn=
|
70 |
-
inputs=gr.Image(type="
|
71 |
outputs=gr.JSON(label="Prediction Results"),
|
72 |
title="LeukoLook Eye Detector",
|
73 |
-
description="A demonstration of the LeukoLook detection model. This UI
|
74 |
)
|
75 |
|
76 |
-
# ---
|
77 |
app = gr.mount_gradio_app(app, gradio_ui, path="/")
|
78 |
|
79 |
-
# ---
|
80 |
if __name__ == "__main__":
|
81 |
-
import uvicorn
|
82 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
1 |
+
# The Complete and Final app.py for Hugging Face Space
|
2 |
|
3 |
+
import os
|
4 |
+
import cv2
|
5 |
+
import tempfile
|
6 |
+
import numpy as np
|
7 |
+
import uvicorn
|
8 |
+
from PIL import Image
|
9 |
+
from inference_sdk import InferenceHTTPClient
|
10 |
+
from fastapi import FastAPI, File, UploadFile
|
11 |
from fastapi.responses import JSONResponse
|
|
|
12 |
import gradio as gr
|
13 |
import tensorflow as tf
|
14 |
from huggingface_hub import hf_hub_download
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
# --- 1. Configuration and Model Loading ---
|
17 |
+
# Note: Ensure ROBOFLOW_API_KEY is set as a secret in your Space settings
|
18 |
+
ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY")
|
19 |
+
CLIENT_FACE = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
20 |
+
CLIENT_EYES = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
21 |
+
CLIENT_IRIS = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
22 |
+
|
23 |
model = None
|
24 |
try:
|
25 |
+
model_path = hf_hub_download("skibi11/leukolook-eye-detector", "MobileNetV1_best.keras")
|
|
|
|
|
|
|
26 |
model = tf.keras.models.load_model(model_path)
|
27 |
print("--- MODEL LOADED SUCCESSFULLY! ---")
|
28 |
except Exception as e:
|
29 |
+
print(f"--- ERROR LOADING LEUKOCORIA MODEL: {e} ---")
|
30 |
+
raise RuntimeError(f"Could not load leukocoria model: {e}")
|
31 |
+
|
32 |
+
# --- 2. All Helper Functions ---
|
33 |
+
def detect_faces_roboflow(image_path):
|
34 |
+
"""Calls Roboflow to find faces in the image."""
|
35 |
+
resp = CLIENT_FACE.infer(image_path, model_id="face-detector-v4liw/2")
|
36 |
+
return resp.get("predictions", [])
|
37 |
+
|
38 |
+
def detect_eyes_roboflow(image_path):
|
39 |
+
"""Calls Roboflow to find eyes and returns cropped images of them."""
|
40 |
+
resp = CLIENT_EYES.infer(image_path, model_id="eye-detection-kso3d/3")
|
41 |
+
raw_image = cv2.imread(image_path)
|
42 |
+
if raw_image is None: return [], "Could not read image"
|
43 |
+
eye_crops = []
|
44 |
+
for p in resp.get("predictions", []):
|
45 |
+
x1 = int(p['x'] - p['width'] / 2)
|
46 |
+
y1 = int(p['y'] - p['height'] / 2)
|
47 |
+
x2 = int(p['x'] + p['width'] / 2)
|
48 |
+
y2 = int(p['y'] + p['height'] / 2)
|
49 |
+
eye_crops.append(raw_image[y1:y2, x1:x2])
|
50 |
+
return eye_crops, None
|
51 |
|
52 |
+
def detect_iris_roboflow(eye_crop):
|
53 |
+
"""Calls Roboflow to find the largest iris in an eye crop."""
|
54 |
+
is_success, buffer = cv2.imencode(".jpg", eye_crop)
|
55 |
+
if not is_success: return None
|
56 |
+
resp = CLIENT_IRIS.infer(data=buffer, model_id="iris_120_set/7")
|
57 |
+
preds = resp.get("predictions", [])
|
58 |
+
if not preds: return None
|
59 |
+
largest = max(preds, key=lambda p: p["width"] * p["height"])
|
60 |
+
x1, y1 = int(largest['x'] - largest['width'] / 2), int(largest['y'] - largest['height'] / 2)
|
61 |
+
x2, y2 = int(largest['x'] + largest['width'] / 2), int(largest['y'] + largest['height'] / 2)
|
62 |
+
return eye_crop[y1:y2, x1:x2]
|
63 |
+
|
64 |
+
def run_leukocoria_prediction(iris_crop):
|
65 |
+
"""Runs the loaded TensorFlow model to predict leukocoria."""
|
66 |
+
if model is None: return {"error": "Leukocoria model not loaded"}
|
67 |
+
img_pil = Image.fromarray(cv2.cvtColor(iris_crop, cv2.COLOR_BGR2RGB))
|
68 |
img = img_pil.resize((224, 224))
|
69 |
+
img_array = np.array(img) / 255.0
|
|
|
|
|
|
|
70 |
img_array = np.expand_dims(img_array, axis=0)
|
71 |
+
prediction = model.predict(img_array)
|
72 |
+
return {f"Class_{i}": float(score) for i, score in enumerate(prediction[0])}
|
73 |
+
|
74 |
+
# --- 3. Create the FastAPI App and Main Endpoint ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
app = FastAPI()
|
76 |
|
77 |
+
@app.post("/api/detect/")
|
78 |
+
async def full_detection_pipeline(image: UploadFile = File(...)):
|
79 |
+
"""The main API endpoint that runs the full detection pipeline."""
|
80 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
|
81 |
+
tmp.write(await image.read())
|
82 |
+
temp_image_path = tmp.name
|
83 |
+
|
84 |
+
try:
|
85 |
+
if not detect_faces_roboflow(temp_image_path):
|
86 |
+
return JSONResponse(status_code=400, content={"error": "No face detected."})
|
87 |
+
|
88 |
+
eye_crops, error_msg = detect_eyes_roboflow(temp_image_path)
|
89 |
+
if error_msg or len(eye_crops) != 2:
|
90 |
+
return JSONResponse(status_code=400, content={"error": "Exactly two eyes not detected."})
|
91 |
+
|
92 |
+
results = {}
|
93 |
+
for i, eye_crop in enumerate(eye_crops):
|
94 |
+
side = f"eye_{i+1}"
|
95 |
+
iris_crop = detect_iris_roboflow(eye_crop)
|
96 |
+
if iris_crop is None:
|
97 |
+
results[side] = {"status": "No iris detected", "prediction": None}
|
98 |
+
continue
|
99 |
+
|
100 |
+
prediction = run_leukocoria_prediction(iris_crop)
|
101 |
+
results[side] = {"status": "Processed", "prediction": prediction}
|
102 |
+
|
103 |
+
return JSONResponse(content=results)
|
104 |
+
|
105 |
+
finally:
|
106 |
+
os.remove(temp_image_path)
|
107 |
|
108 |
+
# --- 4. Create the Gradio UI for the homepage ---
|
109 |
+
# This UI will call our own FastAPI endpoint, ensuring consistent logic.
|
110 |
+
def gradio_wrapper(image):
|
111 |
+
"""A wrapper function to call our own FastAPI endpoint from the Gradio UI."""
|
112 |
try:
|
113 |
+
# Save the numpy array from Gradio to a temporary file to send to our API
|
114 |
+
pil_image = Image.fromarray(image)
|
115 |
+
with tempfile.NamedTemporaryFile(mode="wb", suffix=".jpg", delete=False) as tmp:
|
116 |
+
pil_image.save(tmp, format="JPEG")
|
117 |
+
tmp_path = tmp.name
|
118 |
+
|
119 |
+
with open(tmp_path, "rb") as f:
|
120 |
+
files = {'image': ('image.jpg', f, 'image/jpeg')}
|
121 |
+
# The API is running on the same server, so we call it locally
|
122 |
+
response = requests.post("http://127.0.0.1:7860/api/detect/", files=files)
|
123 |
+
|
124 |
+
os.remove(tmp_path) # Clean up the temp file
|
125 |
+
|
126 |
+
if response.status_code == 200:
|
127 |
+
return response.json()
|
128 |
+
else:
|
129 |
+
return {"error": f"API Error {response.status_code}", "details": response.text}
|
130 |
+
|
131 |
except Exception as e:
|
132 |
+
return {"error": str(e)}
|
133 |
|
|
|
134 |
gradio_ui = gr.Interface(
|
135 |
+
fn=gradio_wrapper,
|
136 |
+
inputs=gr.Image(type="numpy", label="Upload an eye image to test"),
|
137 |
outputs=gr.JSON(label="Prediction Results"),
|
138 |
title="LeukoLook Eye Detector",
|
139 |
+
description="A demonstration of the LeukoLook detection model. This UI calls the same API endpoint that the main application uses."
|
140 |
)
|
141 |
|
142 |
+
# --- 5. Mount the Gradio UI onto the FastAPI app's root ---
|
143 |
app = gr.mount_gradio_app(app, gradio_ui, path="/")
|
144 |
|
145 |
+
# --- 6. Run the server ---
|
146 |
if __name__ == "__main__":
|
|
|
147 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|