parking_web / app.py
wesam0099's picture
Update app.py
e054bda verified
from flask import Flask, jsonify, request, render_template, send_from_directory
from flask_cors import CORS
import cv2
import pandas as pd
import numpy as np
from ultralytics import YOLO
import os
app = Flask(__name__, static_folder='WEB/static', template_folder='WEB/templates')
@app.route('/')
def home():
return render_template('index.html')
# Load YOLO model
model = YOLO('yolov8s.pt')
# Define multiple locations
locations_data = {
"University of Dubai": {
"video": "video1.MOV",
"rectangle_points": "rectangle_points1.txt"
},
"Saudi Hospital": {
"video": "video1.MOV",
"rectangle_points": "rectangle_points2.txt"
},
"Dubai Mall": {
"video": "video1.MOV",
"rectangle_points": "rectangle_points3.txt"
},
"Burj Al Arab": {
"video": "video1.MOV",
"rectangle_points": "rectangle_points4.txt"
}
}
def load_parking_rectangles(file_path):
rectangles = []
if not os.path.exists(file_path):
return rectangles
with open(file_path, 'r') as file:
current_rectangle = []
for line in file:
if line.startswith("Rectangle"):
if current_rectangle:
rectangles.append(current_rectangle)
current_rectangle = []
else:
try:
x, y = map(int, line.strip().split(','))
current_rectangle.append((x, y))
except ValueError:
continue
if current_rectangle:
rectangles.append(current_rectangle)
return rectangles
@app.route('/')
def index():
return render_template('index.html')
@app.route('/signin')
def signin():
return render_template('signin.html')
@app.route('/locations', methods=['GET'])
def get_locations():
return jsonify({"locations": list(locations_data.keys())})
@app.route('/parking-status', methods=['GET'])
def parking_status():
location = request.args.get('location')
if not location or location not in locations_data:
return jsonify({'error': 'Invalid location'}), 400
video_path = locations_data[location]["video"]
rectangle_path = locations_data[location]["rectangle_points"]
if not os.path.exists(video_path) or not os.path.exists(rectangle_path):
return jsonify({'error': 'Files not found'}), 404
rectangles = load_parking_rectangles(rectangle_path)
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
cap.release()
if not ret:
return jsonify({'error': 'Could not read video frame'}), 500
frame = cv2.resize(frame, (1020, 500))
results = model.predict(frame)
detections = results[0].boxes.data
df = pd.DataFrame(detections).astype("float")
occupied_status = [False] * len(rectangles)
for _, row in df.iterrows():
x1, y1, x2, y2 = int(row[0]), int(row[1]), int(row[2]), int(row[3])
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
for rect_idx, rectangle in enumerate(rectangles):
if len(rectangle) < 2:
continue
top_left, bottom_right = rectangle
if top_left[0] <= cx <= bottom_right[0] and top_left[1] <= cy <= bottom_right[1]:
occupied_status[rect_idx] = True
total_parking = len(rectangles)
available_parking = occupied_status.count(False)
unavailable_parking = total_parking - available_parking
return jsonify({
'location': location,
'available_parking': available_parking,
'unavailable_parking': unavailable_parking,
'total_parking': total_parking
})
@app.route('/static/<path:filename>')
def serve_static(filename):
return send_from_directory('WEB/static', filename)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)