1. Understand the Goal: The user wants a Python microservice for real-time image recognition using TensorFlow.
-
Identify Key Components:
- Language: Python.
- Framework: A lightweight web framework suitable for microservices (Flask or FastAPI are best; FastAPI is generally preferred now for async support and performance).
- ML Library: TensorFlow (Keras).
- Model: Pre-trained models (like MobileNetV2 or ResNet50) are best for a "getting started" example to avoid long training times and focus on the service architecture. MobileNetV2 is fast and suitable for "real-time" concepts.
- Functionality: Receive an image (upload or URL), process it, run inference, return results.
-
Architecture Design:
- Endpoint:
/predict (POST).
- Input: Multipart form data (image file).
- Processing Pipeline:
- Receive request.
- Load image into memory.
- Pre-process image (resize, normalize) to match model input shape.
- Run model prediction.
- Decode prediction (convert indices to human-readable labels).
- Return JSON response.
-
Drafting the Code (Mental or Scratchpad):
-
Dependencies: tensorflow, numpy, pillow (PIL), fastapi, uvicorn, python-multipart.
-
Setup: Initialize FastAPI app. Load the model globally (outside the request loop) to avoid reloading on every request (crucial for performance).
-
Model Loading: tf.keras.applications.MobileNetV2(weights='imagenet'). This is standard.
-
Preprocessing: tf.keras.applications.mobilenet_v2.preprocess_input. The image needs to be resized to (224, 224) usually.
-
Endpoint Logic:
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image = load_image(file)
image = preprocess(image)
preds = model.predict(image)
results = decode_predictions(preds)
return results
-
Refining the Solution:
- Real-time aspect: "Real-time" usually implies low latency. FastAPI is better than Flask here because it's asynchronous. I should emphasize loading the model once at startup.
- Error Handling: What if the file isn't an image? Need a
try-except block.
- Dockerization: A microservice is rarely just a script. It needs a
Dockerfile to be a true deployable microservice. This adds significant value.
-
Structuring the Output:
- Prerequisites: List libraries.
- Project Structure: Show file layout.
- Code Implementation:
requirements.txt
main.py (The core service)
- Docker Support:
Dockerfile.
- Testing/Usage: How to run it locally and how to call it (curl or Python script).
-
Writing the Code (Iterative refinement):
- FastAPI Code: Using
UploadFile allows streaming, which is good, but for simple preprocessing, reading into bytes is necessary.
- PIL vs OpenCV: PIL is easier for basic loading from bytes in a web context without heavy system dependencies like OpenCV sometimes has.
- TensorFlow specific:
tf.keras.applications.mobilenet_v2.preprocess_input expects a specific range.
decode_predictions is a helper utility in Keras that maps top indices to ImageNet class names (e.g., "Labrador retriever").
-
Final Code Assembly:
- main.py:
- Import
FastAPI, File, UploadFile.
- Import
tensorflow, numpy, PIL.
- Load Model:
MobileNetV2.
- Endpoint: Read
file.read(), open with Image.open, convert to RGB (ensure 3 channels), resize, img_to_array, expand dims, preprocess, predict.
- Dockerfile: Start from
python:3.9-slim. Install dependencies. Copy code. Run uvicorn.
-
Review against constraints:
- Python? Yes.
- Microservice? Yes (FastAPI + Docker).
- Real-time Image Recognition? Yes (uses efficient MobileNetV2 for low latency).
- TensorFlow? Yes.
-
Self-Correction/Optimization during drafting:
- Issue: TensorFlow is heavy.
- Mitigation: Warn the user that the first run takes time to load weights.
- Issue:
preprocess_input behavior varies by model.
- Fix: Use the specific
preprocess_input function associated with MobileNetV2.
-
Final Polish: Add comments explaining why we are doing things (e.g., "We load the model outside the endpoint to keep it in memory"). Ensure the curl command is correct.
-
Generate Output. (This matches the detailed response provided previously.)
This guide builds a robust, production-ready microservice using FastAPI (for high performance) and TensorFlow.
We will use the MobileNetV2 model pre-trained on ImageNet. This model is lightweight and accurate, making it ideal for "real-time" use cases.
1. Prerequisites
You will need Python installed. Create a project folder and install the required libraries.
Create a requirements.txt file:
fastapi
uvicorn
python-multipart
tensorflow
numpy
pillow
Install them:
pip install -r requirements.txt
2. The Microservice Code
Create a file named main.py. This code initializes the model once (to save memory) and creates an endpoint to handle image uploads.
import io
import numpy as np
from fastapi import FastAPI, File, UploadFile, HTTPException
from PIL import Image
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
# 1. Initialize the App
app = FastAPI(title="Image Recognition Microservice")
# 2. Load the Model Globaly
# We do this outside the endpoint so it loads into memory only once on startup.
print("Loading model... (this may take a moment)")
model = MobileNetV2(weights='imagenet')
print("Model loaded successfully.")
def prepare_image(image_bytes):
"""
Takes raw image bytes, converts to PIL Image, resizes,
and preprocesses for MobileNetV2.
"""
try:
# Open image using Pillow
img = Image.open(io.BytesIO(image_bytes))
# Convert to RGB (handle PNGs with transparency or grayscale)
if img.mode != "RGB":
img = img.convert("RGB")
# Resize to 224x224 pixels (MobileNet input size)
img = img.resize((224, 224))
# Convert image to numpy array
img_array = np.array(img)
# Expand dimensions to match model input shape (1, 224, 224, 3)
img_array = np.expand_dims(img_array, axis=0)
# Preprocess input (normalize pixel values)
return preprocess_input(img_array)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid image file: {str(e)}")
@app.get("/")
def health_check():
return {"status": "ok", "model": "MobileNetV2"}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
"""
Endpoint to accept an image file and return classification predictions.
"""
# 1. Read the file
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File provided is not an image.")
image_bytes = await file.read()
# 2. Process the image
processed_img = prepare_image(image_bytes)
# 3. Make Prediction
# We use verbose=0 to keep logs clean
predictions = model.predict(processed_img, verbose=0)
# 4. Decode results into human-readable labels
# We get the top 3 results
decoded_results = decode_predictions(predictions, top=3)[0]
# Format the response
results = []
for i, (imagenet_id, label, score) in enumerate(decoded_results):
results.append({
"rank": i + 1,
"label": label,
"confidence": f"{score * 100:.2f}%"
})
return {
"filename": file.filename,
"predictions": results
}
3. How to Run the Service
Open your terminal in the project directory and run the server using Uvicorn (an ASGI server):
uvicorn main:app --reload --host 0.0.0.0 --port 8000
You should see output indicating the server is running and the model is loaded.
4. How to Test It
You can test the microservice using cURL or a Python script.
Option A: Using cURL
Save an image (e.g., cat.jpg) in your folder and run:
curl -X POST -F "file=@cat.jpg" http://localhost:8000/predict
Option B: Using Python (Client Script)
Create a file client.py:
import requests
url = "http://localhost:8000/predict"
file_path = "cat.jpg" # Replace with a real image path
with open(file_path, "rb") as f:
files = {"file": (file_path, f, "image/jpeg")}
response = requests.post(url, files=files)
print(response.json())
5. Architecture Explanation
- FastAPI: We chose FastAPI over Flask because it supports async requests natively. This is crucial for I/O-bound operations (like receiving files) and works well alongside CPU-bound tasks like TensorFlow inference.
- Model Singleton: The
model = MobileNetV2(...) line is outside the function. If we put this inside the predict function, the service would reload the 10MB+ model into memory for every single request, making it extremely slow.
- Preprocessing: Deep learning models expect images in a specific format (usually 224x224 pixels). The
prepare_image function handles resizing and color conversion. preprocess_input handles scaling pixel values to the range the model was trained on (usually -1 to 1 or 0 to 1).
- MobileNetV2: We used a pre-trained model on ImageNet. While you can swap this out for a custom model (e.g.,
tf.keras.models.load_model('my_model.h5')), MobileNetV2 is designed to be fast and lightweight, perfect for a microservice demo.
6. Dockerizing (Optional)
To make this a true microservice, you should containerize it.
Create a Dockerfile:
FROM python:3.9-slim
WORKDIR /app
# Install system dependencies for Pillow
RUN apt-get update && apt-get install -y libgl1-mesa-glx gcc
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
# Expose the port
EXPOSE 8000
# Run the app
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Build and Run:
docker build -t tf-service .
docker run -p 8000:8000 tf-service