Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
GouthamOfTheNP authored Nov 4, 2024
1 parent a7d0bae commit fc3c225
Show file tree
Hide file tree
Showing 5 changed files with 148 additions and 14 deletions.
25 changes: 21 additions & 4 deletions camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
import sendemailpy3 as smpy
from threading import Thread
from datetime import datetime
import requests


SERVER_URL = "http://127.0.0.1:5000/upload_frame"
with open("emails.txt", "r") as file:
receiver_email = [email.strip() for email in file.readlines()]

Expand Down Expand Up @@ -53,8 +56,8 @@ def zip_video_file(video_file):


def send_message(emails):
sender_email = "noreplysmtpimportant@gmail.com"
sender_password = "yqfd dnzf oyqe hvph"
sender_email = os.getenv("USERNAME_SENDER")
sender_password = os.getenv("PASSWORD_SENDER")

subject = "Intruder detected at your camera's location!"
body = "Download the following videos to see what happened at what time."
Expand Down Expand Up @@ -87,6 +90,8 @@ def send_message(emails):
merge_time = image_time * merge_time_multiplier

video = cv2.VideoCapture(0)
if not video.isOpened():
print("Error: Camera not accessible.")
fps = int(video.get(cv2.CAP_PROP_FPS))
frames_per_video = 5 * fps
rectangle = None
Expand Down Expand Up @@ -115,6 +120,18 @@ def send_message(emails):
x, y, w, h = cv2.boundingRect(contour)
rectangle = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3)

_, buffer = cv2.imencode('.jpg', frame)
frame_data = buffer.tobytes()
with open("device_id.txt", "r") as f:
info = f.readlines()
user_id = info[1]
response = requests.post(SERVER_URL, files={'frame': frame_data}, data={'user_id': user_id})
if response.status_code != 200:
print(response)
print(f"Error: Failed to upload frame, status code {response.status_code}")
else:
print("Frame uploaded successfully")

cv2.imshow("Video", frame)
key = cv2.waitKey(1)
images.append(frame)
Expand All @@ -129,13 +146,13 @@ def send_message(emails):
video_files.append(video_name)
images = []

if len(video_files) % 12 == 0 and len(video_files) != 0:
if len(video_files) % 20 == 0 and len(video_files) != 0:
merged_name = os.path.join(save_dir, f"merged_time_stamp_{datetime.now()}.mp4")
merge_videos(video_files, merged_name)
video_files = []
video_records.append(merged_name)

if iterations % 150 == 0:
if iterations % 3600 == 0:
if image_files_detected and len(image_files_detected) != 0:
image_files_video_detected = []
for f in image_files_detected:
Expand Down
51 changes: 51 additions & 0 deletions camera_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from flask import Flask, request, render_template
import cv2
import numpy as np

app = Flask(__name__)
user_frames = {}

@app.route('/')
def index():
return "Home Page", 200

@app.route('/upload_frame', methods=['POST'])
def upload_frame():
user_id = request.form.get('user_id')
print(user_id)
if 'frame' not in request.files:
return "No frame found", 400

# Read the frame from the request
frame = request.files['frame'].read()

# Convert the byte data to a numpy array and decode it to an image
np_frame = np.frombuffer(frame, np.uint8)
image = cv2.imdecode(np_frame, cv2.IMREAD_COLOR)

# Store the latest frame for the user
if user_id:
user_frames[user_id] = image

return "Frame received", 200


@app.route('/stream/<user_id>')
def stream(user_id):
if user_id in user_frames:
print(user_frames)
_, buffer = cv2.imencode('.jpg', user_frames[user_id])
return render_template('server.html', user_id=user_id)
return "User not found", 404


@app.route('/stream_default')
def stream_default():
if user_frames:
first_user_id = next(iter(user_frames))
_, buffer = cv2.imencode('.jpg', user_frames[first_user_id])
return buffer.tobytes(), 200, {'Content-Type': 'image/jpeg'}
return "No frames available", 404

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
15 changes: 15 additions & 0 deletions db_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from flask import Flask, request, jsonify
import sqlite3

app = Flask(__name__)


@app.route('/', methods=['GET'])
def home_page():
return "Home page of user database. Please travel to the specified location to get access."




if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) # Accessible on your local network
4 changes: 2 additions & 2 deletions db_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import bcrypt


def create_table():
def create_users_db():
connection = sqlite3.connect("users.db")
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
with connection:
cursor.execute("CREATE TABLE IF NOT EXISTS users "
"(username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, devices TEXT NOT NULL)")
"(username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, devices TEXT)")
connection.commit()


Expand Down
67 changes: 59 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
from db_functions import add_user, user_exists, create_table, verify_password, verify_email
from flask import render_template, request, Flask, session
from db_functions import add_user, user_exists, create_users_db, verify_password, verify_email, create_devices_db
from flask import render_template, request, Flask, session, redirect, url_for, jsonify
from flask.views import MethodView
from flask_cors import CORS
from wtforms import Form, StringField, IntegerField, BooleanField
from wtforms.fields.simple import SubmitField
from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError
from sendemailpy3 import send_gmail
import os
import sqlite3
import time

app = Flask(__name__)
CORS(app)
app.secret_key = os.urandom(24)
app.config["SESSION_TYPE"] = "memcache"

connection = create_table()
create_users_db()
create_devices_db()


class MainPage(MethodView):
def get(self):
if session.get('logged_in'):
return render_template("index.html", username=session.get('username'))
return render_template("index.html")


class SignUpPage(MethodView):
def get(self):
signup_form = SignupForm()
if session.get("logged_in"):
return redirect(url_for("main_page"))
return render_template("signup.html", signup_form=signup_form)

def post(self):
Expand All @@ -35,6 +43,10 @@ def post(self):
if not user_exists(username):
if password == confirm_password:
add_user(username, password, email)
session['logged_in'] = True
session['username'] = username
time.sleep(2)
return redirect(url_for('main_page'))
else:
error_code = "Passwords do not match"
else:
Expand All @@ -44,6 +56,8 @@ def post(self):

class LoginPage(MethodView):
def get(self):
if session.get("logged_in"):
return redirect(url_for("main_page"))
login_form = LoginForm()
return render_template("login.html", login_form=login_form)

Expand All @@ -52,11 +66,17 @@ def post(self):
username = str(login_form.username.data)
password = str(login_form.password.data)
error_code = "Successfully logged in"
if verify_password(username, password):
session['logged_in'] = True
session['username'] = username
else:
error_code = "Invalid username or password"
try:
try:
if verify_password(username, password):
session['logged_in'] = True
session['username'] = username
time.sleep(2)
return redirect(url_for('main_page'))
except TypeError as e:
error_code = "Invalid username or password"
except TypeError as e:
error_code = "An error occurred while logging in. Please try again."
return render_template("login.html", login_form=login_form, error_code=error_code)


Expand Down Expand Up @@ -85,6 +105,19 @@ def get(self):
return render_template("mobile_app.html")


class LogoutPage(MethodView):
def get(self):
try:
session.pop('logged_in', None)
session.pop('username', None)
time.sleep(1)
return redirect(url_for('main_page'))
except Exception:
return render_template('logout.html')
def post(self):
return redirect(url_for('main_page'))


class SecurityCameraPage(MethodView):
def get(self):
connection = sqlite3.connect("devices.db")
Expand All @@ -100,6 +133,21 @@ def get(self):
return render_template("security_camera.html", data=data)


class PrivacyPage(MethodView):
def get(self):
return render_template("privacy.html")


@app.route('/478cb55db6df5b5b4f9d38e081161edf')
def get_devices():
connection = sqlite3.connect("users.db")
cursor = connection.cursor()
cursor.execute("SELECT username, devices FROM users")
devices = cursor.fetchall()
connection.close()
return jsonify(devices)


class SignupForm(Form):
email = StringField("Email: ", validators=[DataRequired(), Email()])
username = StringField("Username: ", validators=[DataRequired()])
Expand Down Expand Up @@ -129,5 +177,8 @@ class ForgotForm(Form):
app.add_url_rule('/forgot', view_func=ForgotPage.as_view('forgot_page'))
app.add_url_rule('/mobile-app', view_func=MobileAppPage.as_view('mobile_app_page'))
app.add_url_rule('/security-camera', view_func=SecurityCameraPage.as_view('security_camera_page'))
app.add_url_rule('/logout', view_func=LogoutPage.as_view('logout_page'))
app.add_url_rule('/privacy', view_func=PrivacyPage.as_view('privacy_page'))

if __name__ == '__main__':
app.run(debug=True)

0 comments on commit fc3c225

Please sign in to comment.