Skip to content

Commit

Permalink
added detection if photo or video is 360
Browse files Browse the repository at this point in the history
  • Loading branch information
elblogbruno committed Aug 20, 2021
1 parent 9e780fd commit dc6a2c5
Show file tree
Hide file tree
Showing 2,421 changed files with 1,085,101 additions and 245 deletions.
31 changes: 12 additions & 19 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,29 @@
from controller.modules.home.geocode_utils import GeoCodeUtils

from config import UPLOAD_FOLDER
from config import UPLOAD_FOLDER, load_custom_video_folder
from controller import create_app
from flask_sqlalchemy import SQLAlchemy
import db
from controller.models.models import Wanderpi
from controller import socketio
from flask_dropzone import Dropzone
from flask import send_from_directory
from config import STATIC_FOLDER, CUSTOM_STATIC_FOLDER
from config import STATIC_FOLDER
from controller.modules.files.utils import get_file_extension
import os
import json

app = create_app('dev')
droppzone = Dropzone(app)


@app.route("/static/<path:path>")
def static_dir(path):
print(path)
extension = get_file_extension()
if extension == 'css' or extension == 'js' or extension == 'json':
return send_from_directory(STATIC_FOLDER, path)
else:
return send_from_directory(CUSTOM_STATIC_FOLDER, path)


@app.route('/wanderpi/<path:filename>')
def custom_static(filename):
print("Serving this: " + str(filename))
CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER, UPLOAD_FOLDER = load_custom_video_folder()
return send_from_directory(CUSTOM_STATIC_FOLDER, filename)

if __name__ == '__main__':
#app.run(threaded=True, host="0.0.0.0")
db.Base.metadata.create_all(db.engine)

app.run(threaded=True, host="0.0.0.0", ssl_context='adhoc')
# w = threading.Thread(target=ImagesWatcher(UPLOAD_FOLDER).run())

# w.start()
# t.start()
load_custom_video_folder()
app.run(threaded=True, host="0.0.0.0", ssl_context=('/etc/letsencrypt/live/wanderpi.duckdns.org/fullchain.pem', '/etc/letsencrypt/live/wanderpi.duckdns.org/privkey.pem'))
16 changes: 16 additions & 0 deletions cameras.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,22 @@
},
{
"index": 1,
"deviceId": "/dev/video1",
"deviceLabel": "Webcam 1",
"is_mjpg": false,
"is_picamera": false,
"auth_required": false
},
{
"index": 2,
"deviceId": "/dev/video3",
"deviceLabel": "Webcam 2",
"is_mjpg": false,
"is_picamera": false,
"auth_required": false
},
{
"index": 3,
"deviceId": "http://admin:manresa21@192.168.1.61/video.cgi?.mjpg",
"deviceLabel": "Jardin 2",
"is_mjpg": false,
Expand Down
37 changes: 30 additions & 7 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import logging
import os
import json
from datetime import timedelta

UPLOAD_FOLDER = os.getcwd()+'/uploads/'
CUSTOM_STATIC_FOLDER = "D:\wanderpi"+'/controller/static/'
from controller.utils.utils import create_folder
#UPLOAD_FOLDER = os.getcwd()+'/uploads/'
#/mnt/wanderpi/controller/static/wanderpis/ec38b9af-2eaf-41c4-a428-1b2e5a827d67/images
#CUSTOM_STATIC_FOLDER = "/mnt/wanderpi"
STATIC_FOLDER = os.getcwd()+'/controller/static/'
VIDEOS_FOLDER = CUSTOM_STATIC_FOLDER+'wanderpis/'

UPLOAD_FOLDER = None
CUSTOM_STATIC_FOLDER = None
VIDEOS_FOLDER = None

def load_custom_video_folder():
global CUSTOM_STATIC_FOLDER
global VIDEOS_FOLDER
global UPLOAD_FOLDER
print(CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER)

if not CUSTOM_STATIC_FOLDER:
#open cameras.json file and load
with open("./settings.json", "r") as f:
CUSTOM_STATIC_FOLDER = json.load(f)['custom_folder']
VIDEOS_FOLDER = CUSTOM_STATIC_FOLDER+'wanderpis/'
create_folder(VIDEOS_FOLDER)
UPLOAD_FOLDER = CUSTOM_STATIC_FOLDER+'uploads/'
create_folder(UPLOAD_FOLDER)
print("Custom folder from json file")
return CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER, UPLOAD_FOLDER
else:
print("Custom folder already loaded")
return CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER, UPLOAD_FOLDER

class Config:

Expand All @@ -17,12 +41,11 @@ class Config:

DROPZONE_MAX_FILE_SIZE= 1024 # set max size limit to a large number, here is 1024 MB
DROPZONE_TIMEOUT=5 * 60 * 1000 # set upload timeout to a large number, here is 5 minutes
DROPZONE_MAX_FILES=30
DROPZONE_PARALLEL_UPLOADS=3 # set parallel amount
DROPZONE_MAX_FILES=100
DROPZONE_PARALLEL_UPLOADS=4 # set parallel amount
DROPZONE_UPLOAD_MULTIPLE=True # enable upload multiple
#DROPZONE_REDIRECT_VIEW='files.completed' # set redirect view
PERMANENT_SESSION_LIFETIME = timedelta(days=7)
UPLOAD_FOLDER = UPLOAD_FOLDER

class DevelopmentConfig(Config):
DEBUG = True
Expand Down
6 changes: 3 additions & 3 deletions controller/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from config import config_dict, STATIC_FOLDER
from config import config_dict, load_custom_video_folder, STATIC_FOLDER
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO

Expand All @@ -23,9 +23,9 @@ def setup_log(log_level):

def create_app(config_type):
config_class = config_dict[config_type]

CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER, UPLOAD_FOLDER = load_custom_video_folder()
app = Flask(__name__, static_folder=STATIC_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config.from_object(config_class)

Expand Down
14 changes: 12 additions & 2 deletions controller/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
import shutil
import uuid
import random
from datetime import *

def datetime_parser(o):
Expand All @@ -25,6 +26,7 @@ class Wanderpi(db.Base):
travel_id = Column(String(256), nullable=False)
stop_id = Column(String(256), nullable=False)
is_image = Column(Boolean)
is_360 = Column(Boolean)
has_been_edited = Column(Boolean, default=False)

def __repr__(self):
Expand Down Expand Up @@ -231,9 +233,11 @@ class Stop(db.Base):
def __repr__(self):
return f'<Stop {self.id}>'

def delete(self):
def delete(self, path=None):
db.session.query(Stop).filter(Stop.id == self.id).delete()
db.session.commit()
# if path and os.path.exists(path):
# os.path.removedir(path)
return True

def save(self):
Expand All @@ -251,7 +255,13 @@ def get_all_wanderpis(self, filter=None):
else:
return db.session.query(Wanderpi).filter(Wanderpi.stop_id == self.id).all()


def get_random_thumbnail(self):
wanderpis = self.get_all_wanderpis()
if len(wanderpis) > 0:
i = random.randint(0, len(wanderpis)-1)
return wanderpis[i].file_thumbnail_path
else:
return '/static/wanderpi-icon.svg'
@staticmethod
def get_by_id(id):
return db.session.query(Stop).get(id)
Expand Down
138 changes: 79 additions & 59 deletions controller/modules/files/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,34 @@
from dateutil import parser
import re
import exiftool
import io
import os

exif_Executable="./exiftool-exe/exiftool(-k).exe"

exif_executable_raspberry = "exiftool"

STATIC_FOLDER = '/static/wanderpis/'
VIDEO_EXTENSIONS = set(['mp4'])
IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
# Allowed extension you can set your own
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'mp4'])

def is_raspberrypi():
if os.name != 'posix':
return False
chips = ('BCM2708','BCM2709','BCM2711','BCM2835','BCM2836')
try:
with io.open('/proc/cpuinfo', 'r') as cpuinfo:
for line in cpuinfo:
if line.startswith('Hardware'):
_, value = line.strip().split(':', 1)
value = value.strip()
if value in chips:
return True
except Exception:
pass
return False

def get_file_extension(filename):
if '.' in filename:
return filename.rsplit('.', 1)[1].lower()
Expand All @@ -30,65 +48,67 @@ def dms_to_dd(dms):
return float(dd)

def get_image_tags(path_name, filename):
f = open(path_name, 'rb')

tags = exifread.process_file(f, stop_tag='GPS')
std_fmt = '%Y:%m:%d %H:%M:%S'

lat = 0
long = 0
creation_datetime = 0

for tag in tags.keys():
if tag == 'GPS GPSLatitude':
lat = dms_to_dd(tags[tag].values)
elif tag == 'GPS GPSLongitude':
long = dms_to_dd(tags[tag].values)
elif tag == 'EXIF DateTimeOriginal':
creation_datetime = datetime.strptime(tags['EXIF DateTimeOriginal'].values, std_fmt)

if creation_datetime == 0:
match_str = re.search(r'\d{4}-\d{2}-\d{2}', filename)
if match_str:
creation_datetime = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
else:
creation_datetime = datetime.today()
print("Parsed datetime : " + str(creation_datetime))

return lat, long, creation_datetime
try:
ex_path = exif_executable_raspberry if is_raspberrypi() else exif_Executable
with exiftool.ExifTool(executable_=ex_path) as et:
tags = et.get_metadata_batch([path_name])[0]
print(tags)
std_fmt = '%Y:%m:%d %H:%M:%S+%M:%S'
is_360 = 'XMP:ProjectionType' in tags
lat = 0
long = 0
creation_datetime = 0
duration = 0

if 'Composite:GPSLatitude' in tags and 'Composite:GPSLongitude' in tags:
lat = tags['Composite:GPSLatitude']
long = tags['Composite:GPSLongitude']

create_date = str(tags['File:FileCreateDate'])
creation_datetime = parser.parse(create_date)

if creation_datetime == 0:
match_str = re.search(r'\d{4}-\d{2}-\d{2}', filename)
if match_str:
creation_datetime = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
else:
creation_datetime = datetime.today()
print("Parsed datetime : " + str(creation_datetime))

return lat, long, creation_datetime, is_360
except:
return 0, 0, datetime.today(), False

def get_video_tags(path_name, filename):

with exiftool.ExifTool(executable_=exif_Executable) as et:
tags = et.get_metadata_batch([path_name])[0]

std_fmt = '%Y:%m:%d %H:%M:%S+%M:%S'

lat = 0
long = 0
creation_datetime = 0
duration = 0

if 'Composite:GPSLatitude' in tags and 'Composite:GPSLongitude' in tags:
lat = tags['Composite:GPSLatitude']
long = tags['Composite:GPSLongitude']

duration = tags['QuickTime:MediaDuration']
create_date = str(tags['File:FileCreateDate'])
creation_datetime = parser.parse(create_date)

if creation_datetime == 0:
try:
creation_datetime = parser.parse(filename,fuzzy=True)
except:
creation_datetime = datetime.today()

return lat, long, creation_datetime, duration

def create_folder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print('Error: Creating directory. ' + directory)
ex_path = exif_executable_raspberry if is_raspberrypi() else exif_Executable
with exiftool.ExifTool(executable_=ex_path) as et:
tags = et.get_metadata_batch([path_name])[0]
print(tags)
std_fmt = '%Y:%m:%d %H:%M:%S+%M:%S'
is_360 = 'XMP:ProjectionType' in tags
lat = 0
long = 0
creation_datetime = 0
duration = 0

if 'Composite:GPSLatitude' in tags and 'Composite:GPSLongitude' in tags:
lat = tags['Composite:GPSLatitude']
long = tags['Composite:GPSLongitude']

duration = tags['QuickTime:MediaDuration']
create_date = str(tags['File:FileCreateDate'])
creation_datetime = parser.parse(create_date)

if creation_datetime == 0:
match_str = re.search(r'\d{4}-\d{2}-\d{2}', filename)
if match_str:
creation_datetime = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
else:
creation_datetime = datetime.today()
print("Parsed datetime : " + str(creation_datetime))

return lat, long, creation_datetime, duration, is_360
except:
return 0, 0, datetime.today(), 0, False

Loading

0 comments on commit dc6a2c5

Please sign in to comment.