Skip to content

Update #8

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 12 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM python:latest

WORKDIR /service

COPY . .

RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
RUN pip install -r requirements.txt

EXPOSE 8200

CMD ["python", "app.py"]
23 changes: 23 additions & 0 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()

def create_app():
app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret-key-goes-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

db.init_app(app)

# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)

# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)

return app
89 changes: 72 additions & 17 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,91 @@
from flask import Flask, render_template, Response
import cv2
from flask import Flask, Response, render_template
from flask import Flask, Response, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = Flask(__name__)
app = Flask(__name__, static_url_path='')
app.secret_key = 'admin' # Change this to a strong, random key
login_manager = LoginManager()
login_manager.init_app(app)

camera = cv2.VideoCapture('rtsp://freja.hiof.no:1935/rtplive/_definst_/hessdalen03.stream') # use 0 for web camera
# for cctv camera use rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' instead of camera
# for local webcam use cv2.VideoCapture(0)
app.config['LOGIN_DISABLED'] = False # Ensure login functionality is enabled
app.config['LOGIN_VIEW'] = 'login'

def gen_frames(): # generate frame by frame from camera
login_manager = LoginManager()
#Added this line fixed the issue.
login_manager.init_app(app)
login_manager.login_view = 'users.login'

# User class for user authentication (replace with your user database)
class User(UserMixin):
def __init__(self, id):
self.id = id

users = {'giulicrenna@gmail.com': {'password': 'kirchhoff2002'}}

camera = cv2.VideoCapture(0) # Use 0 for default camera, replace with camera URL for IP camera

def generate_frames():
while True:
# Capture frame-by-frame
success, frame = camera.read() # read the camera frame
success, frame = camera.read()
if not success:
break
else:
# Process the frame with OpenCV (e.g., object detection)
# You can add your OpenCV processing code here

# Convert the frame to JPEG format
ret, buffer = cv2.imencode('.jpg', frame)
if not ret:
continue
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # concat frame one by one and show result

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

@app.route('/video_feed')
def video_feed():
#Video streaming route. Put this in the src attribute of an img tag
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

@login_manager.user_loader
def load_user(user_id):
return User(user_id)

@app.route('/')
def root():
if current_user.is_authenticated:
return redirect(url_for('main'))
else:
return redirect(url_for('login'))

@app.route('/main')
@login_required
def index():
"""Video streaming home page."""
return render_template('index.html')

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

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']

if username in users and users[username]['password'] == password:
user = User(username)
login_user(user)
flash('Logged in successfully.', 'success')
return redirect(url_for('index'))
else:
flash('Login failed. Check your username and password.', 'danger')

return render_template('login.html')

@app.route('/logout')
@login_required # Require authentication to log out
def logout():
logout_user()
flash('Logged out successfully.', 'success')
return redirect(url_for('login'))

if __name__ == '__main__':
app.run(debug=True)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8200, debug=False)
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Flask
flask-login
opencv-python
5 changes: 5 additions & 0 deletions static/pico.min.css

Large diffs are not rendered by default.

67 changes: 55 additions & 12 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -1,24 +1,67 @@
<!doctype html>
<html lang="en">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="pico.min.css" rel="stylesheet" />
<style>
h1{
margin-top: 0%;
margin-bottom: 0%;
text-align: center;
}
h3{
margin-top: 0%;
text-align: center;
}
img{
border-style: groove;
border-radius: 2%;
border-color: cornflowerblue;
margin-bottom: 10%;
}
a{
margin-top: 3%;
margin-bottom: 0%;
align-content: end;
}
</style>

<title>Live Streaming Demonstration</title>
<title>Live Streaming</title>
</head>

<body>
<div class="container">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h3 class="mt-5">Live Streaming</h3>
<img src="{{ url_for('video_feed') }}" width="100%">
</div>
<main class="container" data-theme="dark" style="padding: 0%;">
<div style="display: flex; justify-content: end;">
<a role="button" href="/logout">Logout</a>
</div>
</div>

<h1 class="header">CAMARA</h3>
<h3 id="current-datetime" class="header"> {{ current_datetime }} </h3>
<p>Bienvenido Giuliano!</p>
<div class="grid">
<img id="video_feed" src="{{ url_for('video_feed') }}" alt="Surveillance Feed" width="100%">
</div>

</main>
</body>
</html>

</html>

<script>
function updateCurrentDatetime() {
const currentDatetimeElement = document.getElementById('current-datetime');
const currentDatetime = new Date();

const formattedDatetime = currentDatetime.toLocaleString();

currentDatetimeElement.textContent = formattedDatetime;
}

// Update the datetime initially and then every second
updateCurrentDatetime();
setInterval(updateCurrentDatetime, 1000);
</script>
46 changes: 46 additions & 0 deletions templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link href="pico.min.css" rel="stylesheet" />
<style>
h2{
margin-top: 5%;
text-align: center;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<h2 class="text-center mb-4">Login</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="list-unstyled">
{% for message in messages %}
<li class="alert alert-{{ message.category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="POST">
<article>
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password" required>
</div>
<button type="submit" class="btn btn-primary btn-block">Login</button>
</article>
</form>
</div>
</div>
</div>
</body>
</html>