skibi11 commited on
Commit
ab24187
·
verified ·
1 Parent(s): 6aa2786

debugged the vercel, render, and huggingface connection

Browse files
Files changed (1) hide show
  1. app.py +34 -17
app.py CHANGED
@@ -1,16 +1,19 @@
1
- # Final, API-only 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 tensorflow as tf
13
  from huggingface_hub import hf_hub_download
 
14
 
15
  # --- 1. Configuration and Model Loading ---
16
  ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY")
@@ -39,10 +42,8 @@ def detect_eyes_roboflow(image_path, raw_image):
39
  resp = CLIENT_EYES.infer(image_path, model_id="eye-detection-kso3d/3")
40
  crops = []
41
  for p in resp.get("predictions", []):
42
- x1 = int(p['x'] - p['width'] / 2)
43
- y1 = int(p['y'] - p['height'] / 2)
44
- x2 = int(p['x'] + p['width'] / 2)
45
- y2 = int(p['y'] + p['height'] / 2)
46
  crop = raw_image[y1:y2, x1:x2]
47
  if crop.size > 0:
48
  crops.append(crop)
@@ -57,30 +58,19 @@ def get_largest_iris_prediction(eye_crop):
57
 
58
  def run_leukocoria_prediction(iris_crop):
59
  if leuko_model is None: return {"error": "Leukocoria model not loaded"}, 0.0
60
-
61
  img_pil = Image.fromarray(cv2.cvtColor(iris_crop, cv2.COLOR_BGR2RGB))
62
  enh = enhance_image_unsharp_mask(np.array(img_pil))
63
  enh_rs = cv2.resize(enh, (224, 224))
64
  img_array = np.array(enh_rs) / 255.0
65
  img_array = np.expand_dims(img_array, axis=0)
66
-
67
  prediction = leuko_model.predict(img_array)
68
  confidence = float(prediction[0][0])
69
  has_leuko = confidence > 0.5
70
-
71
  return has_leuko, confidence
72
 
73
  # --- 3. FastAPI Application ---
74
  app = FastAPI()
75
 
76
- # --- remove display error ---
77
- @app.get("/")
78
- def read_root():
79
- return {
80
- "status": "LeukoLook API is running",
81
- "documentation": "Send a POST request to the /detect/ endpoint with an image file."
82
- }
83
-
84
  @app.post("/detect/")
85
  async def full_detection_pipeline(image: UploadFile = File(...)):
86
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
@@ -118,6 +108,33 @@ async def full_detection_pipeline(image: UploadFile = File(...)):
118
  finally:
119
  os.remove(temp_image_path)
120
 
121
- # --- 4. Run the Server ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  if __name__ == "__main__":
123
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ # Final, Complete, and Working 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
+ import requests
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
  ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY")
 
42
  resp = CLIENT_EYES.infer(image_path, model_id="eye-detection-kso3d/3")
43
  crops = []
44
  for p in resp.get("predictions", []):
45
+ x1, y1 = int(p['x'] - p['width'] / 2), int(p['y'] - p['height'] / 2)
46
+ x2, y2 = int(p['x'] + p['width'] / 2), int(p['y'] + p['height'] / 2)
 
 
47
  crop = raw_image[y1:y2, x1:x2]
48
  if crop.size > 0:
49
  crops.append(crop)
 
58
 
59
  def run_leukocoria_prediction(iris_crop):
60
  if leuko_model is None: return {"error": "Leukocoria model not loaded"}, 0.0
 
61
  img_pil = Image.fromarray(cv2.cvtColor(iris_crop, cv2.COLOR_BGR2RGB))
62
  enh = enhance_image_unsharp_mask(np.array(img_pil))
63
  enh_rs = cv2.resize(enh, (224, 224))
64
  img_array = np.array(enh_rs) / 255.0
65
  img_array = np.expand_dims(img_array, axis=0)
 
66
  prediction = leuko_model.predict(img_array)
67
  confidence = float(prediction[0][0])
68
  has_leuko = confidence > 0.5
 
69
  return has_leuko, confidence
70
 
71
  # --- 3. FastAPI Application ---
72
  app = FastAPI()
73
 
 
 
 
 
 
 
 
 
74
  @app.post("/detect/")
75
  async def full_detection_pipeline(image: UploadFile = File(...)):
76
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
 
108
  finally:
109
  os.remove(temp_image_path)
110
 
111
+ # --- 4. Create and Mount the Gradio UI for a professional homepage ---
112
+ def gradio_wrapper(image_array):
113
+ """A wrapper function to call our own FastAPI endpoint from the Gradio UI."""
114
+ try:
115
+ pil_image = Image.fromarray(image_array)
116
+ with io.BytesIO() as buffer:
117
+ pil_image.save(buffer, format="JPEG")
118
+ files = {'image': ('image.jpg', buffer.getvalue(), 'image/jpeg')}
119
+ response = requests.post("http://127.0.0.1:7860/detect/", files=files)
120
+
121
+ if response.status_code == 200:
122
+ return response.json()
123
+ else:
124
+ return {"error": f"API Error {response.status_code}", "details": response.text}
125
+ except Exception as e:
126
+ return {"error": str(e)}
127
+
128
+ gradio_ui = gr.Interface(
129
+ fn=gradio_wrapper,
130
+ inputs=gr.Image(type="numpy", label="Upload an eye image to test the full pipeline"),
131
+ outputs=gr.JSON(label="Analysis Results"),
132
+ title="LeukoLook Eye Detector",
133
+ description="A demonstration of the LeukoLook detection model pipeline."
134
+ )
135
+
136
+ app = gr.mount_gradio_app(app, gradio_ui, path="/")
137
+
138
+ # --- 5. Run the server ---
139
  if __name__ == "__main__":
140
  uvicorn.run(app, host="0.0.0.0", port=7860)