Spaces:
Sleeping
Sleeping
Nouman-Usman commited on
Commit ·
948f9ef
1
Parent(s): 0c9d1be
Deploy DenseNet121 prediction API with LFS
Browse files- DenseNet121.h5 +3 -0
- Dockerfile +17 -0
- app.py +94 -0
- requirements.txt +6 -0
DenseNet121.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:076f897b3e5fc10e70b2bafb65fece9eae96fe0eeac068fedaf64cf33aa938fd
|
| 3 |
+
size 29509592
|
Dockerfile
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
|
| 2 |
+
FROM python:3.9
|
| 3 |
+
|
| 4 |
+
RUN useradd -m -u 1000 user
|
| 5 |
+
USER user
|
| 6 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
| 11 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 12 |
+
|
| 13 |
+
# Copy all files including the model DenseNet121.h5
|
| 14 |
+
COPY --chown=user . /app
|
| 15 |
+
|
| 16 |
+
# Hugging Face Spaces expect port 7860
|
| 17 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from typing import Dict
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="DenseNet121 Image Prediction API")
|
| 9 |
+
|
| 10 |
+
# Labels dictionary as per requirements
|
| 11 |
+
LABELS = {
|
| 12 |
+
0: {"short": "DR", "full": "Diabetic Retinopathy"},
|
| 13 |
+
1: {"short": "MH", "full": "Media Haze"},
|
| 14 |
+
2: {"short": "NL", "full": "Normal"}
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
# Global variable to store the model
|
| 18 |
+
model = None
|
| 19 |
+
|
| 20 |
+
@app.on_event("startup")
|
| 21 |
+
async def load_model():
|
| 22 |
+
global model
|
| 23 |
+
try:
|
| 24 |
+
# Loading the fully trained model
|
| 25 |
+
model = tf.keras.models.load_model("DenseNet121.h5")
|
| 26 |
+
print("Model loaded successfully.")
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"Error loading model: {e}")
|
| 29 |
+
|
| 30 |
+
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 31 |
+
"""
|
| 32 |
+
Preprocess the image according to requirements:
|
| 33 |
+
- RGB format
|
| 34 |
+
- Resize to 224x224
|
| 35 |
+
- Normalize by dividing by 255
|
| 36 |
+
"""
|
| 37 |
+
if image.mode != "RGB":
|
| 38 |
+
image = image.convert("RGB")
|
| 39 |
+
|
| 40 |
+
image = image.resize((224, 224))
|
| 41 |
+
img_array = np.array(image)
|
| 42 |
+
|
| 43 |
+
# Normalize by 255
|
| 44 |
+
img_array = img_array.astype(np.float32) / 255.0
|
| 45 |
+
|
| 46 |
+
# Add batch dimension
|
| 47 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 48 |
+
|
| 49 |
+
return img_array
|
| 50 |
+
|
| 51 |
+
@app.get("/")
|
| 52 |
+
async def root():
|
| 53 |
+
return {"message": "DenseNet121 Prediction API is running", "model_status": "Loaded" if model else "Not Loaded"}
|
| 54 |
+
|
| 55 |
+
@app.post("/predict")
|
| 56 |
+
async def predict(file: UploadFile = File(...)):
|
| 57 |
+
"""
|
| 58 |
+
Endpoint for image prediction.
|
| 59 |
+
Accepts an image file and returns softmax probabilities and class labels.
|
| 60 |
+
"""
|
| 61 |
+
if model is None:
|
| 62 |
+
raise HTTPException(status_code=500, detail="Model not loaded.")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# Read image
|
| 66 |
+
contents = await file.read()
|
| 67 |
+
image = Image.open(io.BytesIO(contents))
|
| 68 |
+
|
| 69 |
+
# Preprocess
|
| 70 |
+
processed_image = preprocess_image(image)
|
| 71 |
+
|
| 72 |
+
# Predict
|
| 73 |
+
predictions = model.predict(processed_image)[0] # Softmax probabilities
|
| 74 |
+
|
| 75 |
+
# Prepare response
|
| 76 |
+
results = {}
|
| 77 |
+
summary_parts = []
|
| 78 |
+
|
| 79 |
+
for i, prob in enumerate(predictions):
|
| 80 |
+
label_info = LABELS[i]
|
| 81 |
+
percentage = prob * 100
|
| 82 |
+
results[label_info["full"]] = f"{percentage:.2f}%"
|
| 83 |
+
summary_parts.append(f"{int(round(percentage))}% {label_info['short']}")
|
| 84 |
+
|
| 85 |
+
summary_text = ", ".join(summary_parts)
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
"prediction_summary": summary_text,
|
| 89 |
+
"detailed_probabilities": results,
|
| 90 |
+
"top_prediction": LABELS[np.argmax(predictions)]["full"]
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
tensorflow
|
| 4 |
+
Pillow
|
| 5 |
+
python-multipart
|
| 6 |
+
numpy
|