Aadityaramrame commited on
Commit
9f784aa
·
verified ·
1 Parent(s): f4e2c5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -25
app.py CHANGED
@@ -1,24 +1,47 @@
1
- # app.py
2
  from fastapi import FastAPI, UploadFile, File
3
  from fastapi.responses import JSONResponse
 
4
  from keras.models import load_model
5
  from huggingface_hub import hf_hub_download
6
  from PIL import Image
7
  import numpy as np
8
- import uvicorn
9
 
10
- # 🔹 Download model from Hugging Face Hub
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  MODEL_PATH = hf_hub_download(
12
  repo_id="aadityaramrame/blood-cell-cancer-detector",
13
  filename="cancer_classifier.h5"
14
  )
15
-
16
- # 🔹 Load the trained model
17
  model = load_model(MODEL_PATH)
18
 
19
- # 🔹 Initialize FastAPI app
20
- app = FastAPI(title="Cancer Detection API")
 
 
 
 
 
 
 
21
 
 
 
 
22
  @app.get("/")
23
  async def root():
24
  return {"message": "🚀 Cancer Detection API is live!"}
@@ -26,26 +49,14 @@ async def root():
26
  @app.post("/predict")
27
  async def predict(file: UploadFile = File(...)):
28
  try:
29
- # Load and preprocess image
30
  image = Image.open(file.file).convert("RGB").resize((224, 224))
31
  img_array = np.expand_dims(np.array(image) / 255.0, axis=0)
32
 
33
- # Predict
34
  prediction = model.predict(img_array)
35
  predicted_class = int(np.argmax(prediction))
36
  confidence = float(np.max(prediction))
37
 
38
- # 🔹 Map class index to cell type
39
- classes = [
40
- "platelet",
41
- "monocyte",
42
- "lymphocyte",
43
- "erythroblast",
44
- "eosinophil",
45
- "basophil"
46
- ]
47
-
48
- label = classes[predicted_class]
49
 
50
  return JSONResponse(
51
  content={
@@ -54,11 +65,33 @@ async def predict(file: UploadFile = File(...)):
54
  "raw_index": predicted_class
55
  }
56
  )
57
-
58
  except Exception as e:
59
  return JSONResponse(content={"error": str(e)}, status_code=500)
60
 
61
- # 🔹 This line is CRUCIAL for Hugging Face Spaces
62
- # It ensures the FastAPI app is visible when the Space starts
63
- if __name__ == "__main__":
64
- uvicorn.run("app:app", host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.responses import JSONResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
  from keras.models import load_model
5
  from huggingface_hub import hf_hub_download
6
  from PIL import Image
7
  import numpy as np
8
+ import gradio as gr
9
 
10
+ # -------------------------------
11
+ # FASTAPI SETUP
12
+ # -------------------------------
13
+ app = FastAPI(title="Cancer Detection API")
14
+
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ # -------------------------------
24
+ # MODEL LOADING
25
+ # -------------------------------
26
  MODEL_PATH = hf_hub_download(
27
  repo_id="aadityaramrame/blood-cell-cancer-detector",
28
  filename="cancer_classifier.h5"
29
  )
 
 
30
  model = load_model(MODEL_PATH)
31
 
32
+ # Class mapping
33
+ CLASSES = [
34
+ "platelet",
35
+ "monocyte",
36
+ "lymphocyte",
37
+ "erythroblast",
38
+ "eosinophil",
39
+ "basophil"
40
+ ]
41
 
42
+ # -------------------------------
43
+ # FASTAPI ENDPOINTS
44
+ # -------------------------------
45
  @app.get("/")
46
  async def root():
47
  return {"message": "🚀 Cancer Detection API is live!"}
 
49
  @app.post("/predict")
50
  async def predict(file: UploadFile = File(...)):
51
  try:
 
52
  image = Image.open(file.file).convert("RGB").resize((224, 224))
53
  img_array = np.expand_dims(np.array(image) / 255.0, axis=0)
54
 
 
55
  prediction = model.predict(img_array)
56
  predicted_class = int(np.argmax(prediction))
57
  confidence = float(np.max(prediction))
58
 
59
+ label = CLASSES[predicted_class]
 
 
 
 
 
 
 
 
 
 
60
 
61
  return JSONResponse(
62
  content={
 
65
  "raw_index": predicted_class
66
  }
67
  )
 
68
  except Exception as e:
69
  return JSONResponse(content={"error": str(e)}, status_code=500)
70
 
71
+ # -------------------------------
72
+ # GRADIO FRONTEND
73
+ # -------------------------------
74
+ def classify_cancer(image):
75
+ try:
76
+ image = image.convert("RGB").resize((224, 224))
77
+ img_array = np.expand_dims(np.array(image) / 255.0, axis=0)
78
+ prediction = model.predict(img_array)
79
+ predicted_class = int(np.argmax(prediction))
80
+ confidence = float(np.max(prediction))
81
+ label = CLASSES[predicted_class]
82
+ return {label: confidence}
83
+ except Exception as e:
84
+ return {"Error": str(e)}
85
+
86
+ gradio_interface = gr.Interface(
87
+ fn=classify_cancer,
88
+ inputs=gr.Image(type="pil", label="Upload Blood Cell Image"),
89
+ outputs=gr.Label(num_top_classes=3, label="Predicted Cell Type"),
90
+ title="🧫 Blood Cell Cancer Detection",
91
+ description="Upload a blood cell image to predict the cell type using a trained CNN model.",
92
+ theme="soft"
93
+ )
94
+
95
+ # Mount Gradio on FastAPI
96
+ app = gr.mount_gradio_app(app, gradio_interface, path="/")
97
+