label_printer/app.py
2024-11-28 00:59:36 +01:00

265 lines
7.6 KiB
Python

# SPDX-License-Identifier: GPL-3.0-or-later
from flask import Flask, render_template, request, redirect, url_for, session, send_from_directory
from PIL import Image
from gen_image import gen_image
from config import *
from datetime import *
from print import *
from process_image import *
from file_handler import *
from colorama import Fore, Style
from fonts import fonts
import os
text_image_filename = "text_image.png"
uploaded_image_filename = "uploaded_image.png"
app = Flask(__name__)
app.secret_key = "blahaj"
templates = {
"DNH": {
"text1": {
"string": "Do Not Hack",
"size": 130,
"pos": 0
},
"text2": {
"string": "bottom text",
"size": 50,
"pos": 130
},
"cut": True
},
"Food": {
"text1": {
"string": "Nickname",
"size": 130,
"pos": 0
},
"text2": {
"string": "",
"size": 50,
"pos": 130
},
"cut": True
},
"Remove by": {
"text1": {
"string": "Remove by",
"size": 130,
"pos": 0
},
"text2": {
"string": "",
"size": 50,
"pos": 130
},
"cut": True
}
}
def render_text_template(info=None, info_color=None, scrollDown=None):
return render_template('text.html', filename=session["text image path"], text1=session["text1"], text2=session["text2"], cut=session["cut"], info=info, info_color=info_color, scrollDown=scrollDown, fonts=session["fonts"])
def render_image_template(info=None, info_color=None):
return render_template('image.html', filename=session["uploaded image path"], cut=session["cut"], info=info, info_color=info_color, label_width=label_width)
@app.route('/', methods=['GET', 'POST'])
def base():
check_for_new_user(session)
return render_template('base.html')
# gets triggered when the user_data folder for the user is created
@new_user_handler
def on_new_user(session):
print(Fore.BLUE + "new user with ID:", session["ID"], Style.RESET_ALL)
session["text image path"] = None
session["uploaded image path"] = None
session["cut"] = True
session["text1"] = templates["DNH"]["text1"]
session["text2"] = templates["DNH"]["text2"]
session["cut"] = templates["DNH"]["cut"]
session["fonts"] = fonts()
@app.route('/image', methods=['GET', 'POST'])
def image():
check_for_new_user(session)
if request.method == 'POST':
if 'image' not in request.files:
return redirect(request.url)
file = request.files['image']
if file.filename == '':
return redirect(request.url)
if file:
extension = os.path.splitext(file.filename)[1]
try:
message, status, img = process_image(file.stream)
session["uploaded image path"] = uploaded_image_filename
img.save(get_file_path(session, session["uploaded image path"]))
except Exception as e:
message = f"{e}"
status = "Error"
if status == "Error":
session["uploaded image path"] = None
return render_image_template("Error: " + message, "red")
elif status == "Info":
return render_image_template("Info: " + message, "black")
return render_image_template()
#TODO: maybe merge some stuff with text-print
@app.route('/image-print', methods=['GET', 'POST'])
def image_print():
check_for_new_user(session)
if session["uploaded image path"] == None:
print(Fore.YELLOW + "Warning, file doesn't exist" + Style.RESET_ALL)
return render_template('image.html', filename=session["uploaded image path"], cut=session["cut"])
if request.method == 'POST':
image = format_image_to_label(get_file_path(session, session["uploaded image path"]))
print_image(image)
if 'cut' in request.form:
print("printing and cutting")
cut_paper()
session["cut"] = True;
else:
print("printing")
session["cut"] = False;
return render_image_template()
@app.route('/text-template', methods=['GET', 'POST'])
def text_template():
check_for_new_user(session)
if request.method == 'POST':
template = templates[request.form["template"]]
if request.form["template"] == "Food":
template["text2"]["string"] = datetime.now().strftime('%Y-%m-%d')
if request.form["template"] == "Remove by":
template["text2"]["string"] = (datetime.now() + timedelta(weeks=3)).strftime('%Y-%m-%d')
session["text1"] = template["text1"]
session["text2"] = template["text2"]
session["cut"] = template["cut"]
return render_text_template()
@app.route('/text-form', methods=['GET', 'POST'])
def text_form():
check_for_new_user(session)
if request.method == 'POST':
session["text1"] = {
"string": request.form["string1"],
"size": int(request.form["size1"]),
"pos": int(request.form["pos1"]),
}
session["text2"] = {
"string": request.form["string2"],
"size": int(request.form["size2"]),
"pos": int(request.form["pos2"]),
}
# Clear previously saved font
for font in session["fonts"]:
session["fonts"][font]["selected"] = False
# If an invalid font has been submitted, just default to the first one
chosen_font = request.form["font"]
if chosen_font in session["fonts"]:
session["fonts"][chosen_font]["selected"] = True
else:
first_font = next(iter(session["fonts"]))
session["fonts"][first_font]["selected"] = True
# Select the first font that has been marked as selected
chosen_font = None
for font in session["fonts"]:
f = session["fonts"][font]
if f["selected"]:
chosen_font = f
# If the font is still None, something has gone wrong
if chosen_font is None:
return
message, status, img = gen_image(label_width, session["text1"], session["text2"], chosen_font)
if status == "Error":
session["text image path"] = None
return render_text_template(message, "red")
get_folder_path(session)
session["text image path"] = text_image_filename
img.save(get_file_path(session, session["text image path"]))
print()
print(session["text image path"])
return render_text_template(scrollDown = True)
@app.route('/text', methods=['GET', 'POST'])
def text():
check_for_new_user(session)
return render_text_template()
@app.route('/text-print', methods=['GET', 'POST'])
def text_print():
check_for_new_user(session)
if request.method == 'POST':
if session["text image path"] == None:
print(Fore.YELLOW + "Warning, file doesn't exist" + Style.RESET_ALL)
return render_text_template()
image = format_image_to_label(get_file_path(session, session["text image path"]))
print_image(image)
if 'cut' in request.form:
print("printing and cutting")
cut_paper()
session["cut"] = True;
else:
print("printing")
session["cut"] = False;
return render_text_template()
@app.route('/user_data/<filename>')
def user_data(filename):
return send_from_directory(get_folder_path(session), filename)
if __name__ == "__main__":
app.run(debug=False)