from flask import Flask, request, render_template, Response, jsonify
import cv2
import numpy as np
from ultralytics import YOLO
from paddleocr import PaddleOCR
from deepsort_tracker import Tracker
import os
from datetime import datetime
from collections import defaultdict
@app.route('/upload_video', methods=['POST'])
def upload_video():
if 'video' not in request.files:
return jsonify({"error": "No video file in request"}), 400
def process_video_stream(file_path):
global latest_license_plate
cap = cv2.VideoCapture(file_path)
temp = 0
temp2 = " "
ret = True
code
Assistant
User
code
Assistant
User
both code are related
Assistant
User
in my above code when i upload a video 2nd time video stream and license writing are stop i want when upload a new video is upload both video stream and license writing continue to work without change previous written lisence plate no.
Assistant
while ret:
ret, frame = cap.read()
if not ret:
break
# Resize the frame to 640x480
frame = cv2.resize(frame, (640, 480))
# Detect vehicles using YOLO
detections = coco_model(frame)[0]
detections_ = []
for detection in detections.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = detection
if int(class_id) in vehicles:
detections_.append([x1, y1, x2, y2, score])
# Update SORT tracker with detections
tracker.update(frame, detections_)
# Detect license plates
license_plates = license_plate_detector(frame)[0]
for license_plate in license_plates.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = license_plate
for track in tracker.tracks:
bbox = track.bbox
cx1, cy1, cx2, cy2 = bbox
track_id = track.track_id
if x1 > cx1 and y1 > cy1 and x2 < cx2 and y2 < cy2:
license_plate_crop = frame[int(y1):int(y2), int(x1):int(x2), :]
license_plate_crop_gray = cv2.cvtColor(license_plate_crop, cv2.COLOR_BGR2GRAY)
if temp != track_id:
result = ocr.ocr(license_plate_crop_gray, cls=True)
if result:
for res in result:
if res:
for line in res:
text = line[1]
text_str = replace_chars(str(text[0]))
if text_str != temp2:
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latest_license_plate = {
"license_plate": text_str,
"timestamp": current_time
}
temp2 = text_str
temp = track_id
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(frame, text_str, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/get_license_plate')
def get_license_plate():
global latest_license_plate
return jsonify(latest_license_plate)
if name == 'main':
if not os.path.exists('uploads'):
os.makedirs('uploads')
app.run(debug=True)
Your Flask application is structured for handling video uploads and processing them to detect license plates using YOLO models and OCR with PaddleOCR. Here are a few improvements and tips:
Imports and Dependencies:
Ensure all required libraries and dependencies are properly installed. This includes Flask, OpenCV (cv2), numpy, ultralytics (for YOLO models), paddleocr, and any custom deepsort tracker library used.
File Uploads:
The upload_video route saves the uploaded video file and triggers processing tasks (video_feed and get_license_plate). Ensure the video file's processing path is handled correctly.
Real-Time Video Processing:
The process_video_stream function handles real-time video processing. This function uses the YOLO object detection model to identify vehicles and license plates, and uses PaddleOCR to read the license plate characters.
Character Replacement:
The replace_chars function improves OCR accuracy by standardizing commonly misread characters.
Tracker Integration:
The Tracker instance from deepsort_tracker needs to be correctly initialized and integrated with detected bounding boxes for multi-object tracking.
HTML and Frontend:
In index.html, ensure you have the right structure to handle live video streams and asynchronous updates from the server.
Here’s the complete code, improved and clarified for readability:
python
from flask import Flask, request, render_template, Response, jsonify
import cv2
import numpy as np
from ultralytics import YOLO
from paddleocr import PaddleOCR
from deepsort_tracker import Tracker
import os
from datetime import datetime
app = Flask(__name__)
# Initialize PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, use_gpu=True, lang='en')
# Load YOLO models
coco_model = YOLO('yolov8m.pt') # Model for general object detection
license_plate_detector = YOLO('bestm.pt') # Model for license plate detection
# Initialize the tracker
tracker = Tracker()
# Define vehicle classes (from COCO dataset)
vehicles = [2, 3, 5, 7]
# Function to replace commonly misread characters
def replace_chars(input_string):
chars_to_replace = ['0', 'o', 'O', 'Q']
replacement_char = 'O'
translation_table = str.maketrans(''.join(chars_to_replace), replacement_char * len(chars_to_replace))
return input_string.translate(translation_table)
latest_license_plate = {"license_plate": "", "timestamp": ""}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload_video', methods=['POST'])
def upload_video():
if 'video' not in request.files:
return jsonify({"error": "No video file in request"}), 400
file = request.files['video']
file_path = os.path.join('uploads', file.filename)
file.save(file_path)
video_feed(file_path) # Start processing the video
return jsonify({"video_path": file_path}), 200
def process_video_stream(file_path):
global latest_license_plate
cap = cv2.VideoCapture(file_path)
temp = 0
temp2 = " "
ret = True
while ret:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (640, 480))
# Detect vehicles in the frame
detections = coco_model(frame)[0]
detections_ = []
for detection in detections.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = detection
if int(class_id) in vehicles:
detections_.append([x1, y1, x2, y2, score])
# Update tracker with current frame detections
tracker.update(frame, detections_)
# Detect license plates in the frame
license_plates = license_plate_detector(frame)[0]
for license_plate in license_plates.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = license_plate
for track in tracker.tracks:
bbox = track.bbox
cx1, cy1, cx2, cy2 = bbox
track_id = track.track_id
if x1 > cx1 and y1 > cy1 and x2 < cx2 and y2 < cy2:
license_plate_crop = frame[int(y1):int(y2), int(x1):int(x2), :]
license_plate_crop_gray = cv2.cvtColor(license_plate_crop, cv2.COLOR_BGR2GRAY)
if temp != track_id:
result = ocr.ocr(license_plate_crop_gray, cls=True)
if result:
for res in result:
if res:
for line in res:
text = line[1]
text_str = replace_chars(str(text[0]))
if text_str != temp2:
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latest_license_plate = {
"license_plate": text_str,
"timestamp": current_time
}
temp2 = text_str
temp = track_id
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(frame, text_str, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/video_feed')
def video_feed():
file_path = request.args.get('file_path')
return Response(process_video_stream(file_path), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/get_license_plate')
def get_license_plate():
global latest_license_plate
return jsonify(latest_license_plate)
if __name__ == '__main__':
if not os.path.exists('uploads'):
os.makedirs('uploads')
app.run(debug=True)
Considerations:
Concurrency: If multiple users upload videos concurrently, you'll need to handle file paths and sessions properly to avoid conflicts.
Error Handling: Add more error handling for edge cases, such as corrupted video files or OCR errors.
Performance: Depending on your server capacity, processing large videos in real-time can be resource-intensive. Consider using a message queue or asynchronous task queue for better scalability.
Deployment: Ensure your code is production-ready (remove debug=True) and consider setting up a web server (like Gunicorn) for deployment.
With these improvements, your Flask application should be more robust and ready for further development and deployment.
const platesUl = document.getElementById('plates');
setInterval(async () => {
const res = await fetch('/get_license_plate');
const plateData = await res.json();
if (plateData.license_plate) {
// Check if the plate already exists
const existingPlates = Array.from(platesUl.getElementsByTagName('li')).map(li => li.textContent.split(' - ')[1]);
if (!existingPlates.includes(plateData.license_plate)) {
const listItem = document.createElement('li');
sl+=1
listItem.textContent = `${sl} - ${plateData.license_plate} - ${plateData.timestamp}`;
platesUl.appendChild(listItem);
}
}
}, 1000); // Poll every second for updates
});
</script>
When you upload a video a second time, the video stream and license plate updating stop because the existing intervals and video streams are not properly managed. To solve this issue, you'll need to reset the interval and update the video stream correctly when a new video is uploaded.
Below is the improved complete HTML and JavaScript code to handle the stop/reset issue properly:
html
<!DOCTYPE html>
<html>
<head>
<title>Video Streaming</title>
<style>
#video-stream {
width: 640px;
height: 480px;
}
#license-plates-list {
margin-left: 20px;
font-size: 18px;
}
#license-plates-list ul {
list-style-type: none;
padding: 0;
}
#license-plates-list li {
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Video Streaming</h1>
<form id="upload-form" action="/upload_video" method="post" enctype="multipart/form-data">
<input type="file" name="video" accept="video/*" required>
<button type="submit">Upload</button>
</form>
<h2>Processed Video</h2>
<div style="display: flex;">
<img id="video-stream" src="" alt="Video stream will appear here">
<div id="license-plates-list">
<h3>License Plates:</h3>
<ul id="plates">
</ul>
</div>
</div>
<script>
let intervalId = null;
let sl = 0;
const form = document.getElementById('upload-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
// Clear previous interval and reset license plates list
if (intervalId) {
clearInterval(intervalId);
}
sl = 0;
const platesUl = document.getElementById('plates');
platesUl.innerHTML = '';
const formData = new FormData(form);
const response = await fetch('/upload_video', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.video_path) {
document.getElementById('video-stream').src = `/video_feed?file_path=${data.video_path}`;
}
// Set new interval for polling the license plate endpoint
intervalId = setInterval(async () => {
const res = await fetch('/get_license_plate');
const plateData = await res.json();
if (plateData.license_plate) {
// Check if the plate already exists
const existingPlates = Array.from(platesUl.getElementsByTagName('li')).map(li => li.textContent.split(' - ')[1]);
if (!existingPlates.includes(plateData.license_plate)) {
const listItem = document.createElement('li');
sl += 1;
listItem.textContent = `${sl} - ${plateData.license_plate} - ${plateData.timestamp}`;
platesUl.appendChild(listItem);
}
}
}, 1000); // Poll every second for updates
});
</script>
</body>
</html>
Explanation:
Interval Management:
When a new video is uploaded, the previous polling interval is cleared using clearInterval(intervalId).
A new interval is then set up for polling the license plate endpoint.
License Plates List Reset:
The license plates list (platesUl) is cleared by setting platesUl.innerHTML = '' to ensure that new entries do not mix with old ones when a new video is uploaded.
Event Listener:
A single event listener (form.addEventListener('submit', ...)) is responsible for handling the video upload form submission, resetting previous states, and handling the stream update interval.
With these improvements, when a new video is uploaded, the previous stream and license plate entries are correctly reset, allowing the new video processing to start without interference.
I understand you are trying to seamlessly integrate the backend Flask code and the frontend HTML/JavaScript code for a video streaming and license plate detection/recognition application. Let's ensure your application correctly handles multiple uploads and streams.
Backend Flask Code
We keep the backend as you provided with the necessary adjustments:
Ensure the file path for the new video is correctly handled.
Within the upload_video endpoint, make the call to video_feed correctly after ensuring the video is saved.
app.py (Flask backend):
python
from flask import Flask, request, render_template, Response, jsonify
import cv2
import numpy as np
from ultralytics import YOLO
from paddleocr import PaddleOCR
from deepsort_tracker import Tracker
import os
from datetime import datetime
app = Flask(__name__)
# Initialize PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, use_gpu=True, lang='en')
# Load YOLO models
coco_model = YOLO('yolov8m.pt') # Model for general object detection
license_plate_detector = YOLO('bestm.pt') # Model for license plate detection
# Initialize the tracker
tracker = Tracker()
# Define vehicle classes (from COCO dataset)
vehicles = [2, 3, 5, 7]
# Function to replace commonly misread characters
def replace_chars(input_string):
chars_to_replace = ['0', 'o', 'O', 'Q']
replacement_char = 'O'
translation_table = str.maketrans(''.join(chars_to_replace), replacement_char * len(chars_to_replace))
return input_string.translate(translation_table)
latest_license_plate = {"license_plate": "", "timestamp": ""}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload_video', methods=['POST'])
def upload_video():
if 'video' not in request.files:
return jsonify({"error": "No video file in request"}), 400
file = request.files['video']
file_path = os.path.join('uploads', file.filename)
file.save(file_path)
return jsonify({"video_path": file_path}), 200
def process_video_stream(file_path):
global latest_license_plate
cap = cv2.VideoCapture(file_path)
temp = 0
temp2 = " "
ret = True
while ret:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (640, 480))
# Detect vehicles in the frame
detections = coco_model(frame)[0]
detections_ = []
for detection in detections.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = detection
if int(class_id) in vehicles:
detections_.append([x1, y1, x2, y2, score])
# Update tracker with current frame detections
tracker.update(frame, detections_)
# Detect license plates in the frame
license_plates = license_plate_detector(frame)[0]
for license_plate in license_plates.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = license_plate
for track in tracker.tracks:
bbox = track.bbox
cx1, cy1, cx2, cy2 = bbox
track_id = track.track_id
if x1 > cx1 and y1 > cy1 and x2 < cx2 and y2 < cy2:
license_plate_crop = frame[int(y1):int(y2), int(x1):int(x2), :]
license_plate_crop_gray = cv2.cvtColor(license_plate_crop, cv2.COLOR_BGR2GRAY)
if temp != track_id:
result = ocr.ocr(license_plate_crop_gray, cls=True)
if result:
for res in result:
if res:
for line in res:
text = line[1]
text_str = replace_chars(str(text[0]))
if text_str != temp2:
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latest_license_plate = {
"license_plate": text_str,
"timestamp": current_time
}
temp2 = text_str
temp = track_id
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(frame, text_str, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/video_feed')
def video_feed():
file_path = request.args.get('file_path')
return Response(process_video_stream(file_path), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/get_license_plate')
def get_license_plate():
global latest_license_plate
return jsonify(latest_license_plate)
if __name__ == '__main__':
if not os.path.exists('uploads'):
os.makedirs('uploads')
app.run(debug=True)
Frontend HTML and JavaScript
The updated frontend code ensures that the correct video stream is displayed and license plate data is updated even when a new video is uploaded:
templates/index.html:
html
<!DOCTYPE html>
<html>
<head>
<title>Video Streaming</title>
<style>
#video-stream {
width: 640px;
height: 480px;
}
#license-plates-list {
margin-left: 20px;
font-size: 18px;
}
#license-plates-list ul {
list-style-type: none;
padding: 0;
}
#license-plates-list li {
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Video Streaming</h1>
<form id="upload-form" action="/upload_video" method="post" enctype="multipart/form-data">
<input type="file" name="video" accept="video/*" required>
<button type="submit">Upload</button>
</form>
<h2>Processed Video</h2>
<div style="display: flex;">
<img id="video-stream" src="" alt="Video stream will appear here">
<div id="license-plates-list">
<h3>License Plates:</h3>
<ul id="plates">
</ul>
</div>
</div>
<script>
let intervalId = null;
let sl = 0;
const form = document.getElementById('upload-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
// Clear previous interval and reset license plates list
if (intervalId) {
clearInterval(intervalId);
}
sl = 0;
const platesUl = document.getElementById('plates');
platesUl.innerHTML = '';
const formData = new FormData(form);
const response = await fetch('/upload_video', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.video_path) {
document.getElementById('video-stream').src = `/video_feed?file_path=${data.video_path}`;
}
// Set new interval for polling the license plate endpoint
intervalId = setInterval(async () => {
const res = await fetch('/get_license_plate');
const plateData = await res.json();
if (plateData.license_plate) {
// Check if the plate already exists
const existingPlates = Array.from(platesUl.getElementsByTagName('li')).map(li => li.textContent.split(' - ')[1]);
if (!existingPlates.includes(plateData.license_plate)) {
const listItem = document.createElement('li');
sl += 1;
listItem.textContent = `${sl} - ${plateData.license_plate} - ${plateData.timestamp}`;
platesUl.appendChild(listItem);
}
}
}, 1000); // Poll every second for updates
});
</script>
</body>
</html>
Summary
Backend: Handles video uploads, processing via YOLO and OCR, and provides endpoints to serve video streams and license plate data.
Frontend: Manages file uploads, displays the video stream, and periodically fetches and displays recognized license plates.
These changes make sure that every time a new video is uploaded:
The current video stream is reset to show the new video.
The license plates list is cleared and fresh data is fetched without errors.
To ensure that the video stream and license plate updates continue to function properly when a new video is uploaded, without clearing the previous license plate list, we need to make a few adjustments in both your backend and frontend code. Specifically:
Ensure that the backend does not reset the license plate data upon a new upload.
Adjust the frontend to handle new video uploads while continuing to fetch and display license plate data.
Backend Flask Code
It is important to ensure that the global state for licence plates is not cleared inadvertently and that subsequent uploads don't interfere with it.
app.py:
python
from flask import Flask, request, render_template, Response, jsonify
import cv2
import numpy as np
from ultralytics import YOLO
from paddleocr import PaddleOCR
from deepsort_tracker import Tracker
import os
from datetime import datetime
app = Flask(__name__)
# Initialize PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, use_gpu=True, lang='en')
# Load YOLO models
coco_model = YOLO('yolov8m.pt') # Model for general object detection
license_plate_detector = YOLO('bestm.pt') # Model for license plate detection
# Initialize the tracker
tracker = Tracker()
# Define vehicle classes (from COCO dataset)
vehicles = [2, 3, 5, 7]
# Function to replace commonly misread characters
def replace_chars(input_string):
chars_to_replace = ['0', 'o', 'O', 'Q']
replacement_char = 'O'
translation_table = str.maketrans(''.join(chars_to_replace), replacement_char * len(chars_to_replace))
return input_string.translate(translation_table)
latest_license_plate = {"license_plate": "", "timestamp": ""}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload_video', methods=['POST'])
def upload_video():
if 'video' not in request.files:
return jsonify({"error": "No video file in request"}), 400
file = request.files['video']
file_path = os.path.join('uploads', file.filename)
file.save(file_path)
return jsonify({"video_path": file_path}), 200
def process_video_stream(file_path):
global latest_license_plate
cap = cv2.VideoCapture(file_path)
temp = 0
temp2 = " "
ret = True
while ret:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (640, 480))
# Detect vehicles in the frame
detections = coco_model(frame)[0]
detections_ = []
for detection in detections.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = detection
if int(class_id) in vehicles:
detections_.append([x1, y1, x2, y2, score])
# Update tracker with current frame detections
tracker.update(frame, detections_)
# Detect license plates in the frame
license_plates = license_plate_detector(frame)[0]
for license_plate in license_plates.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = license_plate
for track in tracker.tracks:
bbox = track.bbox
cx1, cy1, cx2, cy2 = bbox
track_id = track.track_id
if x1 > cx1 and y1 > cy1 and x2 < cx2 and y2 < cy2:
license_plate_crop = frame[int(y1):int(y2), int(x1):int(x2), :]
license_plate_crop_gray = cv2.cvtColor(license_plate_crop, cv2.COLOR_BGR2GRAY)
if temp != track_id:
result = ocr.ocr(license_plate_crop_gray, cls=True)
if result:
for res in result:
if res:
for line in res:
text = line[1]
text_str = replace_chars(str(text[0]))
if text_str != temp2:
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latest_license_plate = {
"license_plate": text_str,
"timestamp": current_time
}
temp2 = text_str
temp = track_id
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(frame, text_str, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
@app.route('/video_feed')
def video_feed():
file_path = request.args.get('file_path')
return Response(process_video_stream(file_path), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/get_license_plate')
def get_license_plate():
global latest_license_plate
return jsonify(latest_license_plate)
if __name__ == '__main__':
if not os.path.exists('uploads'):
os.makedirs('uploads')
app.run(debug=True)
Frontend HTML and JavaScript Code
Adjust the frontend code to handle the new video upload and ensure the interval for fetching license plates data is managed correctly.
templates/index.html:
html
<!DOCTYPE html>
<html>
<head>
<title>Video Streaming</title>
<style>
#video-stream {
width: 640px;
height: 480px;
}
#license-plates-list {
margin-left: 20px;
font-size: 18px;
}
#license-plates-list ul {
list-style-type: none;
padding: 0;
}
#license-plates-list li {
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Video Streaming</h1>
<form id="upload-form" action="/upload_video" method="post" enctype="multipart/form-data">
<input type="file" name="video" accept="video/*" required>
<button type="submit">Upload</button>
</form>
<h2>Processed Video</h2>
<div style="display: flex;">
<img id="video-stream" src="" alt="Video stream will appear here">
<div id="license-plates-list">
<h3>License Plates:</h3>
<ul id="plates">
</ul>
</div>
</div>
<script>
let intervalId = null;
let sl = 0;
const form = document.getElementById('upload-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
// Get reference to the plates UL
const platesUl = document.getElementById('plates');
// FormData for new video
const formData = new FormData(form);
// Send the video file to the server
const response = await fetch('/upload_video', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.video_path) {
document.getElementById('video-stream').src = `/video_feed?file_path=${data.video_path}`;
}
// Clear previous interval if it exists
if (intervalId) {
clearInterval(intervalId);
}
// Set new interval for polling the license plate endpoint
intervalId = setInterval(async () => {
const res = await fetch('/get_license_plate');
const plateData = await res.json();
if (plateData.license_plate) {
// Check if the plate already exists
const existingPlates = Array.from(platesUl.getElementsByTagName('li')).map(li => li.textContent.split(' - ')[1]);
if (!existingPlates.includes(plateData.license_plate)) {
const listItem = document.createElement('li');
sl += 1;
listItem.textContent = `${sl} - ${plateData.license_plate} - ${plateData.timestamp}`;
platesUl.appendChild(listItem);
}
}
}, 1000); // Poll every second for updates
});
</script>
</body>
</html>
Summary of Changes:
Prevent the backend from clearing the license plate data unnecessarily.
On the frontend, handle new video uploads by:
Setting up a new video stream to display the newly uploaded video.
Clearing any existing intervals and setting up a new interval for polling the license plate data.
Continuing to append new license plates to the list without clearing the previously collected data.
These changes will ensure that when a new video is uploaded, the application will display the new video stream while continuing to list both old and new license plate detections without interruption.