Update linting with black

This commit is contained in:
n07070
2026-05-17 14:24:07 +02:00
parent 641b8a2d1f
commit 85c10a47b0
4 changed files with 214 additions and 117 deletions

View File

@@ -34,31 +34,33 @@ class Printer(object):
self.device_id = device_id
self.vendor_id = vendor_id
self.usb_args = {}
self.usb_args['idVendor'] = self.device_id
self.usb_args['idProduct'] = self.vendor_id
self.usb_args["idVendor"] = self.device_id
self.usb_args["idProduct"] = self.vendor_id
def check_paper(self) -> bool:
# Let's check paper status
self.app.logger.debug('Checking paper status...')
self.app.logger.debug("Checking paper status...")
self.printer.open(self.usb_args)
status = self.printer.paper_status()
match status:
case 0:
self.app.logger.error('Printer has no more paper, aborting...')
self.app.logger.error("Printer has no more paper, aborting...")
self.printer.close()
raise Exception("No more paper in the printer")
case 1:
self.app.logger.warning('Printer needs paper to be changed very soon ! ')
self.app.logger.warning(
"Printer needs paper to be changed very soon ! "
)
self.printer.close()
case 2:
self.app.logger.debug('Printer has paper, good to go')
self.app.logger.debug("Printer has paper, good to go")
self.printer.close()
def init_printer(self):
# Is the printer online ? Is the communication with the printer successfull ?
waiting_elapsed = 30
self.app.logger.debug('Waiting for printer to get online...')
self.app.logger.debug("Waiting for printer to get online...")
while not self.ready:
try:
@@ -66,56 +68,83 @@ class Printer(object):
# or else the device will appear as busy.
p = Usb(self.device_id, self.vendor_id, 0, profile="TM-P80")
except USBNotFoundError as e:
self.app.logger.error("The USB device is not plugged in, trying again : " + str(e))
self.app.logger.error(
"The USB device is not plugged in, trying again : " + str(e)
)
pass
try:
if p.is_online():
self.ready = True
self.app.logger.debug('Printer online !')
self.app.logger.debug("Printer online !")
except Exception as e:
pass
sleep(1)
waiting_elapsed -= 1
if waiting_elapsed < 1:
self.app.logger.error('Printer took more than 30 seconds to get online, aborting...')
waiting_elapsed = 30 # Reset the waiting time for the next print.
self.app.logger.error(
"Printer took more than 30 seconds to get online, aborting..."
)
waiting_elapsed = 1 # Reset the waiting time for the next print.
return False
# Setting up the printing options.
p.set(align='center', font='a', bold=False, underline=0, width=1, height=1, density=9, invert=False, smooth=False, flip=False, double_width=False, double_height=False, custom_size=False)
p.set(
align="center",
font="a",
bold=False,
underline=0,
width=1,
height=1,
density=9,
invert=False,
smooth=False,
flip=False,
double_width=False,
double_height=False,
custom_size=False,
)
# Beware : if we print every time the printer becomes ready, it means
# we are printing before and after every print !
self.printer = p
self.ready = True;
self.printer.close();
self.ready = True
self.printer.close()
self.check_paper()
return True
def print_sms(self, msg, signature="",bold=False):
def print_sms(self, msg, signature="", bold=False):
clean_msg = str(msg) + "\n"
clean_signature = str(signature)
if len(clean_msg) > 4096:
self.app.logger.warning("Could not print message of this length: " + str(len(clean_msg)))
raise Exception("Could not print message of this length :" + str(len(clean_msg)) + ", needs to be below 4096 caracters long.")
self.app.logger.warning(
"Could not print message of this length: " + str(len(clean_msg))
)
raise Exception(
"Could not print message of this length :"
+ str(len(clean_msg))
+ ", needs to be below 4096 caracters long."
)
if len(signature) > 256:
self.app.logger.warning("Could not print signature of this length: " + str(len(clean_signature)))
raise Exception("Could not print signature of this length :" + str(len(clean_signature)) + ", needs to be below 256 caracters long.")
self.app.logger.warning(
"Could not print signature of this length: " + str(len(clean_signature))
)
raise Exception(
"Could not print signature of this length :"
+ str(len(clean_signature))
+ ", needs to be below 256 caracters long."
)
try:
self.printer.open(self.usb_args);
self.printer.set(align='center', font='a', bold=bold)
self.printer.textln(clean_msg )
self.printer.open(self.usb_args)
self.printer.set(align="center", font="a", bold=bold)
self.printer.textln(clean_msg)
if clean_signature:
self.printer.textln(clean_signature )
self.printer.textln(clean_signature)
self.printer.close()
except Exception as e:
self.app.logger.error("Unable to print because : " + str(e))
@@ -123,16 +152,26 @@ class Printer(object):
self.app.logger.info("Printed text")
return True
def print_img(self, path, sign="",center=True,process=False):
def print_img(self, path, sign="", center=True, process=False):
clean_signature = str(sign)
if len(sign) > 256:
self.app.logger.warning("Could not print signature of this length: " + str(len(clean_signature)))
raise Exception("Could not print signature of this length :" + str(len(clean_signature)) + ", needs to be below 256 caracters long.")
self.app.logger.warning(
"Could not print signature of this length: " + str(len(clean_signature))
)
raise Exception(
"Could not print signature of this length :"
+ str(len(clean_signature))
+ ", needs to be below 256 caracters long."
)
if not os.path.isfile(str(path)):
self.app.logger.warning("File does not exist : " + str(path))
raise Exception('The file path for this image :' + str(path) + " wasn't found. Please try again.")
raise Exception(
"The file path for this image :"
+ str(path)
+ " wasn't found. Please try again."
)
else:
self.app.logger.debug("Printing file from " + str(path))
@@ -146,10 +185,9 @@ class Printer(object):
else:
self.app.logger.warning("Not proccessing the image")
try:
self.printer.open(self.usb_args)
self.printer.image(path,center=center)
self.printer.image(path, center=center)
self.printer.close()
self.app.logger.debug("Printed an image : " + str(path))
os.remove(path)
@@ -175,8 +213,6 @@ class Printer(object):
self.app.logger.info("Printed a QR")
return True
def cut(self):
try:
self.printer.open(self.usb_args)
@@ -194,7 +230,7 @@ class Printer(object):
def process_image(self, path):
brightness_factor = 1.5 # Used only if image is too dark
brightness_threshold = 100 # Brightness threshold (0255)
contrast_factor = 0.6 # Less than 1.0 = lower contrast
contrast_factor = 0.6 # Less than 1.0 = lower contrast
max_width = 575
max_height = 1000
@@ -215,13 +251,21 @@ def process_image(self, path):
# Compute brightness of original image (grayscale average)
grayscale = original_img.convert("L")
avg_brightness = np.array(grayscale).mean()
self.app.logger.debug("Average brightness of the image : " + str(avg_brightness) )
self.app.logger.debug(
"Average brightness of the image : " + str(avg_brightness)
)
# Dynamically compute brightness factor if too dark
if avg_brightness < brightness_threshold:
brightness_factor = 1 + (brightness_threshold - avg_brightness) / brightness_threshold
brightness_factor = min(max(brightness_factor, 1.1), 2.5) # Clamp between 1.1 and 2.5
self.app.logger.debug(f"Image too dark, increasing brightness by a factor of {brightness_factor:.2f}")
brightness_factor = (
1 + (brightness_threshold - avg_brightness) / brightness_threshold
)
brightness_factor = min(
max(brightness_factor, 1.1), 2.5
) # Clamp between 1.1 and 2.5
self.app.logger.debug(
f"Image too dark, increasing brightness by a factor of {brightness_factor:.2f}"
)
enhancer = ImageEnhance.Brightness(original_img)
original_img = enhancer.enhance(brightness_factor)
@@ -232,11 +276,13 @@ def process_image(self, path):
# Final resize check
if original_img.height > max_height:
raise ValueError("Image is too long, sorry! Keep it below 575×1000 pixels.")
self.app.logger.error("Image is too long, sorry! Keep it below 575×1000 pixels.")
self.app.logger.error(
"Image is too long, sorry! Keep it below 575×1000 pixels."
)
return False
# Convert to JPEG and save
jpeg_path = os.path.splitext(path)[0] + "_processed.jpg"
original_img.save(jpeg_path, format='JPEG', quality=95, optimize=True)
original_img.save(jpeg_path, format="JPEG", quality=95, optimize=True)
return jpeg_path