-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprintit.py
1362 lines (1123 loc) · 51.7 KB
/
printit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
from PIL import Image, ImageDraw, ImageFont, PngImagePlugin, ImageOps
import requests
import io
import glob
import base64
import os
import re
import tempfile
from datetime import datetime
import time
import qrcode
from brother_ql.models import ModelsManager
from brother_ql.backends import backend_factory
from brother_ql.raster import BrotherQLRaster
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
from brother_ql import labels # Import the labels module
import usb.core
import subprocess
from job_queue import print_queue # Import from renamed file
# After the imports, before the functions
if 'label_type' not in st.session_state:
st.session_state.label_type = None
st.session_state.label_status = None
def find_and_parse_printer():
"""Find and parse Brother QL printer information."""
model_manager = ModelsManager()
# Debug print to show we're searching
print("Searching for Brother QL printer...")
for backend_name in ["pyusb", "linux_kernel"]:
try:
print(f"Trying backend: {backend_name}")
backend = backend_factory(backend_name)
available_devices = backend["list_available_devices"]()
print(f"Found {len(available_devices)} devices with {backend_name} backend")
for printer in available_devices:
print(f"Found device: {printer}")
identifier = printer["identifier"]
parts = identifier.split("/")
if len(parts) < 4:
print(f"Skipping device with invalid identifier format: {identifier}")
continue
protocol = parts[0]
device_info = parts[2]
serial_number = parts[3]
try:
vendor_id, product_id = device_info.split(":")
except ValueError:
print(f"Invalid device info format: {device_info}")
continue
# Default model
model = "QL-570"
# Try to match product ID to determine actual model
try:
product_id_int = int(product_id, 16)
for m in model_manager.iter_elements():
if m.product_id == product_id_int:
model = m.identifier
break
print(f"Matched printer model: {model}")
except ValueError:
print(f"Invalid product ID format: {product_id}")
continue
printer_info = {
"identifier": identifier,
"backend": backend_name,
"model": model,
"protocol": protocol,
"vendor_id": vendor_id,
"product_id": product_id,
"serial_number": serial_number,
}
print(f"Found printer: {printer_info}")
return printer_info
except Exception as e:
print(f"Error with backend {backend_name}: {str(e)}")
continue
print("No Brother QL printer found")
return None
def get_printer_label_info():
printer_info = find_and_parse_printer()
if not printer_info:
return None, "No printer found"
try:
# First try to get status using brother_ql command line tool
cmd = f"brother_ql -b pyusb --model {printer_info['model']} -p {printer_info['identifier']} status"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
# If command succeeded and we got output
if result.returncode == 0 and result.stdout:
status_output = result.stdout
print(f"Printer status output: {status_output}") # Debug print
# Parse the status output
media_width_mm = None
for line in status_output.split('\n'):
if 'Media size:' in line:
try:
# Extract just the number before 'x'
width_str = line.split(':')[1].split('x')[0].strip()
media_width_mm = int(width_str)
print(f"Detected media width: {media_width_mm}mm") # Debug print
except ValueError:
continue
if media_width_mm is not None:
# Map physical width in mm to brother_ql label types
label_sizes = {
12: "12", # 106 dots printable
29: "29", # 306 dots printable
38: "38", # 413 dots printable
50: "50", # 554 dots printable
54: "54", # 590 dots printable
62: "62", # 696 dots printable
102: "102", # 1164 dots printable
103: "103", # 1200 dots printable
104: "104" # 1200 dots printable
}
if media_width_mm in label_sizes:
label_type = label_sizes[media_width_mm]
return label_type, f"Detected {label_type} ({media_width_mm}mm)"
# If we couldn't get the width from status, check if it's in printer_info
if 'model' in printer_info:
# Default mappings for common models
model_defaults = {
'QL-500': "62",
'QL-550': "62",
'QL-560': "62",
'QL-570': "62",
'QL-580N': "62",
'QL-650TD': "62",
'QL-700': "62",
'QL-710W': "62",
'QL-720NW': "62",
'QL-800': "62",
'QL-810W': "62",
'QL-820NWB': "62",
'QL-1050': "102",
'QL-1060N': "102",
}
if printer_info['model'] in model_defaults:
return model_defaults[printer_info['model']], f"Using default for {printer_info['model']}"
# If all else fails, return a safe default
return "62", "Using safe default width"
except Exception as e:
print(f"Error getting printer status: {str(e)}") # Debug print
return "62", f"Error getting printer status, using default"
def get_label_type():
"""
Determine label type in order of precedence:
1. From session state if already detected
2. From printer's current media (most accurate)
3. From secrets.toml configuration (fallback)
4. Default to "62" with warning
"""
# First check if we already have the label type in session state
if st.session_state.label_type is not None:
return st.session_state.label_type, st.session_state.label_status
# Try to detect from printer's current media
detected_label, status_message = get_printer_label_info()
if detected_label:
print(f"Using detected label type: {detected_label} - {status_message}") # Debug print
# Store in session state
st.session_state.label_type = detected_label
st.session_state.label_status = status_message
return detected_label, status_message
# Try to get from secrets.toml
if "label_type" in st.secrets:
configured_type = st.secrets["label_type"]
status = "Using configured label_type from secrets"
print(f"Using configured label type from secrets: {configured_type}") # Debug print
# Store in session state
st.session_state.label_type = configured_type
st.session_state.label_status = status
return configured_type, status
# If neither works, return default with warning
default_type = "62"
status = "Using default label type 62"
print("No label type detected or configured, using default 62") # Debug print
st.warning("⚠️ No label type detected from printer and none configured in secrets.toml. Using default label type 62")
# Store in session state
st.session_state.label_type = default_type
st.session_state.label_status = status
return default_type, status
# Get label type and status message
label_type, label_status = get_label_type()
if 'txt2img_url' not in st.secrets:
st.warning("⚠️ txt2img_url not found in secrets. Using default localhost:8670")
txt2img_url = "http://localhost:8670"
else:
txt2img_url = st.secrets['txt2img_url']
def get_label_width(label_type):
label_definitions = labels.ALL_LABELS
for label in label_definitions:
if label.identifier == label_type:
width = label.dots_printable[0]
print(f"Label type {label_type} width: {width} dots") # Debug print
return width
raise ValueError(f"Label type {label_type} not found in label definitions")
label_width = get_label_width(label_type) # Use the width as label_width
# Check if the 'copy' parameter exists
# add to url "?copy=25"
copy = int(st.query_params.get("copy", [1])[0]) # Default to 1 copy if not specified
# Function to list saved images with optional duplicate filtering
def list_saved_images(filter_duplicates=True):
# Get history limit from secrets with default fallback of 15
history_limit = st.secrets.get("history_limit", 15)
# Get all image files from both temp and labels folders
temp_files = glob.glob(os.path.join("temp", "*.[pj][np][g]*"))
label_files = glob.glob(os.path.join("labels", "*.[pj][np][g]*"))
# Combine all image files
image_files = temp_files + label_files
# Filter out test labels and get valid images
valid_images = [
f for f in image_files
if "write_something" not in os.path.basename(f).lower()
]
if not filter_duplicates:
# Simply return all files sorted by modification time
return sorted(valid_images, key=os.path.getmtime, reverse=True)[:history_limit]
# Create a dictionary to store the latest version of each unique image size
unique_images = {}
for image_path in valid_images:
try:
# Get file size in bytes
file_size = os.path.getsize(image_path)
# If this size already exists, compare modification times
if file_size in unique_images:
existing_time = os.path.getmtime(unique_images[file_size])
current_time = os.path.getmtime(image_path)
if current_time > existing_time:
unique_images[file_size] = image_path
else:
unique_images[file_size] = image_path
except Exception as e:
print(f"Error processing {image_path}: {e}")
continue
# Sort by modification time (newest first)
return sorted(unique_images.values(), key=os.path.getmtime, reverse=True)[:history_limit]
# Replace the get_fonts function
def get_fonts():
"""Return list of fonts with 5x5-Tami.ttf as default"""
default_font = "fonts/5x5-Tami.ttf"
# Check if our default font exists
if os.path.exists(default_font):
try:
# Verify it's a valid font
ImageFont.truetype(default_font, 12)
return [default_font] # Only return our custom font if it exists and works
except Exception as e:
print(f"Error loading 5x5-Tami.ttf: {e}")
# If we get here, either the font doesn't exist or failed to load
# Return system fonts as fallback
return [
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", # Linux
"C:/Windows/Fonts/arial.ttf", # Windows
"/System/Library/Fonts/Helvetica.ttf", # macOS
]
def safe_filename(text):
# Sanitize the text to remove illegal characters and replace spaces with underscores
sanitized_text = re.sub(r'[<>:"/\\|?*\n\r]+', "", text).replace(" ", "_")
# Get the current time in epoch format
epoch_time = int(time.time())
# Return the filename
return f"{epoch_time}_{sanitized_text}.png"
# Ensure label directory exists
label_dir = "labels"
os.makedirs(label_dir, exist_ok=True)
def generate_image(prompt, steps):
payload = {"prompt": prompt, "steps": steps, "width": label_width}
# Get txt2img_url from secrets with default fallback
txt2img_url = st.secrets.get("txt2img_url", "http://localhost:7860")
# Show warning if using default URL
if txt2img_url == "http://localhost:7860":
st.warning("Using default Stable Diffusion URL (http://localhost:7860). Configure txt2img_url in .streamlit/secrets.toml for custom endpoint.")
try:
response = requests.post(url=f'{txt2img_url}/sdapi/v1/txt2img', json=payload)
# Check if the request was successful
response.raise_for_status()
# Print raw response content for debugging
print("Raw response content:", response.content)
r = response.json()
if r["images"]:
first_image = r["images"][0]
base64_data = (
first_image.split("base64,")[1]
if "base64," in first_image
else first_image
)
image = Image.open(io.BytesIO(base64.b64decode(base64_data)))
png_payload = {"image": "data:image/png;base64," + first_image}
response2 = requests.post(
url=f"{txt2img_url}/sdapi/v1/png-info", json=png_payload
)
response2.raise_for_status()
# save image
pnginfo = PngImagePlugin.PngInfo()
info = response2.json().get("info")
if info:
pnginfo.add_text("parameters", str(info))
current_date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
temp_dir = "temp"
os.makedirs(temp_dir, exist_ok=True)
filename = os.path.join(temp_dir, "txt2img_" + current_date + ".png")
image.save(filename, pnginfo=pnginfo)
return image
else:
print("No images found in the response")
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred while making the request: {e}")
return None
except ValueError as e:
print(f"An error occurred while parsing the JSON response: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
def preper_image(image, label_width=label_width):
# Debug print original image size
# print(f"Original image size: {image.size}")
# Handle PNG transparency by adding white background
if image.mode == "RGBA":
# Create a white background image
background = Image.new("RGBA", image.size, "white")
# Alpha composite the image over the white background
image = Image.alpha_composite(background, image)
# Convert to RGB after compositing
image = image.convert("RGB")
# Only resize if the image width doesn't match label width
width, height = image.size
if width != label_width:
# Calculate new height maintaining aspect ratio
new_height = int((label_width / width) * height)
image = image.resize((label_width, new_height))
print(f"Resizing image from ({width}, {height}) >> {image.size}")
# Convert to grayscale if needed
if image.mode != "L":
grayscale_image = image.convert("L")
else:
grayscale_image = image
# Apply Floyd-Steinberg dithering
dithered_image = grayscale_image.convert("1", dither=Image.FLOYDSTEINBERG)
return grayscale_image, dithered_image
def print_image(image, rotate=0, dither=False):
"""
Queue a print job and return the job ID.
The actual printing will be handled by the print queue worker.
"""
# Ensure the temporary directory exists
temp_dir = tempfile.gettempdir()
os.makedirs(temp_dir, exist_ok=True)
# Save the image to a temporary file
with tempfile.NamedTemporaryFile(
suffix=".png", delete=False, dir=temp_dir
) as temp_file:
temp_file_path = temp_file.name
image.save(temp_file_path, "PNG")
print(f"Image saved to: {temp_file_path}") # Print the full path
# Use find_and_parse_printer to get printer information
printer_info = find_and_parse_printer()
if not printer_info:
st.error(
"No Brother QL printer found. Please check the connection and try again."
)
return False
# Get the current label type
label_type, _ = get_label_type()
print(f"Using label type: {label_type}") # Debug print
# Add job to print queue with correct label type
job_id = print_queue.add_job(
image,
rotate=rotate,
dither=dither,
printer_info=printer_info,
temp_file_path=temp_file_path,
label_type=label_type # Add label_type to the job parameters
)
# Start monitoring job status
status = print_queue.get_job_status(job_id)
# Show job status in UI
status_container = st.empty()
while status.status in ["pending", "processing"]:
status_container.info(f"Print job status: {status.status}")
time.sleep(0.5)
status = print_queue.get_job_status(job_id)
if status.status == "completed":
status_container.success("Print job completed successfully!")
return True
else:
status_container.error(f"Print job failed: {status.error}")
return False
# Add a new function to show queue status
def show_queue_status():
"""Show the current print queue status in the UI"""
# Check if queue view is enabled in secrets (default to False)
if not st.secrets.get("queueview", False):
return
status = print_queue.get_queue_status()
# Only show status if there are jobs in queue or currently processing
if status["queue_size"] > 0 or status["is_processing"]:
# Create a small container in the top-right corner
status_container = st.empty()
with status_container.container():
# Make the status display compact
st.markdown(
"""
<style>
div[data-testid="stVerticalBlock"] > div {
padding-top: 0;
padding-bottom: 0;
margin-top: -1em;
}
</style>
""",
unsafe_allow_html=True
)
# Use a single line for each job status
for job_id, job_info in status["jobs"].items():
status_color = {
"pending": "🟡",
"processing": "🔵",
"completed": "🟢",
"failed": "🔴"
}.get(job_info["status"], "⚪")
# Show job ID (first 8 chars) and status
status_text = f"{status_color} Job {job_id[:8]}: {job_info['status']}"
if job_info["error"]:
status_text += f" ({job_info['error']})"
st.write(status_text)
# Add queue status display to the main UI
if __name__ == "__main__":
show_queue_status()
def find_url(string):
url_pattern = re.compile(
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
)
urls = re.findall(url_pattern, string)
return urls
def img_concat_v(im1, im2, image_width=label_width):
dst = Image.new("RGB", (im1.width, im1.height + image_width))
dst.paste(im1, (0, 0))
im2 = im2.resize((image_width, image_width))
dst.paste(im2, (0, im1.height))
return dst
def get_cat_breeds():
cat_api_key = st.secrets.get("cat_api_key", "")
if not cat_api_key or cat_api_key == "ask me":
return ["API key required"]
try:
response = requests.get(
"https://api.thecatapi.com/v1/breeds",
headers={"x-api-key": cat_api_key}
)
breeds = response.json()
return [breed["name"] for breed in breeds]
except:
return ["Error fetching breeds"]
def apply_threshold(image, threshold):
# Ensure the image is in grayscale mode
if image.mode != 'L':
image = image.convert('L')
# Create a LUT with 256 entries
lut = [255 if i > threshold else 0 for i in range(256)]
return image.point(lut, mode='1')
def resize_image_to_width(image, target_width_mm, current_dpi=300):
# Convert mm to inches (since DPI is dots per inch)
target_width_inch = target_width_mm / 25.4
# Calculate the target pixel width using the given DPI
target_width_px = int(target_width_inch * current_dpi)
# Get current dimensions
current_width = image.width
# Calculate scaling factor based on target width
scale_factor = target_width_px / current_width
# Calculate new height maintaining aspect ratio
new_height = int(image.height * scale_factor)
# Resize the image while maintaining the aspect ratio
resized_image = image.resize((target_width_px, new_height), Image.LANCZOS)
# If the resized width is less than label_width pixels, pad with white
if target_width_px < label_width:
new_image = Image.new("RGB", (label_width, new_height), (255, 255, 255))
new_image.paste(resized_image, ((label_width - target_width_px) // 2, 0))
resized_image = new_image
print(f"Image resized from {image.width}x{image.height} to {resized_image.width}x{resized_image.height} pixels.")
print(f"Target width was {target_width_mm}mm ({target_width_px}px)")
return resized_image
def add_border(image, border_width=1):
"""Add a thin black border around the image"""
if image.mode == '1': # Binary image
# For binary images, create a new binary image with border
bordered = Image.new('1', (image.width + 2*border_width, image.height + 2*border_width), 0) # 0 is black
bordered.paste(image, (border_width, border_width))
return bordered
else:
# For other modes, use ImageOps
return ImageOps.expand(image, border=border_width, fill='black')
def apply_levels(image, black_point=0, white_point=255):
"""Apply levels adjustment to an image"""
if image.mode != 'L':
image = image.convert('L')
# Create lookup table for the transformation
lut = []
for i in range(256):
# Normalize the input range
if i <= black_point:
lut.append(0)
elif i >= white_point:
lut.append(255)
else:
# Linear mapping between black and white points
normalized = (i - black_point) / (white_point - black_point)
lut.append(int(normalized * 255))
return image.point(lut)
def apply_histogram_equalization(image, black_point=0, white_point=255):
"""Apply histogram equalization with levels adjustment to an image"""
if image.mode != 'L':
image = image.convert('L')
# First apply levels adjustment
leveled = apply_levels(image, black_point, white_point)
# Then apply histogram equalization
return ImageOps.equalize(leveled)
# Streamlit app
if not os.path.exists(".streamlit/secrets.toml"):
st.error("⚠️ No secrets.toml file found!")
st.info("""
Please set up your `.streamlit/secrets.toml` file:
1. Copy the example file: `cp .streamlit/secrets.toml.example .streamlit/secrets.toml`
2. Edit the file with your settings
The app will try to auto-detect your printer's label type, but you can override it in secrets.toml if needed.
See the example file for all available options and their descriptions.
""")
st.title(st.secrets.get("title", "STICKER FACTORY"))
st.subheader(":printer: hard copies of images and text")
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs(
["Sticker", "Label", "Text2image", "Webcam", "Cat", "Mask Pro", "history", "FAQ"]
)
# Initialize the session state for the prompt and image
if "prompt" not in st.session_state:
st.session_state.prompt = ""
if "generated_image" not in st.session_state:
st.session_state.generated_image = None
def submit():
st.session_state.prompt = st.session_state.widget
st.session_state.widget = ""
st.session_state.generated_image = (
None # Reset the generated image when a new prompt is entered
)
# sticker
with tab1:
st.subheader("Sticker")
# Allow the user to upload an image
uploaded_image = st.file_uploader(
"Choose an image file to print", type=["png", "jpg", "gif", "webp"]
)
# Initialize a variable for the image to be processed
image_to_process = None
filename = None # To hold the filename without extension
# Check if an image has been uploaded
if uploaded_image is not None:
# Convert the uploaded file to a PIL Image
image_to_process = Image.open(uploaded_image).convert("RGB")
filename = os.path.splitext(uploaded_image.name)[0]
# Get the original filename without extension
original_filename_without_extension = (
os.path.splitext(uploaded_image.name)[0]
if uploaded_image
else "selected_image"
)
# grayimage = add_white_background_and_convert_to_grayscale(image_to_process)
grayscale_image, dithered_image = preper_image(image_to_process)
# Paths to save the original and dithered images in the 'temp' directory with postfix
original_image_path = os.path.join(
"temp", original_filename_without_extension + "_original.png"
)
# Create checkboxes for rotation and dithering (dither default to True) inline
col1, col2 = st.columns(2)
with col1:
dither_checkbox = st.checkbox(
"Dither - _use for high detail, true by default_", value=True
)
with col2:
rotate_checkbox = st.checkbox("Rotate - _90 degrees_")
# Determine the button text based on checkbox states
button_text = "Print "
if rotate_checkbox:
button_text += "Rotated "
if dither_checkbox:
button_text += "Dithered "
button_text += "Image"
# Create a single button with dynamic text
if st.button(button_text):
rotate_value = 90 if rotate_checkbox else 0
dither_value = dither_checkbox
print_image(image_to_process, rotate=rotate_value, dither=dither_value)
# Display image based on checkbox status
if dither_checkbox:
st.image(dithered_image, caption="Resized and Dithered Image")
else:
st.image(image_to_process, caption="Original Image")
# Create 'temp' directory if it doesn't exist
os.makedirs("temp", exist_ok=True)
# Save original image
image_to_process.save(original_image_path, "PNG")
# label
with tab2:
st.subheader(":printer: a label")
img = ""
# Function to calculate the actual image height based on the bounding boxes of each line
def calculate_actual_image_height_with_empty_lines(text, font, line_spacing=10):
draw = ImageDraw.Draw(
Image.new("RGB", (1, 1), color="white")
) # Dummy image for calculation
total_height = 0
# Get font metrics for consistent spacing
ascent, descent = font.getmetrics()
font_height = ascent + descent
for line in text.split("\n"):
if line.strip(): # Non-empty lines
# Use textbbox for more accurate measurements
bbox = draw.textbbox((0, 0), line, font=font)
text_height = max(
bbox[3] - bbox[1], font_height
) # Use the larger of bbox height or font height
else: # Empty lines
text_height = font_height
total_height += text_height + line_spacing
# Add padding at top and bottom
padding = 20
return total_height + (padding * 2) # Add padding to total height
# Function to calculate the maximum font size based on the width of the longest line
def calculate_max_font_size(
width, text, font_path, start_size=10, end_size=200, step=1
):
try:
draw = ImageDraw.Draw(
Image.new("RGB", (1, 1), color="white")
) # Dummy image for calculation
max_font_size = start_size
for size in range(start_size, end_size, step):
try:
font = ImageFont.truetype(font_path, size)
except OSError:
# If can't load font, use default
return 50 # Return reasonable default size
adjusted_lines = []
for line in text.split("\n"):
adjusted_lines.append(line)
max_text_width = max(
[
draw.textbbox((0, 0), line, font=font)[2]
for line in adjusted_lines
if line.strip()
]
)
if max_text_width <= width:
max_font_size = size
else:
break
return max_font_size
except Exception as e:
print(f"Error in calculate_max_font_size: {e}")
return 50 # Return reasonable default size if anything fails
# Multiline Text Input
text = st.text_area("Enter your text to print", "write something\n", height=200)
# Check if the text has been changed by the user
if text:
urls = find_url(text)
if urls:
st.success("Found URLs: we might automate the QR code TODO")
for url in urls:
st.write(url)
# init some font vars
fonts = get_fonts()
font = fonts[0] # Default to first available font
alignment = "center"
# Initialize font selection in session state if not already present
if "selected_font" not in st.session_state:
st.session_state.selected_font = fonts[0]
try:
# Try to load the font
test_font = ImageFont.truetype(font, 12)
except OSError:
st.error("5x5-Tami.ttf font not found! Please ensure the fonts directory exists and contains 5x5-Tami.ttf")
st.info("You can download it from the project repository")
font = None # Mark font as unavailable
if font is None:
st.stop() # Stop execution if font is not available
# Calculate initial max size with default font
try:
# Get the longest line length
chars_per_line = max(len(line) for line in text.split('\n'))
if chars_per_line == 0:
chars_per_line = 1
print(f"Debug font sizing:")
print(f"- Label type: {label_type}")
print(f"- Label width: {label_width} dots")
print(f"- Longest line: {chars_per_line} characters")
# Base sizes for different label types
if label_type == "62": # 62mm label
base_font_size = 60
base_width = 696
elif label_type == "102": # 102mm label
base_font_size = 107
base_width = 1164
else:
# For other sizes, scale from 62mm base
base_font_size = 60
base_width = 696
# First scale based on width ratio
width_scale = label_width / base_width
scaled_base_size = int(base_font_size * width_scale)
# Then scale based on text length (14 chars is our reference)
base_text_length = 14 # "write something" length
text_scale = base_text_length / chars_per_line
font_size = int(scaled_base_size * text_scale)
# Ensure minimum size of 20
font_size = max(font_size, 20)
print(f"- Base font size: {base_font_size}")
print(f"- Width scale: {width_scale:.2f}")
print(f"- Text scale: {text_scale:.2f}")
print(f"- Final font size: {font_size}")
max_size = font_size
except Exception as e:
max_size = 60 # Default to known good size for 62mm
font_size = max_size
print(f"Error calculating font size: {e}")
# After font size is set, print debug info about the final text layout
print(f"\nFinal text layout:")
print(f"- Font: {font}")
print(f"- Font size: {font_size}")
print(f"- Label width: {label_width}")
print(f"- Text: {text}")
fontstuff = st.checkbox("font settings", value=False)
col1, col2 = st.columns(2)
if fontstuff:
# Font Selection with session state
with col1:
font = st.selectbox(
"Choose your font",
fonts,
index=fonts.index(st.session_state.selected_font),
)
st.session_state.selected_font = font
# Alignment
with col2:
alignment_options = ["left", "center", "right"]
alignment = st.selectbox(
"Choose text alignment", alignment_options, index=1
)
# Recalculate max size if font changed
try:
if font == "fonts/5x5-Tami.ttf":
chars_per_line = max(len(line) for line in text.split('\n'))
if chars_per_line == 0:
chars_per_line = 1
# Use same calculation as above for consistency
if label_type == "62": # 62mm label
font_size = 60
elif label_type == "102": # 102mm label
font_size = 107
else:
# For other sizes, scale based on width ratio from 62mm label
base_width = 696 # Width of 62mm label
width_scale = label_width / base_width
font_size = int(60 * width_scale) # Scale from base size of 60
print(f"Font size recalculated:")
print(f"- Label type: {label_type}")
print(f"- Label width: {label_width} dots")
print(f"- Font size: {font_size}")
max_size = font_size
else:
max_size = calculate_max_font_size(label_width, text, font)
except Exception as e:
print(f"Error calculating font size for {font}: {e}")
font_size = st.slider("Font Size", 20, max_size + 50, max_size)
# Font Size
try:
fnt = ImageFont.truetype(font, font_size)
except OSError:
# If the 5x5 font is not found, try to use default system font
try:
fnt = ImageFont.load_default()
st.warning(f"Font {font} not found, using default font. Please ensure fonts/5x5-Tami.ttf exists.")
except Exception as e:
st.error(f"Error loading font: {e}")
line_spacing = 20 # Adjust this value to set the desired line spacing
# Calculate the new image height based on the bounding boxes
new_image_height = calculate_actual_image_height_with_empty_lines(
text, fnt, line_spacing
)
# Create Image with padding
padding = 20 # Consistent with the padding in calculate_actual_image_height
img = Image.new("RGB", (label_width, new_image_height), color="white")
d = ImageDraw.Draw(img)
# Adjust starting y position to account for padding
y = padding # Start from padding instead of 5
# Draw Text
for line in text.split("\n"):
text_width = 0
ascent, descent = fnt.getmetrics()
font_height = ascent + descent
if line.strip(): # For non-empty lines
bbox = d.textbbox((0, y), line, font=fnt)
text_width = bbox[2] - bbox[0]
text_height = max(bbox[3] - bbox[1], font_height)
else: # For empty lines
text_height = font_height
if alignment == "center":
x = (label_width - text_width) // 2
elif alignment == "right":
x = label_width - text_width
else:
x = 0
d.text((x, y), line, font=fnt, fill=(0, 0, 0))
y += text_height + line_spacing
# Save the label image
if text != "write something":
filename = safe_filename(text)
file_path = os.path.join(label_dir, filename)
img.save(file_path, "PNG")
st.success(f"Label saved as {filename}")
# QR code
qr = qrcode.QRCode(border=0)