Skip to content

IntelliLot/Flask-API-Server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

16 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

YOLOv8 Parking Detection System

A comprehensive computer vision system for parking space detection and occupancy monitoring using YOLOv8, with MongoDB integration and multi-tenant authentication.

Description

This system detects vehicles in parking lots and determines which parking slots are occupied or empty. It provides:

  • Vehicle Detection: YOLOv8-based car detection
  • Occupancy Monitoring: Real-time parking slot status tracking
  • User Authentication: JWT-based authentication for parking owners
  • MongoDB Integration: Persistent storage of parking data
  • Multiple Interfaces: Web UI, REST API, and command-line
  • Multi-tenant Support: Each parking owner has their own account and data
  • Custom Coordinates: Support for flexible parking slot definitions with rectangle format [x1,y1,x2,y2]
  • SVG Visualization: Scalable vector graphics output with color-coded slots (green=empty, red=occupied)
  • Edge Device Support: APIs for both raw image processing and pre-processed data from edge devices

Features

Authentication & User Management

  • User Registration: Create parking owner accounts with organization details
  • Secure Login: JWT token-based authentication
  • Account Management: User profiles with organization information

Data Management

  • Real-time Processing: Process camera frames and detect parking occupancy
  • Edge Processing Support: Accept pre-processed data from edge devices
  • Historical Data: Query past parking data with filtering options
  • Multi-camera Support: Track multiple cameras per parking area
  • Cloud Storage: Automatic image upload to Google Cloud Storage with hierarchical organization (user_id/node_id/date/time)

API Endpoints

  • POST /register - Register new parking owner
  • POST /login - Authenticate and get JWT token
  • POST /updateRaw - Process raw images (React app โ†’ Server โ†’ MongoDB)
  • POST /update - Store pre-processed data (Edge device โ†’ MongoDB)
  • GET /parking-data/<user_id> - Retrieve parking history with filters
  • POST /api/detect - Basic detection (no auth/storage)
  • GET / - Interactive web interface

Project Structure

YoloParklot/
โ”œโ”€โ”€ apis/                      # API route handlers (modular)
โ”‚   โ”œโ”€โ”€ auth_api.py           # Authentication endpoints
โ”‚   โ”œโ”€โ”€ parking_api.py        # Parking detection endpoints
โ”‚   โ””โ”€โ”€ web_api.py            # Web UI endpoints
โ”œโ”€โ”€ auth/                      # Authentication modules
โ”‚   โ”œโ”€โ”€ jwt_handler.py        # JWT token management
โ”‚   โ””โ”€โ”€ password.py           # Password hashing
โ”œโ”€โ”€ config/                    # Configuration
โ”‚   โ””โ”€โ”€ database.py           # MongoDB connection
โ”œโ”€โ”€ middlewares/               # Request middlewares
โ”‚   โ””โ”€โ”€ auth_middleware.py    # JWT authentication
โ”œโ”€โ”€ models/                    # Data models
โ”‚   โ”œโ”€โ”€ user.py               # User account model
โ”‚   โ””โ”€โ”€ parking_data.py       # Parking data model
โ”œโ”€โ”€ templates/                 # HTML templates
โ”‚   โ”œโ”€โ”€ index.html            # Main web interface
โ”‚   โ””โ”€โ”€ testing.html          # API testing dashboard
โ”œโ”€โ”€ utils/                     # Utility modules
โ”‚   โ”œโ”€โ”€ image_utils.py        # Image processing
โ”‚   โ””โ”€โ”€ svg_generator.py      # SVG visualization
โ”œโ”€โ”€ parking_detection/         # Core detection package
โ”‚   โ”œโ”€โ”€ core/                 # Detection, management, visualization
โ”‚   โ”œโ”€โ”€ config/               # System configuration
โ”‚   โ””โ”€โ”€ utils/                # Helper functions
โ”œโ”€โ”€ app.py                    # Main Flask application
โ”œโ”€โ”€ main_app.py               # Command-line interface
โ”œโ”€โ”€ requirements_full.txt     # Full dependencies (with MongoDB/JWT)
โ”œโ”€โ”€ requirements.txt          # Basic dependencies
โ”œโ”€โ”€ .env.example             # Environment configuration template
โ”œโ”€โ”€ API_DOCUMENTATION.md      # Complete API documentation
โ”œโ”€โ”€ EDGE_APP_API_DOCUMENTATION.md  # Edge app integration guide
โ”œโ”€โ”€ EDGE_APP_QUICK_START.md   # Quick start for edge developers
โ”œโ”€โ”€ ARCHITECTURE.md           # System architecture
โ”œโ”€โ”€ TESTING_GUIDE.md          # Testing documentation
โ””โ”€โ”€ runs/detect/carpk_demo/   # YOLOv8 trained model

Documentation

๐Ÿ“š Complete Documentation Set:

Quick Start

1. Install Dependencies

Full installation (with authentication & MongoDB):

pip install -r requirements_full.txt

Basic installation (detection only):

pip install -r requirements.txt

2. Setup MongoDB

Option A: Local MongoDB

sudo apt-get install mongodb
sudo systemctl start mongodb

Option B: MongoDB Docker

docker run -d -p 27017:27017 --name mongodb mongo:latest

Option C: MongoDB Atlas (Cloud) Visit https://www.mongodb.com/cloud/atlas

3. Configure Environment

cp .env.example .env
# Edit .env with your settings

Key settings in .env:

MONGODB_URI=mongodb://localhost:27017/
JWT_SECRET_KEY=change-this-to-secure-random-key
JWT_ACCESS_TOKEN_EXPIRES=3600

4. Run Application

python app.py

Access at: http://localhost:5001/

Setup (Detailed)

Prerequisites

  • Python 3.8 or higher
  • pip package manager

Installation

  1. Clone or navigate to the project directory
cd YoloParklot
  1. Create and activate virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt

Usage

1. Web Interface (Easiest)

Start the Flask server with interactive web UI:

python app.py

Then open your browser to: http://localhost:5001/

Features:

  • Upload parking lot images
  • Define parking slot coordinates in JSON format: [[x1, y1, x2, y2], ...]
  • View real-time detection results with SVG visualization
  • Download SVG and JSON results

2. REST API with Authentication

Complete API Documentation: See API_DOCUMENTATION.md

Quick Start:

import requests
import json

BASE_URL = "http://localhost:5001"

# Register and Login
response = requests.post(f"{BASE_URL}/register", json={
    "username": "parking_owner",
    "password": "secure123",
    "organization_name": "My Parking Lot",
    "location": "123 Main St",
    "size": 100
})
user_id = response.json()['user_id']

response = requests.post(f"{BASE_URL}/login", json={
    "username": "parking_owner",
    "password": "secure123"
})
token = response.json()['access_token']

# Process image and save to MongoDB
headers = {"Authorization": f"Bearer {token}"}
files = {'image': open('parking.jpg', 'rb')}
data = {
    'coordinates': json.dumps([[401, 238, 508, 286], [752, 377, 859, 425]]),
    'camera_id': 'camera_entrance_1'
}
response = requests.post(f"{BASE_URL}/updateRaw", headers=headers, files=files, data=data)
result = response.json()
print(f"Cars Detected: {result['total_cars_detected']}")
print(f"Occupancy: {result['occupancy_rate']}%")

# Get parking data
response = requests.get(f"{BASE_URL}/parking-data/{user_id}?limit=10", headers=headers)
print(f"Total records: {response.json()['total_count']}")

React Edge App Integration:

// Upload frames from React app
const uploadFrame = async (imageBlob, coordinates, cameraId) => {
  const token = localStorage.getItem('token');
  const formData = new FormData();
  formData.append('image', imageBlob);
  formData.append('coordinates', JSON.stringify(coordinates));
  formData.append('camera_id', cameraId);
  
  const response = await fetch('http://localhost:5001/updateRaw', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${token}` },
    body: formData
  });
  
  return response.json();
};

cURL example:

# Register
curl -X POST http://localhost:5001/register \
  -H "Content-Type: application/json" \
  -d '{"username":"test","password":"test123","organization_name":"Test","location":"Test St","size":50}'

# Login
curl -X POST http://localhost:5001/login \
  -H "Content-Type: application/json" \
  -d '{"username":"test","password":"test123"}'

# Process image (use token from login)
curl -X POST http://localhost:5001/updateRaw \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "image=@parking.jpg" \
  -F 'coordinates=[[100,200,207,248],[220,200,327,248]]'

3. Command Line

Process images or videos directly:

# Process image with default coordinates
python main_app.py --mode image --input parking.jpg --output result.jpg

# Process with custom coordinates from JSON file
python main_app.py --mode image --input parking.jpg --coordinates coords.json

# Process video
python main_app.py --mode video --input parking.mp4 --output result.mp4

# Real-time display
python main_app.py --mode realtime --input parking.mp4

4. Python API

from parking_detection import ParkingDetectionSystem

# With custom coordinates
coordinates = [
    [401, 238, 508, 286],
    [752, 377, 859, 425],
    [55, 100, 162, 148]
]

system = ParkingDetectionSystem(parking_positions=coordinates)
system.process_single_image("parking.jpg", "result.jpg")

Coordinate Format

Each parking slot is defined by 4 coordinates representing a rectangle:

[x1, y1, x2, y2]

Where:

  • (x1, y1) = Top-left corner
  • (x2, y2) = Bottom-right corner

Example:

[
  [401, 238, 508, 286],
  [752, 377, 859, 425],
  [55, 100, 162, 148]
]

API Response Format

{
  "success": true,
  "total_slots": 5,
  "total_cars_detected": 29,
  "occupied_slots": 2,
  "empty_slots": 3,
  "occupancy_rate": 40.0,
  "svg_code": "<svg>...</svg>",
  "slots_details": [...],
  "processing_time_ms": 435.2
}

Edge App Integration

For edge device developers, we provide comprehensive documentation:

๐Ÿ“ฑ Edge App Quick Start Guide

  • Get started in 5 minutes
  • Simple code examples
  • Step-by-step integration
  • Testing with cURL

๐Ÿ“š Complete Edge App API Documentation

  • Detailed API specifications
  • Python client library
  • Integration flow diagrams
  • Error handling patterns
  • Best practices

Quick Integration Example

import requests

# 1. Register device (one-time)
requests.post('http://localhost:5001/auth/register', json={
    "username": "edge_device_01",
    "password": "secure_pass",
    "organization_name": "My Parking Lot",
    "location": "123 Main St",
    "size": 50
})

# 2. Login
response = requests.post('http://localhost:5001/auth/login', json={
    "username": "edge_device_01",
    "password": "secure_pass"
})
token = response.json()['access_token']
user_id = response.json()['user_id']

# 3. Send parking updates
requests.post('http://localhost:5001/parking/update',
    headers={"Authorization": f"Bearer {token}"},
    json={
        "user_id": user_id,
        "camera_id": "cam_01",
        "total_slots": 50,
        "occupied_slots": 35,
        "empty_slots": 15,
        "occupancy_rate": 70.0
    }
)

Configuration

Server can be configured via command-line options:

python app.py --host 0.0.0.0 --port 5001 --debug

Options:

  • --host: Host to bind to (default: 0.0.0.0)
  • --port: Port number (default: 5001)
  • --debug: Enable debug mode

Requirements

Main dependencies (see requirements.txt for full list):

  • Flask >= 2.0.0
  • opencv-python >= 4.5.0
  • ultralytics >= 8.0.0
  • numpy >= 1.21.0

Troubleshooting

Server won't start:

# Try a different port
python api_server_svg.py --port 5002

Module not found:

pip install -r requirements.txt

Coordinates not working:

  • Each coordinate must have exactly 4 values: [x1, y1, x2, y2]
  • Ensure x2 > x1 and y2 > y1
  • Coordinates must be within image bounds

License

MIT License

Acknowledgments

  • Ultralytics YOLOv8 for object detection
  • OpenCV for computer vision
  • Flask for web framework

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •