python
# requirements.txt
"""
fastapi==0.104.1
uvicorn[standard]==0.24.0
tensorflow==2.14.0
pillow==10.1.0
numpy==1.24.3
python-multipart==0.0.6
"""
# main.py
import io
import numpy as np
import tensorflow as tf
from PIL import Image
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
import uvicorn
from typing import List, Dict
app = FastAPI(title="Real-Time Image Recognition Microservice", version="1.0.0")
# Load pre-trained MobileNetV2 model on startup (ImageNet trained, 1000 classes)
# This is efficient (~4MB model size, <100ms inference on CPU)
model = tf.keras.applications.MobileNetV2(
weights='imagenet',
include_top=True
)
def preprocess_image(image: Image.Image, target_size: int = 224) -> np.ndarray:
"""
Preprocess PIL Image for MobileNetV2:
- Resize to 224x224
- Convert to numpy array
- Apply MobileNetV2-specific preprocessing (scale to [-1,1])
- Add batch dimension
"""
image = image.convert('RGB').resize((target_size, target_size))
image_array = np.array(image, dtype=np.float32)
processed = tf.keras.applications.mobilenet_v2.preprocess_input(image_array)
return np.expand_dims(processed, axis=0)
@app.post("/recognize", response_model=Dict[str, List[Dict[str, str]]])
async def recognize_image(file: UploadFile = File(..., media_type="image/*")):
"""
Real-time image recognition endpoint.
- Upload an image file (JPEG/PNG).
- Returns top-5 predictions with ImageNet class labels and confidence scores.
- Optimized for low-latency (~50-200ms on CPU, faster on GPU).
"""
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents))
# Preprocess
processed_image = preprocess_image(image)
# Inference
predictions = model.predict(processed_image, verbose=0)
# Decode top-5 predictions (includes ImageNet class names)
decoded_predictions = tf.keras.applications.imagenet_utils.decode_predictions(
predictions[0], top=5
)[0]
results = [
{"class": pred[1], "score": f"{float(pred[2]):.4f}"}
for pred in decoded_predictions
]
return {"predictions": results}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Image processing failed: {str(e)}")
@app.get("/health")
async def health_check():
"""Health check endpoint for microservice readiness."""
return {"status": "healthy", "model_loaded": True}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY main.py .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]