From 744f7c172b725871a95eb05bdbaa797a33ea58f4 Mon Sep 17 00:00:00 2001 From: atif275 Date: Sun, 4 Feb 2024 22:45:22 +0500 Subject: [PATCH 1/4] CORS Updated --- app.py | 166 +++++++++++++++++++++++++++++++++++++++++++ detect.py | 8 +-- static/script.js | 85 ++++++++++++++++++++++ static/style.css | 144 +++++++++++++++++++++++++++++++++++++ templates/index.html | 41 +++++++++++ 5 files changed, 440 insertions(+), 4 deletions(-) create mode 100644 app.py create mode 100644 static/script.js create mode 100644 static/style.css create mode 100644 templates/index.html diff --git a/app.py b/app.py new file mode 100644 index 000000000000..5f7465beeab4 --- /dev/null +++ b/app.py @@ -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/') +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/') +def stream_video(filename): + return send_from_directory('videos', filename) + +@app.route('/detection/') +# 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) \ No newline at end of file diff --git a/detect.py b/detect.py index b7d77ef431d4..8cf467ef3b1d 100644 --- a/detect.py +++ b/detect.py @@ -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 @@ -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) diff --git a/static/script.js b/static/script.js new file mode 100644 index 000000000000..0228d74262f3 --- /dev/null +++ b/static/script.js @@ -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 = ``; + // 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="
" + // 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); + }); + }; +}); diff --git a/static/style.css b/static/style.css new file mode 100644 index 000000000000..a93c4ba60166 --- /dev/null +++ b/static/style.css @@ -0,0 +1,144 @@ +body { + margin: 1; + display: flex; + justify-content: right; + align-items: center; + height: 60vh; + background-color: #ffffff; +} + +img { + width: 30%; + height: auto; +} + +.app-header { + background-color: rgb(255, 255, 255); /* Change the background color as needed */ + color: rgb(0, 0, 0); /* Change the text color as needed */ + text-align: center; + padding: 20px; + position: absolute; + top: 20px; /* Adjust the distance from the top */ + left: 50%; /* Center horizontally */ + transform: translateX(-50%); /* Center horizontally */ + } + + .app-header h1 { + margin: 0; + font-size: 2em; /* Adjust the font size as needed */ + } + + .button-container { + text-align: center; + margin-bottom: 20px; + position: absolute; + top: 150px; /* Adjust the distance from the top */ + left: 50%; /* Center horizontally */ + transform: translateX(-50%); /* Center horizontally */ +} + +#startButton { + background-color: #4CAF50; /* Green color */ + color: white; + padding: 10px 20px; /* Adjust padding as needed */ + border: none; + text-align: center; + text-decoration: none; + display: inline-block; + font-size: 16px; + margin: 4px 2px; + cursor: pointer; +} + +#stopButton { + background-color: #FF0000; /* Red color */ + color: white; + padding: 10px 20px; /* Adjust padding as needed */ + border: none; + + text-align: center; + text-decoration: none; + display: inline-block; + font-size: 16px; + margin: 4px 2px; + cursor: pointer; +} +#videoDropdown{ + width: 10%; + padding: 10px; + font-size: 16px; + border: 1px solid #ccc; + border-radius: 4px; + cursor: pointer; + position: absolute; + top: 225px; /* Adjust the distance from the top */ + left: 50%; /* Center horizontally */ + transform: translateX(-50%); /* Center horizontally */ +} + +.button-active { + background-color: #4CAF50; /* Green */ + color: white; + + /* Add more styles as needed, such as positioning */ +} + +.button-inactive { + background-color: #ccc; /* Gray */ + color: #666; + /* Add more styles as needed */ +} + +.playButton{ + background-color: #29ca8c; /* Green color */ + color: white; + width: 100px; + height: 50px; + cursor: pointer; + border-radius: 3px; + display: grid; + place-content: center; + position: absolute; + top: 285px; /* Adjust the distance from the top */ + left: 46%; /* Center horizontally */ + transform: translateX(-50%); /* Center horizontally */ +} + +.detectionButton{ + background-color: #0004ff; /* Green color */ + color: white; + width: 100px; + height: 50px; + cursor: pointer; + border-radius: 3px; + display: grid; + place-content: center; + position: absolute; + top: 285px; /* Adjust the distance from the top */ + left: 54%; /* Center horizontally */ + transform: translateX(-50%); /* Center horizontally */ + +} +.loader { + pointer-events: none; + width: 30px; + height: 30px; + border-radius: 50%; + border: 3px solid transparent; /* Light grey */ + border-top-color: #ffffff; /* Blue */ + animation: an1 1s ease infinite; +} + +@keyframes an1 { + 0% { transform: rotate(0turn); } + 100% { transform: rotate(1turn); } +} + +#vi { + position: relative; + top: 150px; /* Adjust the distance from the top */ + left: -10%; /* Center horizontally */ + transform: translateX(-50%); /* Center horizontally */ + width: 40%; + height: auto; +} \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 000000000000..cb9d891b6f44 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,41 @@ + + + + + + + + Echlon Object Detection + + +
+

Echelon Object Detection and Streaming

+
+ +
+ + +
+ + + + + + +
+ + + Video Stream + + + + + + + \ No newline at end of file From a27d403461b8cfac79a547bfbc7ba257d26b174c Mon Sep 17 00:00:00 2001 From: UltralyticsAssistant Date: Sun, 4 Feb 2024 17:49:03 +0000 Subject: [PATCH 2/4] Auto-format by https://ultralytics.com/actions --- app.py | 86 +++++++++++++++++++++++++++---------------------------- detect.py | 2 +- 2 files changed, 44 insertions(+), 44 deletions(-) diff --git a/app.py b/app.py index 5f7465beeab4..dd89d56a1714 100644 --- a/app.py +++ b/app.py @@ -15,19 +15,20 @@ # from wtforms.validators import InputRequired - app = Flask(__name__) streaming_active = False -output_folder = 'videos' +output_folder = "videos" video_writer = None # class UploadFileForm(FlaskForm): # file = FileField("File", validators=[InputRequired()]) # submit = SubmitField("Upload File") -@app.route('/') + +@app.route("/") def index(): - return render_template('index.html') + return render_template("index.html") + # @app.route('/home', methods=['GET',"POST"]) # def home(): @@ -38,8 +39,8 @@ def index(): # return "File has been uploaded." # return render_template('index.html', form=form) -@app.route('/start_stream') +@app.route("/start_stream") def start_stream(): global streaming_active global out @@ -47,58 +48,63 @@ def start_stream(): streaming_active = True start_recording() - return jsonify({'status': 'success', 'message': 'Streaming started and recording initiated'}) + return jsonify({"status": "success", "message": "Streaming started and recording initiated"}) else: - return jsonify({'status': 'error', 'message': 'Streaming is already active'}) + return jsonify({"status": "error", "message": "Streaming is already active"}) -@app.route('/stop_stream') + +@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'}) + + return jsonify({"status": "success", "message": "Streaming stopped and recording saved"}) else: - return jsonify({'status': 'error', 'message': 'Streaming is not active'}) + 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 + 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') + + +@app.route("/video_feed") def video_feed(): - return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') + return Response(generate_frames(), mimetype="multipart/x-mixed-replace; boundary=frame") -@app.route('/static/') + +@app.route("/static/") def static_files(filename): - return send_from_directory('static', filename) + return send_from_directory("static", filename) + -@app.route('/videos') +@app.route("/videos") def list_videos(): - videos = [video for video in os.listdir('videos') if video.endswith('.mp4')] + videos = [video for video in os.listdir("videos") if video.endswith(".mp4")] return jsonify(videos) -@app.route('/video/') + +@app.route("/video/") def stream_video(filename): - return send_from_directory('videos', filename) + return send_from_directory("videos", filename) + -@app.route('/detection/') +@app.route("/detection/") # def detection(filename): # # Placeholder for detection logic # print(f"Detection started for {filename}") @@ -107,7 +113,7 @@ def detection(filename): try: print(f"filename################={filename}") # Construct the command string - command = f'python3 detect.py --source ./videos/{filename}' + command = f"python3 detect.py --source ./videos/{filename}" # Execute the command process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -115,19 +121,20 @@ def detection(filename): if process.returncode != 0: # Handle errors if the command failed - return jsonify({'status': 'Error', 'message': stderr.decode()}), 500 + return jsonify({"status": "Error", "message": stderr.decode()}), 500 # Return success response - return jsonify({'status': 'Detection Done for ' + filename}) + return jsonify({"status": "Detection Done for " + filename}) except Exception as e: # Handle any exceptions - return jsonify({'status': 'Error', 'message': str(e)}), 500 + return jsonify({"status": "Error", "message": str(e)}), 500 + def generate_frames(): global video_writer - folder_path = '/tmp/camera_save_tutorial' + folder_path = "/tmp/camera_save_tutorial" while streaming_active: - image_files = [f for f in os.listdir(folder_path) if f.endswith(('.jpg', '.png'))] + 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))) @@ -137,15 +144,14 @@ def generate_frames(): if frame is None: raise FileNotFoundError("Empty image file or format not supported") - _, buffer = cv2.imencode('.jpg', frame) + _, 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') + 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: @@ -153,14 +159,8 @@ def generate_frames(): continue else: - yield (b'--frame\r\n' - b'Content-Type: image/jpeg\r\n\r\n' + b'\r\n') - - - + yield (b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + b"\r\n") -if __name__ == '__main__': - - - app.run(debug=True) \ No newline at end of file +if __name__ == "__main__": + app.run(debug=True) diff --git a/detect.py b/detect.py index 8cf467ef3b1d..aacb875ccd84 100644 --- a/detect.py +++ b/detect.py @@ -109,7 +109,7 @@ def run( # 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=Path(project) + save_dir = Path(project) # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) From 3217828de895cacb07f78e926d3a508daf92b8eb Mon Sep 17 00:00:00 2001 From: UltralyticsAssistant Date: Sun, 28 Apr 2024 15:19:42 +0000 Subject: [PATCH 3/4] Auto-format by https://ultralytics.com/actions --- app.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/app.py b/app.py index dd89d56a1714..0c0c0a3a4ab4 100644 --- a/app.py +++ b/app.py @@ -1,12 +1,11 @@ -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 +import time +from datetime import datetime + +import cv2 +import numpy as np +from flask import Flask, Response, jsonify, render_template, send_from_directory # from flask_wtf import FlaskForm # from wtforms import FileField, SubmitField From c58b0cea7ef2675ecb0b25d6ede73cfa260b3e32 Mon Sep 17 00:00:00 2001 From: UltralyticsAssistant Date: Sun, 16 Jun 2024 20:09:49 +0000 Subject: [PATCH 4/4] Auto-format by https://ultralytics.com/actions --- app.py | 1 - 1 file changed, 1 deletion(-) diff --git a/app.py b/app.py index 0c0c0a3a4ab4..3d6bf54d406d 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,5 @@ import os import subprocess -import time from datetime import datetime import cv2