Move images functions to own file, add markdown support for text to

image
This commit is contained in:
n07070 committed 2026-11-29 03:23:50 +01:00
1 parent fe99cac8db
commit 5fa7e0bc51
2 files changed
+400 -205

No files matched your search

+382
View File
@@ -0,0 +1,382 @@
"""
Various image processing functions that don't fit in the Printer Class
"""
import math
import re
from pathlib import Path
from uuid import uuid4
from PIL import Image, ImageEnhance, ImageDraw, ImageFont
import numpy as np
def process_image(self, path, max_width=575, max_height=1000):
"""
Adjust the constrat of images
"""
brightness_threshold = 100
contrast_factor = 2.0
with Image.open(path) as img:
# Preserve aspect ratio while fitting within the maximum dimensions.
img.thumbnail(
(max_width, max_height),
Image.Resampling.LANCZOS,
)
grayscale_image = img.convert("L")
avg_brightness = np.asarray(grayscale_image, dtype=np.float32).mean()
self.app.logger.debug("Average brightness of the image: %.2f", avg_brightness)
if avg_brightness < brightness_threshold:
brightness_factor = min(
max(
1 + (brightness_threshold - avg_brightness) / brightness_threshold,
1.1,
),
2.5,
)
self.app.logger.debug(
"Image is dark; increasing brightness by %.2f",
brightness_factor,
)
grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance(
brightness_factor
)
contrast = float(np.asarray(grayscale_image, dtype=np.float32).std())
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
# Save the enhanced result.
processed = ImageEnhance.Contrast(grayscale_image).enhance(contrast_factor)
jpeg_path = os.path.splitext(path)[0] + "_processed.jpg"
processed.save(jpeg_path, format="JPEG", quality=95, optimize=True)
self.app.logger.debug("Processed and saved image: %s", jpeg_path)
return jpeg_path
def text_to_image(
text,
width=400,
font_path="src/static/font/Sono-Regular.ttf",
font_size=24,
padding=10,
line_spacing=4,
background="white",
fill="black",
output_dir="src/static/uploads",
align="center", # "left", "center", or "right"
bold_font_path="src/static/font/Sono-Bold.ttf",
italic_font_path=None,
bold_italic_font_path=None,
):
"""Convert text with basic Markdown bold and italic to an image.
Supported markers: **bold**, *italic*, and ***bold italic***.
Underscore forms (__bold__, _italic_) are supported too.
DISCLAIMER : THIS CODE WAS GENERATED BY A LLM. I'm too dumb to code this myself. If a human has a better solution, I'm very much willing to hear about it. This code may or may not work. If it causes bugs, tough luck !
"""
if align not in {"left", "center", "right"}:
raise ValueError("align must be 'left', 'center', or 'right'")
# Load supplied font faces. Missing styles are simulated from the regular font.
fonts = {
"regular": ImageFont.truetype(font_path, font_size),
"bold": ImageFont.truetype(bold_font_path, font_size)
if bold_font_path else None,
"italic": ImageFont.truetype(italic_font_path, font_size)
if italic_font_path else None,
"bold_italic": ImageFont.truetype(bold_italic_font_path, font_size)
if bold_italic_font_path else None,
}
regular_font = fonts["regular"]
# Match triple markers before double and single markers.
marker_re = re.compile(
r"\*\*\*(.+?)\*\*\*|___(.+?)___|"
r"\*\*(.+?)\*\*|__(.+?)__|"
r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|"
r"(?<!_)_(?!_)(.+?)(?<!_)_(?!_)"
)
def parse_paragraph(paragraph):
"""Return a list of (character, style) pairs."""
result = []
position = 0
for match in marker_re.finditer(paragraph):
result.extend(
(char, "regular") for char in paragraph[position:match.start()]
)
groups = match.groups()
if groups[0] is not None or groups[1] is not None:
content = groups[0] if groups[0] is not None else groups[1]
style = "bold_italic"
elif groups[2] is not None or groups[3] is not None:
content = groups[2] if groups[2] is not None else groups[3]
style = "bold"
else:
content = groups[4] if groups[4] is not None else groups[5]
style = "italic"
result.extend((char, style) for char in content)
position = match.end()
result.extend((char, "regular") for char in paragraph[position:])
return result
def get_font_and_effects(style):
"""Choose a supplied font face, or return fallback drawing effects."""
if style == "regular":
return regular_font, 0, False
if style == "bold":
if fonts["bold"]:
return fonts["bold"], 0, False
return regular_font, 1, False
if style == "italic":
if fonts["italic"]:
return fonts["italic"], 0, False
return regular_font, 0, True
# Prefer a real combined face. Otherwise combine bold and italic effects.
if fonts["bold_italic"]:
return fonts["bold_italic"], 0, False
bold_face = fonts["bold"]
return bold_face or regular_font, 0 if bold_face else 1, True
# Use a small shear for synthetic italics.
italic_shear = 0.25
def grouped_runs(chars):
"""Group adjacent characters that share the same style."""
runs = []
for char, style in chars:
if runs and runs[-1][0] == style:
runs[-1][1] += char
else:
runs.append([style, char])
return runs
def run_width(style, text):
"""Estimate rendered width, including simulated bold/italic effects."""
font, stroke_width, synthetic_italic = get_font_and_effects(style)
extra = stroke_width * 2
if synthetic_italic:
extra += math.ceil(italic_shear * font_size)
return font.getlength(text) + extra
def chars_width(chars):
return sum(run_width(style, text) for style, text in grouped_runs(chars))
max_text_width = width - 2 * padding
if max_text_width <= 0:
raise ValueError("width must be greater than twice the padding")
# Wrap words by their rendered pixel width.
lines = []
for paragraph in text.splitlines() or [""]:
chars = parse_paragraph(paragraph)
words = []
current_word = []
for item in chars:
if item[0].isspace():
if current_word:
words.append(current_word)
current_word = []
else:
current_word.append(item)
if current_word:
words.append(current_word)
if not words:
lines.append([])
continue
line = []
for word in words:
candidate = line + ([(" ", "regular")] if line else []) + word
if chars_width(candidate) <= max_text_width:
line = candidate
continue
if line:
lines.append(line)
line = []
# Break a word that's wider than the available line width.
for item in word:
if line and chars_width(line + [item]) > max_text_width:
lines.append(line)
line = []
line.append(item)
if line:
lines.append(line)
if not lines:
lines = [[]]
ascent, descent = regular_font.getmetrics()
line_height = ascent + descent
image_height = (
2 * padding
+ len(lines) * line_height
+ (len(lines) - 1) * line_spacing
)
image = Image.new("RGBA", (width, image_height), background)
def render_run(style, text):
"""Render one styled run, applying fallback bold/italic effects."""
font, stroke_width, synthetic_italic = get_font_and_effects(style)
bbox = font.getbbox(text, stroke_width=stroke_width)
run_width_px = max(
1,
math.ceil(font.getlength(text) + 2 * stroke_width + font_size),
bbox[2] - bbox[0] + 2 * stroke_width + font_size,
)
run_height_px = max(line_height + font_size, bbox[3] - bbox[1] + font_size)
layer = Image.new("RGBA", (run_width_px, run_height_px), (0, 0, 0, 0))
layer_draw = ImageDraw.Draw(layer)
# Offset the glyphs so their bounding box starts inside the transparent layer.
text_x = stroke_width - bbox[0]
text_y = -bbox[1]
layer_draw.text(
(text_x, text_y),
text,
font=font,
fill=fill,
stroke_width=stroke_width,
stroke_fill=fill,
)
alpha_bbox = layer.getbbox()
if alpha_bbox:
layer = layer.crop(alpha_bbox)
if synthetic_italic:
shear_extra = math.ceil(italic_shear * layer.height)
layer = layer.transform(
(layer.width + shear_extra, layer.height),
Image.Transform.AFFINE,
(1, -italic_shear, 0, 0, 1, 0),
resample=Image.Resampling.BICUBIC,
)
advance = font.getlength(text) + 2 * stroke_width
if synthetic_italic:
advance += math.ceil(italic_shear * font_size)
return layer, advance
# Draw each line using its measured width to position left, center, or right.
y = padding
for line in lines:
line_width = chars_width(line)
if align == "center":
x = padding + (max_text_width - line_width) / 2
elif align == "right":
x = padding + max_text_width - line_width
else:
x = padding
for style, run_text in grouped_runs(line):
run_image, advance = render_run(style, run_text)
image.alpha_composite(run_image, (round(x), y))
x += advance
y += line_height + line_spacing
# Convert to RGB so backgrounds like named colors save consistently as PNG.
image = image.convert("RGB")
upload_dir = Path(output_dir)
upload_dir.mkdir(parents=True, exist_ok=True)
image_path = upload_dir / f"{uuid4().hex}.png"
image.save(image_path, format="PNG")
return str(image_path)
def _resize_image(
self,
label_type: str,
image_path: str,
device_pixel_width: int,
printer_model: object,
):
# """
# Resize an image to the specs needed for a label. Only used in Brother printers
# """
# self.app.logger.debug("Resizing the image from %s", image_path)
# label_specs = LabelsManager().get_label_by_identifier(label_type)
# right_margin_dots = label_specs.offset_r
# model_obj = ModelsManager().get_model_by_identifier(printer_model)
# right_margin_dots += model_obj.additional_offset_r
# max_image_dimension = label_specs.dots_printable
# self.app.logger.debug("Found label %s with maximum dimensions %s", label_type, max_image_dimension)
# # Open image
# with Image.open(image_path ) as img:
# self.app.logger.debug("Image current dimensions before resizing are %s", img.size)
# # Fit inside the label dimensions while preserving aspect ratio.
# max_width = max_image_dimension[0]
# max_height = max_image_dimension[1]
# img = ImageOps.contain(
# img,
# (max_width, max_height),
# method=Image.Resampling.LANCZOS,
# )
# # Create a new image of the correct dimensions
# new_im = Image.new(
# img.mode,
# (device_pixel_width, max_image_dimension[1]),
# (255,) * len(img.mode),
# )
# # Set image position
# x = max(0, device_pixel_width - img.size[0] - right_margin_dots)
# # Paste the resized image into the new image
# new_im.paste(img, (x, 0))
# # Replace the original image
# img = new_im
# # Set path for the image
# jpeg_path = os.path.splitext(image_path)[0] + "_resized.jpg"
# try:
# img.save(jpeg_path, format="JPEG", quality=95, optimize=True)
# except OSError as e:
# self.app.logger.debug("Error while saving the rised image ! %s", str(e))
# raise e
# # end try
# return jpeg_path
pass
+18 -205
View File
@@ -9,11 +9,9 @@ from dataclasses import dataclass
import time import time
from enum import Enum from enum import Enum
import uuid import uuid
from pathlib import Path
from uuid import uuid4
import usb.core import usb.core
from PIL import Image, ImageEnhance, ImageDraw, ImageFont, ImageOps
import numpy as np from PIL import Image
# Importing the modules needed for each supported printer Type # Importing the modules needed for each supported printer Type
import escpos.printer import escpos.printer
@@ -28,6 +26,8 @@ from brother_ql import create_label
# Used for typing # Used for typing
from task import PrintTask from task import PrintTask
# Image processing functions
from images import process_image, text_to_image
class PrinterType(Enum): class PrinterType(Enum):
""" """
@@ -288,7 +288,7 @@ class EscPosPrinter(Printer):
if process: if process:
try: try:
self.app.logger.debug("Proccessing the image") self.app.logger.debug("Proccessing the image")
processed_path = _process_image(self, path) processed_path = process_image(self, path)
except RuntimeError as e: except RuntimeError as e:
self.app.logger.error( self.app.logger.error(
"Error while processing the image, aborting print : %s", str(e) "Error while processing the image, aborting print : %s", str(e)
@@ -460,7 +460,7 @@ class BrotherPrinter(Printer):
len(matching_identifiers), len(matching_identifiers),
) )
raise RuntimeError( raise RuntimeError(
"Expected one Brother backend device matching %s, found %s", "Expected one Brother backend device matching %s, found %s" %
expected_prefix, expected_prefix,
len(matching_identifiers), len(matching_identifiers),
) )
@@ -513,12 +513,13 @@ class BrotherPrinter(Printer):
def _state(self): def _state(self):
return self.ready return self.ready
def _print_txt(self, msg, signature="", do_cut=False): def _print_txt(self, msg, signature="", do_cut=False, align="right",font_size=20):
"""Print text after converting it to an image""" """Print text after converting it to an image"""
if signature == "": if signature == "":
self._print_img(text_to_image(msg), do_cut=do_cut) self._print_img(text_to_image(msg, align=align,font_size=font_size), do_cut=do_cut)
else: else:
self._print_img(text_to_image(msg), signature, do_cut=do_cut) self._print_img(text_to_image(msg, align="right",font_size=font_size), signature, do_cut=do_cut)
def _print_img(self, data, signature="", process=False, do_cut=False): def _print_img(self, data, signature="", process=False, do_cut=False):
""" """
@@ -532,7 +533,7 @@ class BrotherPrinter(Printer):
if process: if process:
try: try:
self.app.logger.debug("\t[⚙ %s] Proccessing the image", self.id) self.app.logger.debug("\t[⚙ %s] Proccessing the image", self.id)
processed_path = _process_image(self, data) processed_path = process_image(self, data)
except RuntimeError as e: except RuntimeError as e:
self.app.logger.error( self.app.logger.error(
"Error while processing the image, aborting print : %s", str(e) "Error while processing the image, aborting print : %s", str(e)
@@ -543,8 +544,8 @@ class BrotherPrinter(Printer):
self.app.logger.warning("Not proccessing the image") self.app.logger.warning("Not proccessing the image")
try: try:
# selected_backend = guess_backend(self.printer_info.identifier) selected_backend = guess_backend(self.printer_info.identifier)
# BACKEND_CLASS = backend_factory(selected_backend)["backend_class"] BACKEND_CLASS = backend_factory(selected_backend)["backend_class"]
BACKEND_STRING_DESCR = self.printer_info.identifier BACKEND_STRING_DESCR = self.printer_info.identifier
except Exception as e: except Exception as e:
self.app.logger.error( self.app.logger.error(
@@ -552,6 +553,8 @@ class BrotherPrinter(Printer):
) )
raise e raise e
do_cut_before_sign = True if signature != "" and do_cut else False
try: try:
qlr = BrotherQLRaster(self.printer_info.model) qlr = BrotherQLRaster(self.printer_info.model)
@@ -572,7 +575,7 @@ class BrotherPrinter(Printer):
dither=True, dither=True,
compress=False, compress=False,
dpi_600=False, dpi_600=False,
cut=do_cut, cut=do_cut_before_sign,
) )
return_from_printer = send( return_from_printer = send(
@@ -627,7 +630,7 @@ class BrotherPrinter(Printer):
dither=True, dither=True,
compress=False, compress=False,
dpi_600=False, dpi_600=False,
cut=False, cut=do_cut,
) )
success = send( success = send(
@@ -682,7 +685,7 @@ class BrotherPrinter(Printer):
) )
case "text": case "text":
self._print_txt( self._print_txt(
data["txt"], signature=data["sign"], do_cut=data["do_cut"] data["txt"], signature=data["sign"], do_cut=data["do_cut"], align=data["align"],font_size=data["font_size"]
) )
case _: case _:
raise RuntimeError("This task type is not supported") raise RuntimeError("This task type is not supported")
@@ -702,193 +705,3 @@ class BrotherPrinter(Printer):
"\t[⚙ %s] Finished consuming task %s", self.id, task.task_id "\t[⚙ %s] Finished consuming task %s", self.id, task.task_id
) )
self.ready = True self.ready = True
def _process_image(self, path, max_width=575, max_height=1000):
brightness_threshold = 100
contrast_factor = 2.0
with Image.open(path) as img:
# Preserve aspect ratio while fitting within the maximum dimensions.
img.thumbnail(
(max_width, max_height),
Image.Resampling.LANCZOS,
)
grayscale_image = img.convert("L")
avg_brightness = np.asarray(grayscale_image, dtype=np.float32).mean()
self.app.logger.debug("Average brightness of the image: %.2f", avg_brightness)
if avg_brightness < brightness_threshold:
brightness_factor = min(
max(
1 + (brightness_threshold - avg_brightness) / brightness_threshold,
1.1,
),
2.5,
)
self.app.logger.debug(
"Image is dark; increasing brightness by %.2f",
brightness_factor,
)
grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance(
brightness_factor
)
contrast = float(np.asarray(grayscale_image, dtype=np.float32).std())
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
# Save the enhanced result.
processed = ImageEnhance.Contrast(grayscale_image).enhance(contrast_factor)
jpeg_path = os.path.splitext(path)[0] + "_processed.jpg"
processed.save(jpeg_path, format="JPEG", quality=95, optimize=True)
self.app.logger.debug("Processed and saved image: %s", jpeg_path)
return jpeg_path
def text_to_image(
text,
width=400,
font_path="src/static/font/MonospaceTypewriter.ttf",
font_size=24,
padding=10,
line_spacing=4,
background="white",
fill="black",
output_dir="src/static/uploads",
):
"""Converts a string to an image"""
font = ImageFont.truetype(font_path, font_size)
# Measure and wrap text by pixel width.
measure_img = Image.new("RGB", (1, 1))
draw = ImageDraw.Draw(measure_img)
max_text_width = width - 2 * padding
if max_text_width <= 0:
raise ValueError("width must be greater than twice the padding")
lines = []
for paragraph in text.splitlines() or [""]:
words = paragraph.split()
if not words:
lines.append("")
continue
line = ""
for word in words:
candidate = f"{line} {word}".strip()
if draw.textbbox((0, 0), candidate, font=font)[2] <= max_text_width:
line = candidate
continue
if line:
lines.append(line)
# Split a word that is wider than the available width.
line = ""
piece = ""
for char in word:
if (
piece
and draw.textbbox((0, 0), piece + char, font=font)[2]
> max_text_width
):
lines.append(piece)
piece = char
else:
piece += char
line = piece
if line:
lines.append(line)
if not lines:
lines = [""]
ascent, descent = font.getmetrics()
line_height = ascent + descent
height = 2 * padding + len(lines) * line_height + (len(lines) - 1) * line_spacing
image = Image.new("RGB", (width, height), background)
draw = ImageDraw.Draw(image)
y = padding
for line in lines:
draw.text((padding, y), line, font=font, fill=fill)
y += line_height + line_spacing
upload_dir = Path(output_dir)
upload_dir.mkdir(parents=True, exist_ok=True)
image_path = upload_dir / f"{uuid4().hex}.png"
image.save(image_path, format="PNG")
return str(image_path)
def _resize_image(
self,
label_type: str,
image_path: str,
device_pixel_width: int,
printer_model: object,
):
# """
# Resize an image to the specs needed for a label. Only used in Brother printers
# """
# self.app.logger.debug("Resizing the image from %s", image_path)
# label_specs = LabelsManager().get_label_by_identifier(label_type)
# right_margin_dots = label_specs.offset_r
# model_obj = ModelsManager().get_model_by_identifier(printer_model)
# right_margin_dots += model_obj.additional_offset_r
# max_image_dimension = label_specs.dots_printable
# self.app.logger.debug("Found label %s with maximum dimensions %s", label_type, max_image_dimension)
# # Open image
# with Image.open(image_path ) as img:
# self.app.logger.debug("Image current dimensions before resizing are %s", img.size)
# # Fit inside the label dimensions while preserving aspect ratio.
# max_width = max_image_dimension[0]
# max_height = max_image_dimension[1]
# img = ImageOps.contain(
# img,
# (max_width, max_height),
# method=Image.Resampling.LANCZOS,
# )
# # Create a new image of the correct dimensions
# new_im = Image.new(
# img.mode,
# (device_pixel_width, max_image_dimension[1]),
# (255,) * len(img.mode),
# )
# # Set image position
# x = max(0, device_pixel_width - img.size[0] - right_margin_dots)
# # Paste the resized image into the new image
# new_im.paste(img, (x, 0))
# # Replace the original image
# img = new_im
# # Set path for the image
# jpeg_path = os.path.splitext(image_path)[0] + "_resized.jpg"
# try:
# img.save(jpeg_path, format="JPEG", quality=95, optimize=True)
# except OSError as e:
# self.app.logger.debug("Error while saving the rised image ! %s", str(e))
# raise e
# # end try
# return jpeg_path
pass