-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrentv2.py
More file actions
executable file
·3497 lines (2946 loc) · 133 KB
/
Currentv2.py
File metadata and controls
executable file
·3497 lines (2946 loc) · 133 KB
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 sys, locale
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
import certifi
import os
import tempfile # For creating temporary files
import usb.core
import usb.backend.libusb1
import pandas as pd
import json
import requests
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, session, send_file, render_template_string
from PIL import Image, ImageDraw, ImageFont
# Brother QL imports (ensure these are installed: brother_ql, pyusb, libusb1)
try:
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
from brother_ql.raster import BrotherQLRaster
except ImportError:
print("Warning: brother_ql, pyusb, or libusb1 not installed.")
print("Printing functionality will be disabled.")
print("Install with: pip install brother_ql pyusb libusb1")
# Define dummy functions if imports fail, so the app can still run
# (though printing won't work)
def convert(*args, **kwargs):
print("brother_ql not imported. Printing disabled.")
return []
def send(*args, **kwargs):
print("brother_ql not imported. Printing disabled.")
class BrotherQLRaster:
def __init__(self, model):
self.exception_on_warning = True
app = Flask(__name__)
app.secret_key = os.urandom(24) # Keep this unique and secret
# ==========================================
# CONFIGURATION & STATE
CONFIG_FILE = "app_config.json" # File to store configuration
CONFIG = {} # Dictionary to hold current configuration
ADMIN_PASSWORD = "admin" # Update the admin password as needed
# Use a Windows-compatible temporary directory
TEMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'temp')
os.makedirs(TEMP_DIR, exist_ok=True)
# Shopify Configuration (These could also go into config.json if preferred)
STORE_DOMAIN = "homestead-gristmill.myshopify.com"
ACCESS_TOKEN = "REPLACE_ME" # Masked for security before pushing to GitHub
API_VERSION = "2024-01"
LOCATION_ID_GID = "gid://shopify/Location/79621390578" # Verified GID for the location
GRAPHQL_URL = f"https://{STORE_DOMAIN}/admin/api/{API_VERSION}/graphql.json"
HEADERS = {
"Content-Type": "application/json",
"X-Shopify-Access-Token": ACCESS_TOKEN
}
# Print Job State
cancel_print_flag = False
printing_in_progress = False
current_progress = 0
total_to_print = 0
# We'll keep a global reference to the spreadsheet data once loaded
SPREADSHEET_DATA = pd.DataFrame()
# ---------------- DEBUG BUS -------------------------------------
LAST_JOB_LOG: list[str] = [] # keeps the last ~150 lines
def dbg(msg: str):
"""Collect + echo debug lines with timestamp."""
from datetime import datetime
ts = datetime.now().strftime("%H:%M:%S")
line = f"[{ts}] {msg}"
print(line) # still shows up in journalctl
LAST_JOB_LOG.append(line)
if len(LAST_JOB_LOG) > 150:
LAST_JOB_LOG.pop(0)
# ----------------------------------------------------------------
# ==========================================
# CONFIG FILE MANAGEMENT
def load_config():
"""Loads configuration from config.json."""
global CONFIG
default_config = {
'spreadsheet_file': os.path.abspath('data.xlsx'), # Default to data.xlsx in the script directory
'logo_path': '', # Default empty, user must set
'barcode_folder': os.path.abspath('barcodes'), # Default to 'barcodes' folder in script directory
'front_label_folder': os.path.abspath('frontlabels'), # Default to 'frontlabels' folder in script directory
'back_label_folder': os.path.abspath('backlabels'), # Default to 'backlabels' folder in script directory
'font_path_regular': '', # Default empty, user must set
'font_path_price': '', # Default empty, user must set
}
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
CONFIG = json.load(f)
# Merge with defaults in case new keys are added later
CONFIG = {**default_config, **CONFIG}
print(f"Loaded configuration from {CONFIG_FILE}")
else:
CONFIG = default_config
print(f"No {CONFIG_FILE} found. Using default configuration.")
save_config(CONFIG) # Save default config on first run
# Ensure barcode folder exists
if CONFIG.get('barcode_folder') and not os.path.exists(CONFIG['barcode_folder']):
try:
os.makedirs(CONFIG['barcode_folder'])
print(f"Created barcode folder: {CONFIG['barcode_folder']}")
except OSError as e:
print(f"Error creating barcode folder {CONFIG['barcode_folder']}: {e}")
# Optionally set to empty if creation fails critically?
# CONFIG['barcode_folder'] = '' # Consider how to handle this error gracefully
# Ensure front label folder exists
if CONFIG.get('front_label_folder') and not os.path.exists(CONFIG['front_label_folder']):
try:
os.makedirs(CONFIG['front_label_folder'])
print(f"Created front label folder: {CONFIG['front_label_folder']}")
except OSError as e:
print(f"Error creating front label folder {CONFIG['front_label_folder']}: {e}")
# Ensure back label folder exists
if CONFIG.get('back_label_folder') and not os.path.exists(CONFIG['back_label_folder']):
try:
os.makedirs(CONFIG['back_label_folder'])
print(f"Created back label folder: {CONFIG['back_label_folder']}")
except OSError as e:
print(f"Error creating back label folder {CONFIG['back_label_folder']}: {e}")
except (IOError, json.JSONDecodeError) as e:
print(f"Error loading configuration: {e}")
CONFIG = default_config # Fallback to defaults on error
def save_config(config_dict):
"""Saves configuration to config.json."""
try:
with open(CONFIG_FILE, 'w') as f:
json.dump(config_dict, f, indent=4)
print(f"Saved configuration to {CONFIG_FILE}")
except IOError as e:
print(f"Error saving configuration: {e}")
# ==========================================
# SHOPIFY INVENTORY FUNCTIONS (Unchanged - kept for context)
def execute_graphql_query(query, variables):
"""Sends a GraphQL query or mutation to the Shopify API."""
data = {"query": query, "variables": variables}
try:
response = requests.post(
GRAPHQL_URL,
headers=HEADERS,
# --- TEMPORARY: Disable SSL Verification ---
# This is INSECURE and for debugging the certificate issue ONLY.
# Revert to verify=certifi.where() or a proper solution ASAP.
verify=False,
# --- End TEMPORARY ---
timeout=10,
data=json.dumps(data)
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"HTTP Request failed: {e}")
try:
# Access response text defensively
error_details = e.response.text if e.response else "No response details available."
except Exception:
error_details = "No response details available (error accessing response)."
return {"errors": [{"message": f"Request failed: {e}", "details": error_details}]}
except json.JSONDecodeError:
# Add defensive check for response existence and text
response_text = response.text if 'response' in locals() and response else "No response text available."
return {"errors": [{"message": "Failed to decode JSON response", "details": response_text}]}
except Exception as e:
# Catch any other unexpected errors
print(f"An unexpected error occurred during GraphQL query: {e}")
return {"errors": [{"message": f"An unexpected error occurred: {str(e)}"}]}
def get_inventory_item_id_by_sku(sku):
"""Finds the Inventory Item GID for a given SKU."""
query = """
query getInventoryItemBySku($skuQuery: String!) {
productVariants(first: 1, query: $skuQuery) {
edges {
node {
inventoryItem {
id
}
}
}
}
}
"""
sku_query_string = f"sku:'{sku}'"
variables = {"skuQuery": sku_query_string}
result = execute_graphql_query(query, variables)
if "errors" in result:
print(f"GraphQL Error fetching inventory item ID: {result['errors']}")
return None
try:
edges = result.get("data", {}).get("productVariants", {}).get("edges", [])
if not edges:
print(f"No product variant found for SKU: {sku}")
return None
inventory_item_id = edges[0].get("node", {}).get("inventoryItem", {}).get("id")
if not inventory_item_id:
print(f"Variant found for SKU {sku}, but it has no inventory item associated.")
return None
return inventory_item_id
except (AttributeError, IndexError, TypeError) as e:
print(f"Error parsing GraphQL response for SKU {sku}: {e}")
print(f"Full response data: {result.get('data')}")
return None
def get_current_quantity(inventory_item_id, location_id_gid):
"""Fetches the current 'available' quantity for an item at a specific location."""
query = """
query getCurrentQuantity($inventoryItemId: ID!) {
inventoryItem(id: $inventoryItemId) {
id
inventoryLevels(first: 10) {
edges {
node {
location {
id
}
quantities(names: ["available"]) {
name
quantity
}
}
}
}
}
}
"""
variables = {"inventoryItemId": inventory_item_id}
result = execute_graphql_query(query, variables)
if "errors" in result:
print(f"GraphQL Error fetching current quantity: {result['errors']}")
return None
try:
inventory_item_data = result.get("data", {}).get("inventoryItem")
if not inventory_item_data:
print(f"No inventory item data found for ID: {inventory_item_id}")
return None
inventory_levels = inventory_item_data.get("inventoryLevels", {}).get("edges", [])
for edge in inventory_levels:
level_node = edge.get("node", {})
level_location_id = level_node.get("location", {}).get("id")
# Check if this inventory level matches the desired location
if level_location_id == location_id_gid:
quantities = level_node.get("quantities", [])
for qty_info in quantities:
if qty_info.get("name") == "available":
return int(qty_info.get("quantity", 0)) # Return the available quantity
# If loop finishes without finding the location
print(f"Inventory level for location {location_id_gid} not found for item {inventory_item_id}.")
return None # Indicate location not found for this item
except (AttributeError, IndexError, TypeError, ValueError) as e:
print(f"Error parsing quantity response for item {inventory_item_id}: {e}")
print(f"Full response data: {result.get('data')}")
return None
def update_inventory_quantity(inventory_item_id, location_id_gid, new_quantity, current_quantity):
"""Adjusts the available inventory quantity for an item at a location."""
adjustment_quantity = new_quantity - current_quantity
# Using inventoryAdjustQuantities mutation
mutation = """
mutation inventoryAdjustQuantities($input: InventoryAdjustQuantitiesInput!) {
inventoryAdjustQuantities(input: $input) {
inventoryAdjustmentGroup {
createdAt
reason
changes {
name
delta
}
}
userErrors {
field
message
}
}
}
"""
variables = {
"input": {
"name": "available",
"reason": "correction",
"changes": [
{
"delta": adjustment_quantity,
"inventoryItemId": inventory_item_id,
"locationId": location_id_gid
}
]
}
}
result = execute_graphql_query(mutation, variables)
if "errors" in result:
print(f"GraphQL Execution Error updating inventory: {result['errors']}")
return False
mutation_result = result.get("data", {}).get("inventoryAdjustQuantities", {})
user_errors = mutation_result.get("userErrors", [])
if user_errors:
print("Shopify User Errors occurred during update:")
for error in user_errors:
print(f"- Field: {error.get('field')}, Message: {error.get('message')}")
return False
adjustment_group = mutation_result.get("inventoryAdjustmentGroup")
if adjustment_group:
changes = adjustment_group.get("changes", [])
print("\n--- Inventory Update Successful ---")
print(f"Location: {location_id_gid}")
for change in changes:
if change.get("name") == "available":
delta = change.get("delta", 0)
print(f"Change Applied: {delta:+d} units")
# The mutation returns the *change* applied, not the final quantity
# We could fetch the current quantity again, but for simplicity,
# report based on the requested change.
# print(f"New Available Quantity (estimated): {current_quantity + delta}")
return True
else:
print("Update might have failed or response format unexpected.")
print(f"Full response data: {result.get('data')}")
return False
def update_shopify_inventory_after_printing(sku, quantity_printed):
"""Update Shopify inventory after printing labels - ADDS the printed quantity to inventory."""
if not sku:
print("Cannot update inventory: No SKU provided")
return False, "No SKU provided"
# Get the inventory item ID for this SKU
inventory_item_id = get_inventory_item_id_by_sku(sku)
if not inventory_item_id:
return False, f"SKU {sku} not found in Shopify"
# Get current quantity
current_quantity = get_current_quantity(inventory_item_id, LOCATION_ID_GID)
if current_quantity is None:
# get_current_quantity already printed error message
return False, f"Could not retrieve current quantity for SKU {sku}"
# Calculate new quantity (ADD printed quantity)
new_quantity = current_quantity + quantity_printed
# Update the inventory
# Pass current_quantity to the update function so it can calculate delta
success = update_inventory_quantity(inventory_item_id, LOCATION_ID_GID, new_quantity, current_quantity)
if success:
# Message generated by update_inventory_quantity is more detailed
return True, f"Updated inventory for SKU {sku}: added {quantity_printed}" # Simpler success message
else:
# Error message printed by update_inventory_quantity
return False, f"Failed to update inventory for SKU {sku}" # Simpler failure message
# ==========================================
# HELPER FUNCTIONS
def apply_offset(img: Image.Image, dx_px: int, dy_px: int,
canvas_w: int, canvas_h: int) -> Image.Image:
"""
Paste *img* onto a blank canvas of *canvas_w × canvas_h* pixels,
shifted by (dx_px, dy_px). Anything that would fall outside the canvas
is clipped.
"""
canvas = Image.new("RGB", (canvas_w, canvas_h), "white")
canvas.paste(img, (dx_px, dy_px))
return canvas
def load_spreadsheet():
"""Load and validate spreadsheet data with robust type checking and cleanup."""
global CONFIG # Use the global config
spreadsheet_file = CONFIG.get('spreadsheet_file')
if not spreadsheet_file:
print("Error: Spreadsheet file path not configured.")
return pd.DataFrame()
try:
if not os.path.exists(spreadsheet_file):
print(f"Error: Spreadsheet file not found at {spreadsheet_file}")
return pd.DataFrame()
print(f"Attempting to load spreadsheet from {spreadsheet_file}")
df = pd.read_excel(
spreadsheet_file,
dtype={
'Product': str,
'Variant': str,
'SKU': str,
'BarcodePath': str, # Expecting filename now
'FrontLabels': str, # Add this line
'FrontLabelFiles': str # Add this line
}
)
print("Spreadsheet loaded.")
# Validate required columns
required = ['Product', 'Variant', 'Price', 'Timeframe', 'BarcodePath', 'SKU']
if not all(col in df.columns for col in required):
missing = [col for col in required if col not in df.columns]
print(f"Error: Missing required columns in spreadsheet: {missing}")
return pd.DataFrame()
# Clean string columns except FrontLabels which needs special handling
string_cols = ['Product', 'Variant', 'BarcodePath', 'SKU', 'FrontLabelFiles']
for col in string_cols:
if col in df.columns: # Check if column exists before processing
df[col] = df[col].astype(str).str.strip().replace(r'\s+', ' ', regex=True)
else:
df[col] = '' # Add missing column with default empty strings
# Handle FrontLabels column specially to preserve True/False values
if 'FrontLabels' in df.columns:
# Convert to proper string 'True'/'False' values
df['FrontLabels'] = df['FrontLabels'].astype(str)
# Normalize to ensure consistent case - 'True' or 'False'
df['FrontLabels'] = df['FrontLabels'].apply(
lambda x: 'True' if x.strip().lower() == 'true' else 'False'
)
else:
df['FrontLabels'] = 'False' # Default value if column missing
# Convert numeric columns with error handling
df['Price'] = pd.to_numeric(df['Price'], errors='coerce')
df['Timeframe'] = pd.to_numeric(df['Timeframe'], errors='coerce').fillna(0).astype(int)
# Drop rows where essential data is missing (Product, Variant, Price, Barcode filename)
initial_count = len(df)
df = df.dropna(subset=['Product', 'Variant', 'Price', 'BarcodePath'])
# Also drop if BarcodePath is an empty string after stripping
df = df[df['BarcodePath'] != ''].reset_index(drop=True)
cleaned_count = len(df)
# Check for duplicates (optional but good practice)
duplicates = df.duplicated(subset=['Product', 'Variant'], keep=False)
if duplicates.any():
dup_count = duplicates.sum()
print(f"Warning: Found {dup_count} duplicate Product/Variant combinations.")
if df.empty:
print("No valid data remaining after cleanup.")
return pd.DataFrame()
print(f"Loaded {cleaned_count}/{initial_count} valid items from spreadsheet.")
# Include all columns, not just required ones, to ensure front label columns are preserved
return df.reset_index(drop=True)
except Exception as e:
print(f"Critical error loading spreadsheet: {str(e)}")
return pd.DataFrame()
def calculate_dates(timeframe):
"""Calculates Best By and Julian dates based on timeframe in years."""
try:
timeframe_days = int(timeframe) * 365
except (ValueError, TypeError):
print(f"Warning: Invalid timeframe '{timeframe}'. Using 0 years.")
timeframe_days = 0
current_date = datetime.now()
best_by_date = current_date + timedelta(days=timeframe_days)
# Julian date is 1 year prior to the best-by date
julian_year_back = best_by_date - timedelta(days=365)
# Format is DayOfYearYear (e.g., 00124 for Jan 1, 2024)
julian_date = julian_year_back.strftime("%j") + julian_year_back.strftime("%y")[-2:]
return best_by_date.strftime("%y-%m-%d"), julian_date
# Modified to accept barcode_filename and use CONFIG['barcode_folder']
def create_label_image(best_by, price, julian, barcode_filename):
"""Creates the label image."""
global CONFIG # Use global config
label_width = 991
label_height = 306
image = Image.new("RGB", (label_width, label_height), "white")
draw = ImageDraw.Draw(image)
logo_path = CONFIG.get('logo_path')
if logo_path and os.path.exists(logo_path):
try:
logo = Image.open(logo_path).convert("L")
logo = logo.resize((500, 245))
image.paste(logo, (0, 0))
except Exception as e:
print(f"Error loading or pasting logo from {logo_path}: {e}")
# Load fonts from configured paths
font_regular_path = CONFIG.get('font_path_regular')
font_price_path = CONFIG.get('font_path_price')
font_regular = ImageFont.load_default() # Fallback
font_price = ImageFont.load_default() # Fallback
try:
if font_regular_path and os.path.exists(font_regular_path):
font_regular = ImageFont.truetype(font_regular_path, 35)
else:
print(f"Warning: Regular font not found at {font_regular_path}. Using default.")
# Attempt to load common system fonts if config fails
try:
# Check common Linux paths
font_regular = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 35)
print("Using DejavuSans as fallback regular font.")
except OSError:
try:
# Check common Windows paths (less likely for server but good fallback)
font_regular = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 35)
print("Using Arial as fallback regular font.")
except OSError:
pass # Stick to default if system fonts fail
except OSError:
print(f"Warning: Could not load TrueType font from {font_regular_path}. Using default.")
font_regular = ImageFont.load_default()
try:
if font_price_path and os.path.exists(font_price_path):
font_price = ImageFont.truetype(font_price_path, 56)
else:
print(f"Warning: Price font not found at {font_price_path}. Using default.")
# Attempt to load common system fonts if config fails
try:
font_price = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 56)
print("Using DejavuSans-Bold as fallback price font.")
except OSError:
try:
font_price = ImageFont.truetype("C:/Windows/Fonts/arialbd.ttf", 56) # Arial Bold
print("Using Arial Bold as fallback price font.")
except OSError:
pass # Stick to default if system fonts fail
except OSError:
print(f"Warning: Could not load TrueType font from {font_price_path}. Using default.")
font_price = ImageFont.load_default()
best_by_text = best_by
price_text = f"${float(price):.2f}" # Ensure price is treated as float
julian_text = julian
# Calculate text widths
bw = draw.textlength(best_by_text, font=font_regular)
pw = draw.textlength(price_text, font=font_price)
jw = draw.textlength(julian_text, font=font_regular)
spacing = 20
text_area_width = 450 # Area next to logo
# Position text block
# Calculate Y position - bottom aligned
best_by_bbox = draw.textbbox((0, 0), best_by_text, font=font_regular)
price_bbox = draw.textbbox((0, 0), price_text, font=font_price)
julian_bbox = draw.textbbox((0, 0), julian_text, font=font_regular)
# Find the lowest point among the text elements to align bottoms
max_text_height = max(best_by_bbox[3] - best_by_bbox[1],
price_bbox[3] - price_bbox[1],
julian_bbox[3] - julian_bbox[1])
# Base line for the text block - slightly above the bottom edge
text_baseline_y = label_height - 25 # Adjust padding from bottom
# Y positions adjusted for baseline alignment (approximate)
best_by_y = text_baseline_y - (best_by_bbox[3] - best_by_bbox[1]) # Align top based on height difference
price_y = text_baseline_y - (price_bbox[3] - price_bbox[1])
julian_y = text_baseline_y - (julian_bbox[3] - julian_bbox[1])
# Calculate total width if placed side-by-side with spacing
total_combined_width = bw + pw + jw + (2 * spacing)
# Determine starting X position for the text block
left_margin = 10
if total_combined_width < text_area_width:
# Center within the text area if it fits
start_x = left_margin + (text_area_width - total_combined_width) // 2
else:
# Start from the left margin if it's too wide
start_x = left_margin
# Draw text
current_x = start_x
draw.text((current_x, best_by_y), best_by_text, fill="black", font=font_regular)
current_x += bw + spacing
draw.text((current_x, price_y), price_text, fill="black", font=font_price)
current_x += pw + spacing
draw.text((current_x, julian_y), julian_text, fill="black", font=font_regular)
# Barcode image
barcode_folder = CONFIG.get('barcode_folder')
full_barcode_path = None
if barcode_folder and barcode_filename:
full_barcode_path = os.path.join(barcode_folder, barcode_filename)
if full_barcode_path and os.path.exists(full_barcode_path):
try:
barcode_img = Image.open(full_barcode_path).convert("L")
# Resize barcode to fit right side
barcode_desired_width = 500
barcode_desired_height = 285 # Leave some space at the bottom
# Maintain aspect ratio while fitting within desired area
original_width, original_height = barcode_img.size
aspect_ratio = original_width / original_height
# Calculate new size trying to fit width first
new_width = barcode_desired_width
new_height = int(new_width / aspect_ratio)
# If fitting width makes height too large, fit height instead
if new_height > barcode_desired_height:
new_height = barcode_desired_height
new_width = int(new_height * aspect_ratio)
# Ensure dimensions are at least 1x1
new_width = max(1, new_width)
new_height = max(1, new_height)
barcode_img = barcode_img.resize((new_width, new_height))
# Position barcode - centered vertically on the right side
barcode_x = label_width - new_width - 10 # 10px padding from right
barcode_y = (label_height - new_height) // 2
image.paste(barcode_img, (barcode_x, barcode_y))
except Exception as e:
print(f"Error loading or pasting barcode from {full_barcode_path}: {e}")
else:
if barcode_filename: # Only warn if a filename was expected
print(f"Warning: Barcode file not found at {full_barcode_path or 'None'}. Barcode area will be blank.")
# Save the image to our Windows-compatible temp directory
temp_path = os.path.join(TEMP_DIR, "temp_label.png")
try:
image.save(temp_path)
print(f"Label image saved to {temp_path}")
return temp_path
except Exception as e:
print(f"Error saving temporary label image: {e}")
return None # Return None if image saving fails
def send_to_printer(image_path):
"""Send the label image to the Brother QL-800 printer."""
if not image_path or not os.path.exists(image_path):
print(f"Error: Cannot print. Image file not found at {image_path}")
return False # Return False on failure
# --- START: Find Printer ---
try:
# Ensure libusb1 backend is available on Windows
backend = usb.backend.libusb1.get_backend()
if backend is None:
print("libusb1 backend not found. Ensure libusb is installed and configured.")
return False
# Use the backend object when finding the device
printer_handle = usb.core.find(idVendor=0x04f9, idProduct=0x209b, backend=backend)
if printer_handle is None:
print("Printer not found over USB (VID: 0x04f9, PID: 0x209b).")
print("Make sure the printer is connected and the driver was replaced using Zadig.")
return False
# Detach kernel driver if needed (often required on Linux, might not be on Windows)
# You might need to experiment with this line on Windows
# try:
# printer_handle.detach_kernel_driver(0)
# except usb.core.USBError:
# pass # Ignore if no kernel driver attached
# Set configuration (often needed after finding device)
# try:
# printer_handle.set_configuration()
# except usb.core.USBError as e:
# print(f"Failed to set USB configuration: {e}")
# # Depending on error, might need to re-attach driver? Or it's already claimed.
# # This is a complex USB detail. If printing fails, this might be a place to investigate.
# pass # Continue and hope it works
except Exception as e:
print(f"Error finding or configuring USB printer: {e}")
return False # Return False on failure
# --- END: Find Printer ---
try:
im = Image.open(image_path).resize((991, 306))
im = apply_offset(im, -15, -24, 991, 306) # 35 px left, 24 px up (moved right by 12px)
qlr = BrotherQLRaster('QL-800')
qlr.exception_on_warning = True
instructions = convert(
qlr=qlr,
images=[im],
label='29x90', # Or your actual label size, e.g., '62' for 62mm
rotate='90',
threshold=70.0,
dither=False,
compress=False,
cut=True
)
send(instructions, printer_handle, 'pyusb')
print("Print job sent to Brother QL-800.")
return True
except Exception as e:
print(f"Print error for Brother QL-800: {e}")
return False
import win32print, win32ui, win32con
from PIL import Image, ImageWin
def send_to_epson(image_path, copies=1, extra_left_mm=0):
# Configure printer name - use the exact printer name from Windows
printer_name = "EPSON CW-C6500Au"
# Open the image file
img = Image.open(image_path)
img = img.convert("RGB") # Ensure no alpha channel or palette issues
# Process for each copy requested
for _ in range(max(1, copies)):
# Open a handle to the printer
hPrinter = win32print.OpenPrinter(printer_name)
try:
# Get printer settings (DEVMODE) – can be modified if needed
properties = win32print.GetPrinter(hPrinter, 2)
devmode = properties["pDevMode"]
# e.g., to force a specific paper or orientation (optional):
# devmode.Orientation = 2 # 1 = Portrait, 2 = Landscape
# devmode.PaperSize = 1 # e.g., 1 = Letter, etc. (driver-defined for labels)
# devmode fields can be changed before creating the DC
# Create a Device Context (DC) for the printer using the driver settings
hDC = win32ui.CreateDC()
hDC.CreatePrinterDC(printer_name) # (Alternatively, win32gui.CreateDC with devmode)
# Get printable area (HORZRES/VERTRES) and total paper size (PHYSICALWIDTH/HEIGHT)
printable_area = (hDC.GetDeviceCaps(win32con.HORZRES),
hDC.GetDeviceCaps(win32con.VERTRES))
physical_size = (hDC.GetDeviceCaps(win32con.PHYSICALWIDTH),
hDC.GetDeviceCaps(win32con.PHYSICALHEIGHT))
# Get printer margins (PHYSICALOFFSETX/Y). Typically small or zero for label printers.
offsets = (hDC.GetDeviceCaps(win32con.PHYSICALOFFSETX),
hDC.GetDeviceCaps(win32con.PHYSICALOFFSETY))
# Apply extra left margin if specified (converted from mm to pixels)
dpi = hDC.GetDeviceCaps(win32con.LOGPIXELSX)
extra_px = int((extra_left_mm / 25.4) * dpi)
# Rotate image if it better fits the orientation of the label
if img.width > img.height and printable_area[0] < printable_area[1]:
img = img.rotate(90, expand=True)
elif img.width < img.height and printable_area[0] > printable_area[1]:
img = img.rotate(90, expand=True)
# Scale the image to max size within printable area
scale_x = printable_area[0] / img.width
scale_y = printable_area[1] / img.height
scale = min(scale_x, scale_y)
new_width = int(img.width * scale)
new_height = int(img.height * scale)
# Center the image within the total physical page (so margins are accounted for)
# Start coordinates (top-left) for centering:
x = (physical_size[0] - new_width) // 2 + extra_px # Add extra_px to shift left if needed
y = (physical_size[1] - new_height) // 2
# Start the print job and draw the image
hDC.StartDoc("Python Label Print")
hDC.StartPage()
dib = ImageWin.Dib(img)
dib.draw(hDC.GetHandleOutput(), (x, y, x + new_width, y + new_height))
hDC.EndPage()
hDC.EndDoc()
hDC.DeleteDC()
finally:
win32print.ClosePrinter(hPrinter)
def create_front_label(front_label_filename):
"""Creates a front label image."""
global CONFIG
front_label_folder = CONFIG.get('front_label_folder')
# Enhanced debugging output
print(f"Front label function called with filename: '{front_label_filename}'")
print(f"Front label folder from config: '{front_label_folder}'")
# Check for empty values
if not front_label_folder:
print("ERROR: front_label_folder not set in configuration")
return None
if not front_label_filename or pd.isna(front_label_filename) or front_label_filename.strip() == '':
print("ERROR: front_label_filename is empty or NaN")
return None
# Ensure filename is a string and clean it
front_label_filename = str(front_label_filename).strip()
# Construct full path
full_front_label_path = os.path.join(front_label_folder, front_label_filename)
print(f"Constructed full front label path: '{full_front_label_path}'")
# Check if file exists
if not os.path.exists(full_front_label_path):
print(f"ERROR: Front label file not found at '{full_front_label_path}'")
# List files in directory to help with debugging
try:
files = os.listdir(front_label_folder)
print(f"Files in front label folder: {files}")
except Exception as list_err:
print(f"Could not list directory contents: {str(list_err)}")
return None
try:
# Attempt to open and process the image
print(f"Attempting to open front label file: '{full_front_label_path}'")
front_image = Image.open(full_front_label_path)
print(f"Original image size: {front_image.size}, format: {front_image.format}")
# Resize the image
ROLL_DPI = 300
ROLL_WIDTH_IN = 3.5
ROLL_LEN_IN = 5.0
max_w = int(ROLL_WIDTH_IN * ROLL_DPI)
max_h = int(ROLL_LEN_IN * ROLL_DPI)
w, h = front_image.size
scale = min(max_w / w, max_h / h)
new_size = (int(w * scale), int(h * scale))
front_image = front_image.resize(new_size)
# Save temporary file to the Windows-compatible temp directory
temp_path = os.path.join(TEMP_DIR, "temp_front_label.png")
front_image.save(temp_path)
print(f"Front label image saved to temporary file: '{temp_path}'")
return temp_path
except Exception as e:
print(f"ERROR processing front label image: {str(e)}")
import traceback
traceback.print_exc() # Print full stack trace for debugging
return None
def create_back_label(back_label_filename):
"""Creates a back label image for Epson printing."""
global CONFIG
back_label_folder = CONFIG.get('back_label_folder')
# Enhanced debugging output
print(f"Back label function called with filename: '{back_label_filename}'")
print(f"Back label folder from config: '{back_label_folder}'")
# Check for empty values
if not back_label_folder:
print("ERROR: back_label_folder not set in configuration")
return None
if not back_label_filename or pd.isna(back_label_filename) or back_label_filename.strip() == '':
print("ERROR: back_label_filename is empty or NaN")
return None
# Ensure filename is a string and clean it
back_label_filename = str(back_label_filename).strip()
# Construct full path
full_back_label_path = os.path.join(back_label_folder, back_label_filename)
print(f"Constructed full back label path: '{full_back_label_path}'")
# Check if file exists
if not os.path.exists(full_back_label_path):
print(f"ERROR: Back label file not found at '{full_back_label_path}'")
# List files in directory to help with debugging
try:
files = os.listdir(back_label_folder)
print(f"Files in back label folder: {files}")
except Exception as list_err:
print(f"Could not list directory contents: {str(list_err)}")
return None
try:
# Attempt to open and process the image
print(f"Attempting to open back label file: '{full_back_label_path}'")
back_image = Image.open(full_back_label_path)
print(f"Original image size: {back_image.size}, format: {back_image.format}")
# Resize the image
ROLL_DPI = 300
ROLL_WIDTH_IN = 3.5
ROLL_LEN_IN = 5.0
max_w = int(ROLL_WIDTH_IN * ROLL_DPI)
max_h = int(ROLL_LEN_IN * ROLL_DPI)
w, h = back_image.size
scale = min(max_w / w, max_h / h)
new_size = (int(w * scale), int(h * scale))
back_image = back_image.resize(new_size)
# Save temporary file to the Windows-compatible temp directory
temp_path = os.path.join(TEMP_DIR, "temp_back_label.png")
back_image.save(temp_path)
print(f"Back label image saved to temporary file: '{temp_path}'")
return temp_path
except Exception as e:
print(f"ERROR processing back label image: {str(e)}")
import traceback
traceback.print_exc() # Print full stack trace for debugging
return None
def check_front_label_configuration():
"""Checks the configuration and spreadsheet for front label issues."""
global CONFIG, SPREADSHEET_DATA
print("\n--- Front Label Configuration Check ---")
# Check if front_label_folder is configured
front_label_folder = CONFIG.get('front_label_folder', '')
if not front_label_folder:
print("WARNING: front_label_folder is not configured in config.json")
print("Front label printing will not work until this is set.")
return
# Check if the folder exists
if not os.path.exists(front_label_folder):
print(f"WARNING: Configured front_label_folder does not exist: '{front_label_folder}'")
try:
os.makedirs(front_label_folder)
print(f"Created front label folder: '{front_label_folder}'")
except OSError as e:
print(f"ERROR: Failed to create front label folder: {e}")
print("Front label printing will not work until this folder is created.")
return
if SPREADSHEET_DATA.empty:
print("WARNING: Spreadsheet data not loaded. Cannot check front label columns.")
return