22 Commits

Author SHA1 Message Date
0ad49d7962 asdf 2025-04-08 14:38:44 -04:00
64209694e3 sghfsg 2025-04-08 14:07:29 -04:00
d00ceef282 f 2025-04-08 13:25:30 -04:00
72d19bd8b0 asdf 2025-04-08 11:59:53 -04:00
fa71c39780 h 2025-04-08 11:55:30 -04:00
a37918fe11 h 2025-04-08 11:42:42 -04:00
963a59d2d4 f 2025-04-08 11:08:39 -04:00
537d3725d7 j 2025-04-08 10:35:26 -04:00
8c552af606 a 2025-04-08 10:33:46 -04:00
6b900ef16d j 2025-04-08 10:32:34 -04:00
d028ecb842 f 2025-04-08 10:29:26 -04:00
c51c95c42b a 2025-04-08 10:14:15 -04:00
00d737714b asdfasd 2025-04-07 17:54:54 -04:00
d06716ac92 FSGHDFG 2025-04-07 17:53:07 -04:00
a60cfae01c ASDFASDFAS 2025-04-07 17:50:44 -04:00
fe07e61505 asdf 2025-04-07 17:49:19 -04:00
357e47cc73 asdfdasfasd 2025-04-07 17:44:19 -04:00
c242c75b6b b 2025-04-07 17:40:45 -04:00
96ee09c7be k 2025-04-07 17:32:59 -04:00
935344d581 f 2025-04-07 17:29:54 -04:00
2561febca9 f 2025-04-07 17:26:48 -04:00
c53baccb38 d 2025-04-07 17:22:26 -04:00

112
app.py
View File

@ -4,29 +4,44 @@ import threading
import queue import queue
import pdf2image import pdf2image
from brother_ql.conversion import convert from brother_ql.conversion import convert
from brother_ql.backends.helpers import send from brother_ql.backends.helpers import send, status
from brother_ql.raster import BrotherQLRaster from brother_ql.raster import BrotherQLRaster
from PIL import Image from PIL import Image
import mimetypes import mimetypes
import logging import logging
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
import time
app = Flask(__name__) app = Flask(__name__)
printer_busy = False
# Set up logging # Set up logging
log_file = 'log.txt' log_file = 'log.txt'
# Create a rotating file handler for logging
log_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5) # 10MB per log file, keep 5 backups log_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5) # 10MB per log file, keep 5 backups
log_handler.setLevel(logging.INFO) log_handler.setLevel(logging.DEBUG)
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_handler.setFormatter(log_formatter) log_handler.setFormatter(log_formatter)
# Add the log handler to the Flask app's logger
app.logger.addHandler(log_handler) app.logger.addHandler(log_handler)
# Ensure Flask app uses our logger, not its default one
app.logger.setLevel(logging.DEBUG)
# Create a queue to hold the files for processing # Create a queue to hold the files for processing
file_queue = queue.Queue() file_queue = queue.Queue()
image_queue = queue.Queue()
lock = threading.Lock()
# Directory to save uploaded files (you can modify this path) # Directory to save uploaded files (you can modify this path)
UPLOAD_FOLDER = './uploads' UPLOAD_FOLDER = './uploads'
IMAGE_FOLDER = './images'
os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(IMAGE_FOLDER, exist_ok=True)
# Printer configuration # Printer configuration
printer_model = "QL-1100" printer_model = "QL-1100"
@ -34,30 +49,31 @@ backend = 'pyusb'
printer = 'usb://0x04f9:0x20a7' printer = 'usb://0x04f9:0x20a7'
# Convert PDF to image # Convert PDF to image
def convert_pdf_to_image(pdf_path): def convert_pdf_to_images(pdf_path):
"""Converts a PDF to a PIL Image""" """Converts a PDF to a PIL Image"""
try: try:
# Convert PDF to image (get the first page)
images = pdf2image.convert_from_path(pdf_path) images = pdf2image.convert_from_path(pdf_path)
if images: if images:
return images[0] # We will only print the first page for now return images
return None return None
except Exception as e: except Exception as e:
app.logger.error(f"Error converting PDF: {str(e)}") app.logger.error(f"Error converting PDF: {str(e)}")
return None return None
# Function to print address labels # Function to print address labels
def print_address_label(pdf_path): def print_address_label(image, pdf_path):
try: try:
# Convert PDF to image if 'address' in pdf_path.lower():
image = convert_pdf_to_image(pdf_path) target_width = 1660
if not image: target_height = 1164
raise Exception("Failed to create label images") image = image.convert("RGB")
image = image.resize((target_width, target_height), Image.LANCZOS)
target_width = 1164 image = image.rotate(90, expand=True)
target_height = 1660 else:
image = image.convert("RGB") target_width = 1164
image = image.resize((target_width, target_height), Image.LANCZOS) target_height = 1660
image = image.convert("RGB")
image = image.resize((target_width, target_height), Image.LANCZOS)
qlr = BrotherQLRaster(printer_model) qlr = BrotherQLRaster(printer_model)
qlr.exception_on_warning = True qlr.exception_on_warning = True
@ -65,7 +81,7 @@ def print_address_label(pdf_path):
app.logger.info("Converting image to printer instructions...") app.logger.info("Converting image to printer instructions...")
instructions = convert( instructions = convert(
qlr=qlr, qlr=qlr,
images=[image], # Pass as a list with the single image images=[image],
label='102x152', label='102x152',
threshold=70.0, threshold=70.0,
dither=False, dither=False,
@ -77,33 +93,79 @@ def print_address_label(pdf_path):
) )
app.logger.info("Sending to printer...") app.logger.info("Sending to printer...")
send( status = send(
instructions=instructions, instructions=instructions,
printer_identifier=printer, printer_identifier=printer,
backend_identifier=backend, backend_identifier=backend,
blocking=True blocking=True
) )
app.logger.info(f"Printer status: {status}")
app.logger.info("Print job sent successfully") app.logger.info("Print job sent successfully")
except Exception as e: except Exception as e:
app.logger.error(f"Error during printing: {str(e)}") app.logger.error(f"Error during printing: {str(e)}")
def save_images(images, pdf_path):
uuid = str(int(time.time()))
for i, image in enumerate(images):
if 'address' in pdf_path.lower():
image.save(os.path.join(IMAGE_FOLDER, f"address_label_{uuid}_{i}.png"), "PNG")
elif 'packing' in pdf_path.lower():
image.save(os.path.join(IMAGE_FOLDER, f"shipping_label_{uuid}_{i}.png"), "PNG")
else:
image.save(os.path.join(IMAGE_FOLDER, f"unknown_{uuid}_{i}.png"), "PNG")
image_queue.put((image, pdf_path))
# Worker thread that processes files from the queue # Worker thread that processes files from the queue
def process_queue(): def file_worker():
global printer_busy
while True: while True:
# Wait until a file is available in the queue
file_path = file_queue.get() file_path = file_queue.get()
if file_path is None: # Shutdown signal if file_path is None: # Shutdown signal
break break
# Process the file (convert and print) while printer_busy:
time.sleep(1)
app.logger.info(f"Processing file: {file_path}") app.logger.info(f"Processing file: {file_path}")
print_address_label(file_path) images = convert_pdf_to_images(file_path)
# Signal that the task is done if images:
save_images(images, file_path)
else:
app.logger.error(f"Failed to convert PDF to images: {file_path}")
file_queue.task_done() file_queue.task_done()
# Start the worker thread # Printer worker
thread = threading.Thread(target=process_queue, daemon=True) def printer_worker():
thread.start() global printer_busy
while True:
image, path = image_queue.get()
if image is None:
if printer_busy:
time.sleep(10)
printer_busy = False
break
with lock:
printer_busy = True
print_address_label(image, path)
image_queue.task_done()
# Variable to track the printer worker thread
printer_worker_thread = None
# Ensure only one printer worker is created
def start_printer_worker():
global printer_worker_thread
if printer_worker_thread is None or not printer_worker_thread.is_alive():
app.logger.info("Starting printer worker thread.")
printer_worker_thread = threading.Thread(target=printer_worker, daemon=True)
printer_worker_thread.start()
else:
app.logger.info("Printer worker thread already running.")
# Start the file worker thread
threading.Thread(target=file_worker, daemon=True).start()
# Start the printer worker only once
start_printer_worker()
@app.route('/upload', methods=['POST']) @app.route('/upload', methods=['POST'])
def upload_file(): def upload_file():