Files
photoassistant/settings.py

147 lines
7.0 KiB
Python

from wtforms import SubmitField, StringField, FloatField, HiddenField, validators, Form, SelectField
from flask_wtf import FlaskForm
from flask import request, render_template, redirect
from main import db, app, ma
from sqlalchemy import Sequence
from sqlalchemy.exc import SQLAlchemyError
from status import st, Status
from flask_login import login_required, current_user
# pylint: disable=no-member
################################################################################
# Class describing AI_MODEL in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class AIModel(db.Model):
__tablename__ = "ai_model"
id = db.Column(db.Integer, primary_key=True )
name = db.Column(db.String)
def __repr__(self):
return f"<id: {self.id}, name: {self.name}>"
################################################################################
# Class describing Settings in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Settings(db.Model):
id = db.Column(db.Integer, db.Sequence('settings_id_seq'), primary_key=True )
base_path = db.Column(db.String)
import_path = db.Column(db.String)
storage_path = db.Column(db.String)
recycle_bin_path = db.Column(db.String)
default_refimg_model = db.Column(db.Integer,db.ForeignKey('ai_model.id'), unique=True, nullable=False)
default_scan_model = db.Column(db.Integer,db.ForeignKey('ai_model.id'), unique=True, nullable=False)
default_threshold = db.Column(db.Integer)
def __repr__(self):
return f"<id: {self.id}, import_path: {self.import_path}, storage_path: {self.storage_path}, recycle_bin_path: {self.recycle_bin_path}, default_refimg_model: {self.default_refimg_model}, default_scan_model: {self.default_scan_model}, default_threshold: {self.default_threshold}>"
################################################################################
# Helper class that inherits a .dump() method to turn class Settings into json / useful in jinja2
################################################################################
class SettingsSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Settings
ordered = True
settings_schema = SettingsSchema(many=True)
################################################################################
# Helper class that defines a form for Settings, used to make html <form>
# with field validation (via wtforms)
################################################################################
class SettingsForm(FlaskForm):
id = HiddenField()
base_path = StringField('Base Path to use below (optional):', [validators.DataRequired()])
import_path = StringField('Path(s) to import from:', [validators.DataRequired()])
storage_path = StringField('Path to store sorted images to:', [validators.DataRequired()])
recycle_bin_path = StringField('Path to temporarily store deleted images in:', [validators.DataRequired()])
default_refimg_model = SelectField( 'default_refimg_model', choices=[(c.id, c.name) for c in AIModel.query.order_by('id')] )
default_scan_model = SelectField( 'default_scan_model', choices=[(c.id, c.name) for c in AIModel.query.order_by('id')] )
default_threshold = StringField('Face Distance threshold (below is a match):', [validators.DataRequired()])
submit = SubmitField('Save' )
################################################################################
# /settings -> show current settings
################################################################################
@app.route("/settings", methods=["GET", "POST"])
@login_required
def settings():
form = SettingsForm(request.form)
page_title='Settings'
if request.method == 'POST' and form.validate():
try:
# HACK, I don't really need an id here, but sqlalchemy get weird
# without one, so just grab the id of the only row there, it will
# do...
id = Settings.query.all()[0].id
s = Settings.query.get(id)
if 'submit' in request.form:
st.SetMessage("Successfully Updated Settings" )
s.import_path = request.form['import_path']
s.storage_path = request.form['storage_path']
s.recycle_bin_path = request.form['recycle_bin_path']
s.default_refimg_model = request.form['default_refimg_model']
s.default_scan_model = request.form['default_scan_model']
s.default_threshold = request.form['default_threshold']
db.session.commit()
return redirect( '/settings' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( "<b>Failed to modify Setting:</b>&nbsp;{}".format(e.orig) )
return render_template("settings.html", form=form, page_title=page_title)
else:
form = SettingsForm( obj=Settings.query.first() )
return render_template("settings.html", form=form, page_title = page_title)
##############################################################################
# SettingsRBPath(): return modified array of paths (take each path in
# recycle_bin_path and add base_path if needed)
##############################################################################
def SettingsRBPath():
settings = Settings.query.first()
if settings == None:
print("Cannot create file data with no settings / recycle bin path is missing")
return
# path setting is an absolute path, just use it, otherwise prepend base_path first
if settings.recycle_bin_path[0] == '/':
path = settings.recycle_bin_path
else:
path = settings.base_path+settings.recycle_bin_path
return path
##############################################################################
# SettingsSPath(): return modified array of paths (take each path in
# storage_path and add base_path if needed)
##############################################################################
def SettingsSPath():
paths=[]
settings = Settings.query.first()
if settings == None:
print("Cannot create file data with no settings / storage path is missing")
return
for p in settings.storage_path.split("#"):
if p[0] == '/':
paths.append(p)
else:
paths.append(settings.base_path+p)
return paths
##############################################################################
# SettingsIPath(): return modified array of paths (take each path in
# import_path and add base_path if needed)
##############################################################################
def SettingsIPath():
paths=[]
settings = Settings.query.first()
if settings == None:
print ("Cannot create file data with no settings / import path is missing")
return
for p in settings.import_path.split("#"):
if p[0] == '/':
paths.append(p)
else:
paths.append(settings.base_path+p)
return paths