skibi11 commited on
Commit
976b4e4
·
0 Parent(s):

Initial commit: consolidate frontend, backend, api, and model into monorepo

Browse files
Files changed (4) hide show
  1. .gitattributes +35 -0
  2. README.md +14 -0
  3. app.py +219 -0
  4. requirements.txt +9 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Leukolook Api
3
+ emoji: 🏃
4
+ colorFrom: blue
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 5.34.2
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ short_description: run our model and expose it as an API
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # Adapted to follow the logic from the provided Django api/views.py with added logging
3
+ import os
4
+ import cv2
5
+ import tempfile
6
+ import numpy as np
7
+ import uvicorn
8
+ import base64
9
+ import io
10
+ from PIL import Image
11
+ from inference_sdk import InferenceHTTPClient
12
+ from fastapi import FastAPI, File, UploadFile
13
+ from fastapi.responses import JSONResponse
14
+ import tensorflow as tf
15
+ from huggingface_hub import hf_hub_download
16
+ import gradio as gr
17
+
18
+ # --- 1. Configuration and Model Loading ---
19
+ # Constants from the new Django logic
20
+ MAX_INFER_DIM = 1024
21
+ ENHANCED_SIZE = (224, 224)
22
+
23
+ # Roboflow and TF Model setup
24
+ ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY")
25
+ CLIENT_FACE = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
26
+ CLIENT_EYES = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
27
+ CLIENT_IRIS = InferenceHTTPClient(api_url="https://detect.roboflow.com", api_key=ROBOFLOW_API_KEY)
28
+
29
+ leuko_model = None
30
+ try:
31
+ model_path = hf_hub_download("skibi11/leukolook-eye-detector", "MobileNetV1_best.keras")
32
+ leuko_model = tf.keras.models.load_model(model_path)
33
+ print("--- LEUKOCORIA MODEL LOADED SUCCESSFULLY! ---")
34
+ except Exception as e:
35
+ print(f"--- FATAL ERROR: COULD NOT LOAD LEUKOCORIA MODEL: {e} ---")
36
+ raise RuntimeError(f"Could not load leukocoria model: {e}")
37
+
38
+ # --- 2. Helper Functions (Adapted from Django views.py) ---
39
+
40
+ def enhance_image_unsharp_mask(image, strength=0.5, radius=5):
41
+ """Enhances image using unsharp masking."""
42
+ blur = cv2.GaussianBlur(image, (radius, radius), 0)
43
+ return cv2.addWeighted(image, 1.0 + strength, blur, -strength, 0)
44
+
45
+ def detect_faces_roboflow(image_path):
46
+ """Detects faces using Roboflow."""
47
+ return CLIENT_FACE.infer(image_path, model_id="face-detector-v4liw/2").get("predictions", [])
48
+
49
+ def detect_eyes_roboflow(image_path):
50
+ """
51
+ Detects eyes, resizing the image if necessary for inference,
52
+ then scales coordinates back to the original image size.
53
+ """
54
+ raw_image = cv2.imread(image_path)
55
+ if raw_image is None:
56
+ return None, []
57
+
58
+ h, w = raw_image.shape[:2]
59
+ scale = min(1.0, MAX_INFER_DIM / max(h, w))
60
+
61
+ if scale < 1.0:
62
+ small_image = cv2.resize(raw_image, (int(w*scale), int(h*scale)))
63
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
64
+ cv2.imwrite(tmp.name, small_image)
65
+ infer_path = tmp.name
66
+ else:
67
+ infer_path = image_path
68
+
69
+ try:
70
+ resp = CLIENT_EYES.infer(infer_path, model_id="eye-detection-kso3d/3")
71
+ finally:
72
+ if scale < 1.0 and os.path.exists(infer_path):
73
+ os.remove(infer_path)
74
+
75
+ crops = []
76
+ for p in resp.get("predictions", []):
77
+ cx, cy = p["x"] / scale, p["y"] / scale
78
+ bw, bh = p["width"] / scale, p["height"] / scale
79
+
80
+ x1 = int(cx - bw / 2)
81
+ y1 = int(cy - bh / 2)
82
+ x2 = int(cx + bw / 2)
83
+ y2 = int(cy + bh / 2)
84
+
85
+ crop = raw_image[y1:y2, x1:x2]
86
+ if crop.size > 0:
87
+ crops.append({"coords": (x1, y1, x2, y2), "image": crop})
88
+
89
+ return raw_image, crops
90
+
91
+ def get_largest_iris_prediction(eye_crop):
92
+ """Finds the largest iris in an eye crop."""
93
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
94
+ cv2.imwrite(tmp.name, eye_crop)
95
+ temp_path = tmp.name
96
+ try:
97
+ resp = CLIENT_IRIS.infer(temp_path, model_id="iris_120_set/7")
98
+ preds = resp.get("predictions", [])
99
+ return max(preds, key=lambda p: p["width"] * p["height"]) if preds else None
100
+ finally:
101
+ os.remove(temp_path)
102
+
103
+ def run_leukocoria_prediction(iris_crop):
104
+ """Runs the loaded TensorFlow model on an iris crop."""
105
+ enh = enhance_image_unsharp_mask(iris_crop)
106
+ enh_rs = cv2.resize(enh, ENHANCED_SIZE)
107
+
108
+ img_array = np.array(enh_rs) / 255.0
109
+ img_array = np.expand_dims(img_array, axis=0)
110
+
111
+ prediction = leuko_model.predict(img_array)
112
+ confidence = float(prediction[0][0])
113
+ has_leuko = confidence > 0.5
114
+ return has_leuko, confidence
115
+
116
+ def to_base64(image):
117
+ """Converts a CV2 image to a base64 string."""
118
+ _, buffer = cv2.imencode(".jpg", image)
119
+ return "data:image/jpeg;base64," + base64.b64encode(buffer).decode()
120
+
121
+ # --- 3. FastAPI Application ---
122
+ app = FastAPI()
123
+
124
+ @app.post("/detect/")
125
+ async def full_detection_pipeline(image: UploadFile = File(...)):
126
+ print("\n--- 1. Starting full detection pipeline. ---")
127
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
128
+ tmp.write(await image.read())
129
+ temp_image_path = tmp.name
130
+
131
+ try:
132
+ print("--- 2. Checking for faces... ---")
133
+ if not detect_faces_roboflow(temp_image_path):
134
+ print("--- 2a. No face detected. Aborting. ---")
135
+ return JSONResponse(status_code=200, content={"warnings": ["No face detected."]})
136
+ print("--- 2b. Face found. Proceeding. ---")
137
+
138
+ print("--- 3. Detecting eyes... ---")
139
+ raw_image, eye_crops = detect_eyes_roboflow(temp_image_path)
140
+ if raw_image is None:
141
+ return JSONResponse(status_code=400, content={"error": "Could not read uploaded image."})
142
+
143
+ print(f"--- 4. Found {len(eye_crops)} eyes. ---")
144
+ if len(eye_crops) != 2:
145
+ return JSONResponse(status_code=200, content={
146
+ "analyzed_image": to_base64(raw_image),
147
+ "warnings": ["Exactly two eyes not detected."]
148
+ })
149
+
150
+ initial_coords = [e['coords'] for e in eye_crops]
151
+ print(f"--- 5. Initial eye coordinates: {initial_coords} ---")
152
+
153
+ sorted_eyes = sorted(eye_crops, key=lambda e: e["coords"][0])
154
+ sorted_coords = [e['coords'] for e in sorted_eyes]
155
+ print(f"--- 6. Sorted eye coordinates: {sorted_coords} ---")
156
+
157
+ images_b64 = {}
158
+ flags = {}
159
+
160
+ for i, eye_info in enumerate(sorted_eyes):
161
+ side = "right" if i == 0 else "left"
162
+ print(f"--- 7. Processing side: '{side}' ---")
163
+ eye_img = eye_info["image"]
164
+
165
+ pred = get_largest_iris_prediction(eye_img)
166
+ if pred:
167
+ print(f"--- 8. Iris found for '{side}' eye. Running leukocoria prediction... ---")
168
+ cx, cy, w, h = pred["x"], pred["y"], pred["width"], pred["height"]
169
+ x1, y1 = int(cx - w / 2), int(cy - h / 2)
170
+ x2, y2 = int(cx + w / 2), int(cy + h / 2)
171
+
172
+ iris_crop = eye_img[y1:y2, x1:x2]
173
+
174
+ has_leuko, confidence = run_leukocoria_prediction(iris_crop)
175
+ print(f"--- 9. Prediction for '{side}' eye: Has Leukocoria={has_leuko}, Confidence={confidence:.4f} ---")
176
+ flags[side] = has_leuko
177
+ else:
178
+ print(f"--- 8a. No iris found for '{side}' eye. ---")
179
+ flags[side] = None
180
+
181
+ images_b64[side] = to_base64(eye_img)
182
+
183
+ print(f"--- 10. Final generated flags: {flags} ---")
184
+ return JSONResponse(status_code=200, content={
185
+ "analyzed_image": to_base64(raw_image),
186
+ "two_eyes": images_b64,
187
+ "leukocoria": flags,
188
+ "warnings": []
189
+ })
190
+
191
+ finally:
192
+ os.remove(temp_image_path)
193
+
194
+ # --- 4. Gradio UI (for simple testing) ---
195
+ def gradio_wrapper(image_array):
196
+ try:
197
+ pil_image = Image.fromarray(image_array)
198
+ with io.BytesIO() as buffer:
199
+ pil_image.save(buffer, format="JPEG")
200
+ files = {'image': ('image.jpg', buffer.getvalue(), 'image/jpeg')}
201
+ response = requests.post("http://127.0.0.1:7860/detect/", files=files)
202
+
203
+ return response.json()
204
+ except Exception as e:
205
+ return {"error": str(e)}
206
+
207
+ gradio_ui = gr.Interface(
208
+ fn=gradio_wrapper,
209
+ inputs=gr.Image(type="numpy", label="Upload an eye image"),
210
+ outputs=gr.JSON(label="Analysis Results"),
211
+ title="LeukoLook Eye Detector",
212
+ description="Demonstration of the full detection pipeline."
213
+ )
214
+
215
+ app = gr.mount_gradio_app(app, gradio_ui, path="/")
216
+
217
+ # --- 5. Run Server ---
218
+ if __name__ == "__main__":
219
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ tensorflow==2.10.0
2
+ numpy==1.24.4
3
+ Pillow
4
+ gradio
5
+ huggingface_hub
6
+ fastapi
7
+ uvicorn
8
+ opencv-python
9
+ inference-sdk