Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS Updated #12706

Open
wants to merge 61 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
744f7c1
CORS Updated
atif275 Feb 4, 2024
a27d403
Auto-format by https://ultralytics.com/actions
UltralyticsAssistant Feb 4, 2024
01cf546
Merge branch 'master' into main
glenn-jocher Apr 9, 2024
e7e35ac
Merge branch 'master' into main
UltralyticsAssistant Apr 14, 2024
520827e
Merge branch 'master' into main
UltralyticsAssistant Apr 18, 2024
39c85c2
Merge branch 'master' into main
UltralyticsAssistant Apr 27, 2024
a3a30cc
Merge branch 'master' into main
UltralyticsAssistant Apr 28, 2024
3217828
Auto-format by https://ultralytics.com/actions
UltralyticsAssistant Apr 28, 2024
32b97fb
Merge branch 'master' into main
UltralyticsAssistant May 5, 2024
4389c32
Merge branch 'master' into main
UltralyticsAssistant May 12, 2024
d62f20a
Merge branch 'master' into main
UltralyticsAssistant May 12, 2024
cd24383
Merge branch 'master' into main
UltralyticsAssistant May 12, 2024
833bc99
Merge branch 'master' into main
UltralyticsAssistant May 12, 2024
a5c0adc
Merge branch 'master' into main
UltralyticsAssistant May 13, 2024
47c2a32
Merge branch 'master' into main
UltralyticsAssistant May 18, 2024
86c73c7
Merge branch 'master' into main
UltralyticsAssistant May 24, 2024
1874509
Merge branch 'master' into main
UltralyticsAssistant May 28, 2024
2197a01
Merge branch 'master' into main
UltralyticsAssistant May 29, 2024
db615d2
Merge branch 'master' into main
UltralyticsAssistant May 29, 2024
f70d821
Merge branch 'master' into main
UltralyticsAssistant May 30, 2024
acd1d9b
Merge branch 'master' into main
UltralyticsAssistant Jun 8, 2024
e248f0d
Merge branch 'master' into main
UltralyticsAssistant Jun 8, 2024
f153b85
Merge branch 'master' into main
UltralyticsAssistant Jun 9, 2024
f575622
Merge branch 'master' into main
UltralyticsAssistant Jun 16, 2024
c58b0ce
Auto-format by https://ultralytics.com/actions
UltralyticsAssistant Jun 16, 2024
f9644a5
Merge branch 'master' into main
UltralyticsAssistant Jun 16, 2024
e38fdb6
Merge branch 'master' into main
UltralyticsAssistant Jun 17, 2024
2961f7b
Merge branch 'master' into main
UltralyticsAssistant Jun 19, 2024
f92bd0b
Merge branch 'master' into main
UltralyticsAssistant Jun 19, 2024
9095bd7
Merge branch 'master' into main
UltralyticsAssistant Jun 20, 2024
7578fbd
Merge branch 'master' into main
UltralyticsAssistant Jun 20, 2024
0583016
Merge branch 'master' into main
UltralyticsAssistant Jun 20, 2024
c7e7d16
Merge branch 'master' into main
UltralyticsAssistant Jun 20, 2024
584fedc
Merge branch 'master' into main
UltralyticsAssistant Jun 22, 2024
cf5e13a
Merge branch 'master' into main
UltralyticsAssistant Jun 30, 2024
81d8094
Merge branch 'master' into main
UltralyticsAssistant Jun 30, 2024
6b60506
Merge branch 'master' into main
UltralyticsAssistant Jun 30, 2024
72ae6ba
Merge branch 'master' into main
UltralyticsAssistant Jul 5, 2024
7be120f
Merge branch 'master' into main
UltralyticsAssistant Jul 8, 2024
d1b999f
Merge branch 'master' into main
UltralyticsAssistant Jul 8, 2024
93a2467
Merge branch 'master' into main
UltralyticsAssistant Jul 8, 2024
3801c75
Merge branch 'master' into main
UltralyticsAssistant Jul 10, 2024
342fe6b
Merge branch 'master' into main
UltralyticsAssistant Jul 13, 2024
9d4505c
Merge branch 'master' into main
UltralyticsAssistant Jul 15, 2024
f267b09
Merge branch 'master' into main
UltralyticsAssistant Jul 15, 2024
60d8152
Merge branch 'master' into main
UltralyticsAssistant Jul 17, 2024
0bebd35
Merge branch 'master' into main
UltralyticsAssistant Jul 17, 2024
b52ede3
Merge branch 'master' into main
UltralyticsAssistant Jul 22, 2024
7705e8e
Merge branch 'master' into main
UltralyticsAssistant Jul 23, 2024
007477d
Merge branch 'master' into main
UltralyticsAssistant Jul 25, 2024
496cd25
Merge branch 'master' into main
UltralyticsAssistant Jul 29, 2024
69f8c6f
Merge branch 'master' into main
UltralyticsAssistant Jul 29, 2024
d2709a0
Merge branch 'master' into main
UltralyticsAssistant Aug 11, 2024
4b01e99
Auto-format by https://ultralytics.com/actions
UltralyticsAssistant Aug 11, 2024
dd2242a
Merge branch 'master' into main
UltralyticsAssistant Aug 14, 2024
7902d68
Merge branch 'master' into main
UltralyticsAssistant Aug 14, 2024
942e855
Merge branch 'master' into main
UltralyticsAssistant Aug 19, 2024
fdeb385
Merge branch 'master' into main
UltralyticsAssistant Aug 20, 2024
fc4942e
Merge branch 'master' into main
UltralyticsAssistant Aug 20, 2024
72f7a2f
Merge branch 'master' into main
UltralyticsAssistant Aug 24, 2024
893e941
Auto-format by https://ultralytics.com/actions
UltralyticsAssistant Aug 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
from flask import Flask, render_template, Response, jsonify
from flask import Flask, render_template, send_from_directory
import cv2
import os
import numpy as np
from datetime import datetime
import time
from flask import jsonify
import subprocess

# from flask_wtf import FlaskForm
# from wtforms import FileField, SubmitField
# from werkzeug.utils import secure_filename
# import os
# from wtforms.validators import InputRequired


app = Flask(__name__)

streaming_active = False
output_folder = "videos"
video_writer = None
# class UploadFileForm(FlaskForm):
# file = FileField("File", validators=[InputRequired()])
# submit = SubmitField("Upload File")


@app.route("/")
def index():
return render_template("index.html")


# @app.route('/home', methods=['GET',"POST"])
# def home():
# form = UploadFileForm()
# if form.validate_on_submit():
# file = form.file.data # First grab the file
# file.save(os.path.join(os.path.abspath(os.path.dirname(__file__)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) # Then save the file
# return "File has been uploaded."
# return render_template('index.html', form=form)


@app.route("/start_stream")
def start_stream():
global streaming_active
global out
if not streaming_active:
streaming_active = True
start_recording()

return jsonify({"status": "success", "message": "Streaming started and recording initiated"})
else:
return jsonify({"status": "error", "message": "Streaming is already active"})


@app.route("/stop_stream")
def stop_stream():
global streaming_active
if streaming_active:
streaming_active = False
stop_recording()

return jsonify({"status": "success", "message": "Streaming stopped and recording saved"})
else:
return jsonify({"status": "error", "message": "Streaming is not active"})


def start_recording():
global video_writer

filename = f"recording_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
fourcc = cv2.VideoWriter_fourcc(*"mp4v") # You can change the codec as needed
frame_size = (640, 480) # Adjust the frame size as needed
# video_writer = cv2.VideoWriter(filename, fourcc, 10.0, frame_size)
video_writer = cv2.VideoWriter(os.path.join(output_folder, filename), fourcc, 40.0, frame_size)


def stop_recording():
global video_writer

if video_writer is not None:
video_writer.release()
video_writer = None


@app.route("/video_feed")
def video_feed():
return Response(generate_frames(), mimetype="multipart/x-mixed-replace; boundary=frame")


@app.route("/static/<path:filename>")
def static_files(filename):
return send_from_directory("static", filename)


@app.route("/videos")
def list_videos():
videos = [video for video in os.listdir("videos") if video.endswith(".mp4")]
return jsonify(videos)


@app.route("/video/<filename>")
def stream_video(filename):
return send_from_directory("videos", filename)


@app.route("/detection/<filename>")
# def detection(filename):
# # Placeholder for detection logic
# print(f"Detection started for {filename}")
# return jsonify({'status': 'Detection started for ' + filename})
def detection(filename):
try:
print(f"filename################={filename}")
# Construct the command string
command = f"python3 detect.py --source ./videos/{filename}"

# Execute the command
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

if process.returncode != 0:
# Handle errors if the command failed
return jsonify({"status": "Error", "message": stderr.decode()}), 500

# Return success response
return jsonify({"status": "Detection Done for " + filename})
except Exception as e:
# Handle any exceptions
return jsonify({"status": "Error", "message": str(e)}), 500


def generate_frames():
global video_writer
folder_path = "/tmp/camera_save_tutorial"
while streaming_active:
image_files = [f for f in os.listdir(folder_path) if f.endswith((".jpg", ".png"))]
if image_files:
try:
latest_image = max(image_files, key=lambda x: os.path.getctime(os.path.join(folder_path, x)))
image_path = os.path.join(folder_path, latest_image)

frame = cv2.imread(image_path)
if frame is None:
raise FileNotFoundError("Empty image file or format not supported")

_, buffer = cv2.imencode(".jpg", frame)
frame = buffer.tobytes()

# Write the frame to the video file if recording is active
if video_writer is not None:
video_writer.write(cv2.imdecode(np.frombuffer(frame, dtype=np.uint8), 1))

yield (b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n")
# time.sleep(0.05)

except Exception as e:
print(f"Error processing image: {e}")
continue

else:
yield (b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + b"\r\n")


if __name__ == "__main__":
app.run(debug=True)
8 changes: 4 additions & 4 deletions detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
@smart_inference_mode()
def run(
weights=ROOT / "yolov5s.pt", # model path or triton URL
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
source=ROOT / "videos", # file/dir/URL/glob/screen/0(webcam)
data=ROOT / "data/coco128.yaml", # dataset.yaml path
imgsz=(640, 640), # inference size (height, width)
conf_thres=0.25, # confidence threshold
Expand Down Expand Up @@ -107,9 +107,9 @@ def run(
source = check_file(source) # download

# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir

# save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
# (save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
save_dir = Path(project)
# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
Expand Down
85 changes: 85 additions & 0 deletions static/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
function startStream() {

fetch('/start_stream')
.then(response => response.json())
.then(data => {
console.log('Start Stream:', data);
document.getElementById('videoStream').src = '/video_feed';
});
}

function stopStream() {

fetch('/stop_stream')
.then(response => response.json())
.then(data => {
console.log('Stop Stream:', data);
document.getElementById('videoStream').src = '';
});
}


document.addEventListener('DOMContentLoaded', function() {
const videoDropdown = document.getElementById('videoDropdown');
//const playButton = document.getElementById('playButton');
// const detectionButton = document.getElementById('detectionButton');
const videoPlayer = document.getElementById('videoPlayer');
detectionButton= document.querySelector(".detectionButton");
playButton= document.querySelector(".playButton");



fetch('/videos').then(response => response.json()).then(videos => {
videos.forEach(video => {
let option = document.createElement('option');
option.value = video;
option.textContent = video;
videoDropdown.appendChild(option);
});
});

videoDropdown.onchange = function() {
if (this.value) {
playButton.style.display = 'block';
detectionButton.style.display='block'

} else {
playButton.style.display = 'none';
detectionButton.style.display = 'none';
}
};

playButton.onclick = function() {

videoPlayer.innerHTML = `<video id = vi src="/video/${videoDropdown.value}" controls></video>`;
// function playVideo(videoSource) {
// var videoPlayer = document.getElementById("videoPlayer");
// videoPlayer.src = videoSource;
// videoPlayer.load();
// videoPlayer.play();
// toggleDropdown(); // Close the dropdown after selecting a video
// }
// playVideo(`/videos/${videoDropdown.value}`);

};

detectionButton.onclick = function() {

this.innerHTML="<div class= 'loader'></div>"
// setTimeout(()=>{
// this.innerHTML="Detection Done";
// this.style="background : #f1f5f4; color: #333; pointer-events: none";
// },2000)

fetch(`/detection/${videoDropdown.value}`).then(response => response.json()).then(data => {
this.innerHTML="Detection Done";
this.style="background : #f1f5f4; color: #333; pointer-events: none";
alert(data.status);
})
.catch(error => {

loadingMessage.style.display = 'none';
console.error('Error:', error);
});
};
});
Loading