This document outlines the development of microservice consisting of two main components: a UI backend service and an AI backend service.The UI end takes the image input from the user. The AI backend utilizes a lightweight open-source model to perform object detection and returns the results in a structured JSON format. The two components communicate seamlessly to provide a comprehensive solution to the user.
Prerequisites
To successfully replicate this solution, ensure you have the following installed:
Docker: For containerization of the application.
Python (Flask or FastAPI): For building the backend services.
Lightweight Detection Model: Any open-source model suitable for object detection (e.g., YOLO, MobileNet SSD,etc)
Deliverables
Your task project folder should be zipped and mailed to us,such that we should be able to replicate your solution in our system or share your github private link.
A documentation to your project solution, essentially the steps, how did you to reach to the solution (any reference you took from anywhere mention it in the documentation)
Output images (containing the bounding box) and corresponding json files.
Use torch yolov10s
Assistant
Technical Assessment Solution
This document provides a comprehensive guide to developing a microservice architecture consisting of a UI Backend Service and an AI Backend Service for object detection using a lightweight YOLO model (yolov10s). The solution leverages FastAPI for building backend services and Docker for containerization. Below, you'll find detailed steps, code snippets, and explanations to help you replicate the solution effectively.
Optional: Python 3.8+ (for local development and testing)
AI Backend Service
The AI Backend Service handles object detection using the yolov10s model. It exposes an API endpoint that receives an image, processes it, and returns detection results.
Setup
Navigate to AI Backend Directory:
bash
cd microservice-object-detection/ai_backend
Create Virtual Environment (Optional for Local Development):
bash
python3 -m venv venv
source venv/bin/activate
Dependencies
Create a requirements.txt file with the following content:
txt
fastapi
uvicorn
torch
opencv-python
pillow
numpy
yolov5 # Replace with yolov10s if available
Note: As of my knowledge cutoff in April 2023, yolov10s may not be officially released. If unavailable, use yolov5 or yolov8. Adjust the dependencies accordingly.
Code Implementation
Create main.py inside ai_backend/app/:
python
# ai_backend/app/main.py
from fastapi import FastAPI, File, UploadFile, HTTPException
from typing import List
import torch
from PIL import Image
import io
import json
import cv2
import numpy as np
import os
app = FastAPI(title="AI Backend Service for Object Detection")
# Load the YOLO model
# Replace 'yolov10s.pt' with the correct model file
MODEL_PATH = "yolov10s.pt"
try:
model = torch.hub.load('ultralytics/yolov5', 'custom', path=MODEL_PATH, force_reload=True)
except Exception as e:
print(f"Error loading model: {e}")
raise e
@app.post("/detect/")
async def detect_objects(file: UploadFile = File(...)):
try:
# Read image file
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert("RGB")
img_bytes = io.BytesIO()
image.save(img_bytes, format='JPEG')
img_bytes = img_bytes.getvalue()
# Perform detection
results = model(img_bytes)
# Process results
detections = results.pandas().xyxy[0].to_json(orient="records")
detections = json.loads(detections)
# Draw bounding boxes
img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
for det in detections:
xmin = int(det['xmin'])
ymin = int(det['ymin'])
xmax = int(det['xmax'])
ymax = int(det['ymax'])
label = det['name']
confidence = det['confidence']
# Draw rectangle
cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
# Put label
cv2.putText(img, f"{label} {confidence:.2f}",
(xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.9, (36,255,12), 2)
# Save the image with bounding boxes
output_image_path = "output.jpg"
cv2.imwrite(output_image_path, img)
# Prepare response
with open(output_image_path, "rb") as img_file:
img_encoded = img_file.read()
return {
"detections": detections,
"image": f"data:image/jpeg;base64,{base64.b64encode(img_encoded).decode('utf-8')}"
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Notes:
Model Loading: The code attempts to load a custom YOLO model. Ensure that yolov10s.pt exists in the ai_backend directory. If using a different YOLO version, adjust accordingly.
Detection Endpoint (/detect/): Accepts image uploads, performs object detection, draws bounding boxes, and returns detections along with the annotated image encoded in Base64.
Error Handling: Basic error handling is implemented to catch and report exceptions.
Dockerization
Create a Dockerfile inside ai_backend/:
dockerfile
# ai_backend/Dockerfile
FROM python:3.9-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
# Copy application
COPY ./app /app
# Copy model
COPY yolov10s.pt /app/
# Expose port
EXPOSE 8001
# Run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
Notes:
Model File: Ensure that the yolov10s.pt model file is placed inside ai_backend/ directory.
Port Exposure: The AI backend service runs on port 8001.
UI Backend Service
The UI Backend Service provides an interface for users to upload images and view object detection results.
Setup
Navigate to UI Backend Directory:
bash
cd microservice-object-detection/ui_backend
Create Virtual Environment (Optional for Local Development):
bash
python3 -m venv venv
source venv/bin/activate
Dependencies
Create a requirements.txt file with the following content:
Template Rendering: Uses Jinja2 templates to render the HTML page with dynamic content.
Error Handling: Displays error messages if any issues occur during image processing.
Dockerization
Create a Dockerfile inside ui_backend/:
dockerfile
# ui_backend/Dockerfile
FROM python:3.9-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
# Copy application
COPY ./app /app
# Expose port
EXPOSE 8000
# Run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
Inter-Service Communication
To enable communication between the UI Backend Service and the AI Backend Service, we'll use Docker Compose to orchestrate both containers and manage networking.
Create a docker-compose.yml in the root directory (microservice-object-detection/):
ui_backend: Exposes port 8000 and depends on ai_backend.
Networking: Both services are connected to the same Docker network (app-network), allowing them to communicate via service names.
Volume Mounting: Maps local directories to container directories for easier development and debugging.
Running the Solution
Navigate to Project Root:
bash
cd microservice-object-detection/
Build and Start Services with Docker Compose:
bash
docker-compose up --build
This command builds the Docker images and starts both services.
Access the UI:
Open your browser and navigate to http://localhost:8000 to access the UI Backend Service.
Using the Application:
Upload Image: Use the form to upload an image.
View Results: After processing, the page will display detection results and the annotated image with bounding boxes.
Stopping the Services:
Press Ctrl + C in the terminal where Docker Compose is running, then execute:
bash
docker-compose down
Deliverables
Project Folder:
Ensure that the entire microservice-object-detection/ directory is zipped, preserving the folder structure.
Alternatively, initialize a Git repository, commit all files, and provide a private GitHub link with necessary access permissions.
Documentation (README.md):
Provide detailed steps on setting up and running the project, including prerequisites, installation steps, and usage instructions. Include any references or resources you utilized.
markdown
# Microservice Object Detection
## Overview
This project consists of two main components:
- **UI Backend Service:** Provides a web interface for users to upload images and view object detection results.
- **AI Backend Service:** Performs object detection using a YOLO-based model and returns structured JSON results.
## Prerequisites
- Docker
- Docker Compose
## Setup and Installation
1. **Clone the Repository:**
```bash
git clone <your-repo-link>
cd microservice-object-detection/
Place YOLO Model:
Ensure the yolov10s.pt model is placed inside the ai_backend/ directory.
Model Compatibility: Ensure that the YOLO model used (yolov10s.pt) is compatible with the Torch hub loading mechanism. If yolov10s is not available, adjust the model loading to use a supported version like yolov5s or yolov8s.
Performance Considerations: Since the assessment specifies using CPU, ensure that the model is optimized for CPU inference to maintain reasonable performance.
Security Considerations: For production environments, consider implementing security measures such as input validation, authentication, and rate limiting.
Scaling: Docker Compose is suitable for development and small-scale deployments. For larger deployments, consider using orchestration tools like Kubernetes.
By following this guide, you should be able to replicate the microservice architecture for object detection, fulfilling all the requirements outlined in the technical assessment. Ensure to test each component thoroughly and validate the communication between services.
After processing images via the UI, ensure that annotated images and corresponding JSON files are saved in a designated output directory or returned via the API.
For demonstration, you can include sample outputs in a samples/ directory.