Spaces:
Running
Running
removed enhance_image_unsharp_mask function
Browse files
app.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
# Final, Complete, and Working app.py for Hugging Face Space
|
2 |
-
|
3 |
import os
|
4 |
import cv2
|
5 |
import tempfile
|
@@ -18,6 +17,7 @@ import gradio as gr
|
|
18 |
|
19 |
# --- 1. Configuration and Model Loading ---
|
20 |
ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY")
|
|
|
21 |
CLIENT_FACE = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
22 |
CLIENT_EYES = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
23 |
CLIENT_IRIS = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
@@ -32,9 +32,8 @@ except Exception as e:
|
|
32 |
raise RuntimeError(f"Could not load leukocoria model: {e}")
|
33 |
|
34 |
# --- 2. All Helper Functions ---
|
35 |
-
|
36 |
-
|
37 |
-
return cv2.addWeighted(image, 1.0 + strength, blur, -strength, 0)
|
38 |
|
39 |
def detect_faces_roboflow(image_path):
|
40 |
return CLIENT_FACE.infer(image_path, model_id="face-detector-v4liw/2").get("predictions", [])
|
@@ -52,41 +51,32 @@ def detect_eyes_roboflow(image_path, raw_image):
|
|
52 |
crop = raw_image[y1:y2, x1:x2]
|
53 |
if crop.size > 0:
|
54 |
crops.append(crop)
|
55 |
-
# On success, return the crops and None for the error message
|
56 |
return crops, None
|
57 |
except Exception as e:
|
58 |
-
# If Roboflow fails, return an empty list and the error message
|
59 |
print(f"Error in Roboflow eye detection: {e}")
|
60 |
return [], str(e)
|
61 |
|
62 |
-
# In app.py, replace the existing function with this one
|
63 |
-
|
64 |
def get_largest_iris_prediction(eye_crop):
|
65 |
"Calls Roboflow to find the largest iris using a temporary file for reliability."
|
66 |
-
|
67 |
-
# --- NEW: Enhance the eye crop before saving it ---
|
68 |
-
enhanced_eye_crop = enhance_image_unsharp_mask(eye_crop)
|
69 |
-
|
70 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
|
71 |
-
# Save the
|
72 |
-
cv2.imwrite(tmp.name,
|
73 |
temp_iris_path = tmp.name
|
74 |
-
|
75 |
try:
|
76 |
-
# Use the file path for inference, which is more robust
|
77 |
resp = CLIENT_IRIS.infer(temp_iris_path, model_id="iris_120_set/7")
|
78 |
preds = resp.get("predictions", [])
|
79 |
return max(preds, key=lambda p: p["width"] * p["height"]) if preds else None
|
80 |
finally:
|
81 |
-
# Ensure the temporary file is always deleted
|
82 |
os.remove(temp_iris_path)
|
83 |
|
84 |
def run_leukocoria_prediction(iris_crop):
|
85 |
if leuko_model is None: return {"error": "Leukocoria model not loaded"}, 0.0
|
|
|
86 |
img_pil = Image.fromarray(cv2.cvtColor(iris_crop, cv2.COLOR_BGR2RGB))
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
90 |
img_array = np.expand_dims(img_array, axis=0)
|
91 |
prediction = leuko_model.predict(img_array)
|
92 |
confidence = float(prediction[0][0])
|
@@ -102,22 +92,18 @@ async def full_detection_pipeline(image: UploadFile = File(...)):
|
|
102 |
contents = await image.read()
|
103 |
tmp.write(contents)
|
104 |
temp_image_path = tmp.name
|
105 |
-
|
106 |
try:
|
107 |
raw_image = cv2.imread(temp_image_path)
|
108 |
if raw_image is None:
|
109 |
return JSONResponse(status_code=400, content={"error": "Could not read uploaded image."})
|
110 |
-
|
111 |
if not detect_faces_roboflow(temp_image_path):
|
112 |
return JSONResponse(status_code=400, content={"error": "No face detected."})
|
113 |
-
|
114 |
image_to_process = raw_image
|
115 |
was_mirrored = False
|
116 |
|
117 |
print("--- 1. Attempting detection on original image... ---")
|
118 |
eye_crops, error_msg = detect_eyes_roboflow(temp_image_path, image_to_process)
|
119 |
print(f"--- 2. Found {len(eye_crops)} eyes in original image. ---")
|
120 |
-
|
121 |
if len(eye_crops) != 2:
|
122 |
print("--- 3. Original failed. Attempting detection on mirrored image... ---")
|
123 |
mirrored_image = cv2.flip(raw_image, 1)
|
@@ -132,16 +118,16 @@ async def full_detection_pipeline(image: UploadFile = File(...)):
|
|
132 |
print(f"--- 4. Found {len(eye_crops)} eyes in mirrored image. ---")
|
133 |
finally:
|
134 |
os.remove(temp_mirrored_image_path)
|
135 |
-
|
136 |
if error_msg or len(eye_crops) != 2:
|
137 |
return JSONResponse(
|
138 |
status_code=400,
|
139 |
content={"error": "Could not detect exactly two eyes. Please try another photo."}
|
140 |
)
|
141 |
-
|
142 |
initial_boxes = [cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)) for c in eye_crops]
|
143 |
print(f"--- 5. Initial eye coordinates (x,y,w,h): {initial_boxes} ---")
|
144 |
-
|
145 |
eye_crops.sort(key=lambda c: cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY))[0])
|
146 |
|
147 |
sorted_boxes = [cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)) for c in eye_crops]
|
@@ -152,7 +138,7 @@ async def full_detection_pipeline(image: UploadFile = File(...)):
|
|
152 |
eye_crops.reverse()
|
153 |
reversed_boxes = [cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)) for c in eye_crops]
|
154 |
print(f"--- 8. Reversed eye coordinates (x,y,w,h): {reversed_boxes} ---")
|
155 |
-
|
156 |
flags = {}
|
157 |
eye_images_b64 = {}
|
158 |
for i, eye_crop in enumerate(eye_crops):
|
@@ -162,7 +148,7 @@ async def full_detection_pipeline(image: UploadFile = File(...)):
|
|
162 |
is_success, buffer = cv2.imencode(".jpg", eye_crop)
|
163 |
if is_success:
|
164 |
eye_images_b64[side] = "data:image/jpeg;base64," + base64.b64encode(buffer).decode("utf-8")
|
165 |
-
|
166 |
pred = get_largest_iris_prediction(eye_crop)
|
167 |
if pred:
|
168 |
x1, y1 = int(pred['x'] - pred['width'] / 2), int(pred['y'] - pred['height'] / 2)
|
@@ -172,27 +158,24 @@ async def full_detection_pipeline(image: UploadFile = File(...)):
|
|
172 |
flags[side] = has_leuko
|
173 |
else:
|
174 |
flags[side] = None
|
175 |
-
|
176 |
-
# --- THIS BLOCK IS NOW CORRECTLY UN-INDENTED ---
|
177 |
-
# It runs AFTER the 'for' loop is complete.
|
178 |
print("--- 10. Final generated flags:", flags, "---")
|
179 |
|
180 |
is_success_main, buffer_main = cv2.imencode(".jpg", image_to_process)
|
181 |
analyzed_image_b64 = ""
|
182 |
if is_success_main:
|
183 |
analyzed_image_b64 = "data:image/jpeg;base64," + base64.b64encode(buffer_main).decode("utf-8")
|
184 |
-
|
185 |
return JSONResponse(content={
|
186 |
"leukocoria": flags,
|
187 |
"warnings": [],
|
188 |
"two_eyes": eye_images_b64,
|
189 |
"analyzed_image": analyzed_image_b64
|
190 |
})
|
191 |
-
|
192 |
finally:
|
193 |
os.remove(temp_image_path)
|
194 |
-
|
195 |
-
# --- 4. Create and Mount the Gradio UI
|
196 |
def gradio_wrapper(image_array):
|
197 |
"""A wrapper function to call our own FastAPI endpoint from the Gradio UI."""
|
198 |
try:
|
@@ -200,8 +183,9 @@ def gradio_wrapper(image_array):
|
|
200 |
with io.BytesIO() as buffer:
|
201 |
pil_image.save(buffer, format="JPEG")
|
202 |
files = {'image': ('image.jpg', buffer.getvalue(), 'image/jpeg')}
|
|
|
203 |
response = requests.post("http://127.0.0.1:7860/detect/", files=files)
|
204 |
-
|
205 |
if response.status_code == 200:
|
206 |
return response.json()
|
207 |
else:
|
@@ -214,8 +198,7 @@ gradio_ui = gr.Interface(
|
|
214 |
inputs=gr.Image(type="numpy", label="Upload an eye image to test the full pipeline"),
|
215 |
outputs=gr.JSON(label="Analysis Results"),
|
216 |
title="LeukoLook Eye Detector",
|
217 |
-
description="A demonstration of the LeukoLook detection model pipeline."
|
218 |
-
)
|
219 |
|
220 |
app = gr.mount_gradio_app(app, gradio_ui, path="/")
|
221 |
|
|
|
1 |
# Final, Complete, and Working app.py for Hugging Face Space
|
|
|
2 |
import os
|
3 |
import cv2
|
4 |
import tempfile
|
|
|
17 |
|
18 |
# --- 1. Configuration and Model Loading ---
|
19 |
ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY")
|
20 |
+
|
21 |
CLIENT_FACE = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
22 |
CLIENT_EYES = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
23 |
CLIENT_IRIS = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
|
|
|
32 |
raise RuntimeError(f"Could not load leukocoria model: {e}")
|
33 |
|
34 |
# --- 2. All Helper Functions ---
|
35 |
+
|
36 |
+
# NOTE: The 'enhance_image_unsharp_mask' function has been removed.
|
|
|
37 |
|
38 |
def detect_faces_roboflow(image_path):
|
39 |
return CLIENT_FACE.infer(image_path, model_id="face-detector-v4liw/2").get("predictions", [])
|
|
|
51 |
crop = raw_image[y1:y2, x1:x2]
|
52 |
if crop.size > 0:
|
53 |
crops.append(crop)
|
|
|
54 |
return crops, None
|
55 |
except Exception as e:
|
|
|
56 |
print(f"Error in Roboflow eye detection: {e}")
|
57 |
return [], str(e)
|
58 |
|
|
|
|
|
59 |
def get_largest_iris_prediction(eye_crop):
|
60 |
"Calls Roboflow to find the largest iris using a temporary file for reliability."
|
|
|
|
|
|
|
|
|
61 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
|
62 |
+
# Save the original eye crop, not an enhanced version
|
63 |
+
cv2.imwrite(tmp.name, eye_crop)
|
64 |
temp_iris_path = tmp.name
|
|
|
65 |
try:
|
|
|
66 |
resp = CLIENT_IRIS.infer(temp_iris_path, model_id="iris_120_set/7")
|
67 |
preds = resp.get("predictions", [])
|
68 |
return max(preds, key=lambda p: p["width"] * p["height"]) if preds else None
|
69 |
finally:
|
|
|
70 |
os.remove(temp_iris_path)
|
71 |
|
72 |
def run_leukocoria_prediction(iris_crop):
|
73 |
if leuko_model is None: return {"error": "Leukocoria model not loaded"}, 0.0
|
74 |
+
# Convert crop to PIL Image
|
75 |
img_pil = Image.fromarray(cv2.cvtColor(iris_crop, cv2.COLOR_BGR2RGB))
|
76 |
+
# Resize the original image array
|
77 |
+
img_resized = cv2.resize(np.array(img_pil), (224, 224))
|
78 |
+
# Normalize and expand dimensions for the model
|
79 |
+
img_array = np.array(img_resized) / 255.0
|
80 |
img_array = np.expand_dims(img_array, axis=0)
|
81 |
prediction = leuko_model.predict(img_array)
|
82 |
confidence = float(prediction[0][0])
|
|
|
92 |
contents = await image.read()
|
93 |
tmp.write(contents)
|
94 |
temp_image_path = tmp.name
|
|
|
95 |
try:
|
96 |
raw_image = cv2.imread(temp_image_path)
|
97 |
if raw_image is None:
|
98 |
return JSONResponse(status_code=400, content={"error": "Could not read uploaded image."})
|
|
|
99 |
if not detect_faces_roboflow(temp_image_path):
|
100 |
return JSONResponse(status_code=400, content={"error": "No face detected."})
|
|
|
101 |
image_to_process = raw_image
|
102 |
was_mirrored = False
|
103 |
|
104 |
print("--- 1. Attempting detection on original image... ---")
|
105 |
eye_crops, error_msg = detect_eyes_roboflow(temp_image_path, image_to_process)
|
106 |
print(f"--- 2. Found {len(eye_crops)} eyes in original image. ---")
|
|
|
107 |
if len(eye_crops) != 2:
|
108 |
print("--- 3. Original failed. Attempting detection on mirrored image... ---")
|
109 |
mirrored_image = cv2.flip(raw_image, 1)
|
|
|
118 |
print(f"--- 4. Found {len(eye_crops)} eyes in mirrored image. ---")
|
119 |
finally:
|
120 |
os.remove(temp_mirrored_image_path)
|
121 |
+
|
122 |
if error_msg or len(eye_crops) != 2:
|
123 |
return JSONResponse(
|
124 |
status_code=400,
|
125 |
content={"error": "Could not detect exactly two eyes. Please try another photo."}
|
126 |
)
|
127 |
+
|
128 |
initial_boxes = [cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)) for c in eye_crops]
|
129 |
print(f"--- 5. Initial eye coordinates (x,y,w,h): {initial_boxes} ---")
|
130 |
+
|
131 |
eye_crops.sort(key=lambda c: cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY))[0])
|
132 |
|
133 |
sorted_boxes = [cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)) for c in eye_crops]
|
|
|
138 |
eye_crops.reverse()
|
139 |
reversed_boxes = [cv2.boundingRect(cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)) for c in eye_crops]
|
140 |
print(f"--- 8. Reversed eye coordinates (x,y,w,h): {reversed_boxes} ---")
|
141 |
+
|
142 |
flags = {}
|
143 |
eye_images_b64 = {}
|
144 |
for i, eye_crop in enumerate(eye_crops):
|
|
|
148 |
is_success, buffer = cv2.imencode(".jpg", eye_crop)
|
149 |
if is_success:
|
150 |
eye_images_b64[side] = "data:image/jpeg;base64," + base64.b64encode(buffer).decode("utf-8")
|
151 |
+
|
152 |
pred = get_largest_iris_prediction(eye_crop)
|
153 |
if pred:
|
154 |
x1, y1 = int(pred['x'] - pred['width'] / 2), int(pred['y'] - pred['height'] / 2)
|
|
|
158 |
flags[side] = has_leuko
|
159 |
else:
|
160 |
flags[side] = None
|
161 |
+
|
|
|
|
|
162 |
print("--- 10. Final generated flags:", flags, "---")
|
163 |
|
164 |
is_success_main, buffer_main = cv2.imencode(".jpg", image_to_process)
|
165 |
analyzed_image_b64 = ""
|
166 |
if is_success_main:
|
167 |
analyzed_image_b64 = "data:image/jpeg;base64," + base64.b64encode(buffer_main).decode("utf-8")
|
168 |
+
|
169 |
return JSONResponse(content={
|
170 |
"leukocoria": flags,
|
171 |
"warnings": [],
|
172 |
"two_eyes": eye_images_b64,
|
173 |
"analyzed_image": analyzed_image_b64
|
174 |
})
|
|
|
175 |
finally:
|
176 |
os.remove(temp_image_path)
|
177 |
+
|
178 |
+
# --- 4. Create and Mount the Gradio UI ---
|
179 |
def gradio_wrapper(image_array):
|
180 |
"""A wrapper function to call our own FastAPI endpoint from the Gradio UI."""
|
181 |
try:
|
|
|
183 |
with io.BytesIO() as buffer:
|
184 |
pil_image.save(buffer, format="JPEG")
|
185 |
files = {'image': ('image.jpg', buffer.getvalue(), 'image/jpeg')}
|
186 |
+
# The URL points to the local FastAPI server running within the Hugging Face Space
|
187 |
response = requests.post("http://127.0.0.1:7860/detect/", files=files)
|
188 |
+
|
189 |
if response.status_code == 200:
|
190 |
return response.json()
|
191 |
else:
|
|
|
198 |
inputs=gr.Image(type="numpy", label="Upload an eye image to test the full pipeline"),
|
199 |
outputs=gr.JSON(label="Analysis Results"),
|
200 |
title="LeukoLook Eye Detector",
|
201 |
+
description="A demonstration of the LeukoLook detection model pipeline.")
|
|
|
202 |
|
203 |
app = gr.mount_gradio_app(app, gradio_ui, path="/")
|
204 |
|