Repository navigation
Expand file tree
/
Copy pathprocessor.py
More file actions
817 lines (691 loc) Β· 31 KB
/
Copy pathprocessor.py
File metadata and controls
817 lines (691 loc) Β· 31 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
#!/usr/bin/env python3
"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QR Code Batch Image Processor v1.1 β
β Watermark product images with dynamically generated β
β QR codes containing the product SKU. β
β β
β Supports styled QR codes: classic, luxury, rose-gold, β
β midnight themes with optional containers and shadows. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Usage:
python processor.py # Use config.json defaults
python processor.py --input ./my_images # Custom input directory
python processor.py --workers 4 # Parallel processing
python processor.py --dry-run # Simulate without writing
python processor.py --skip-existing # Skip already processed files
python processor.py --theme rose-gold # Use rose-gold QR style
python processor.py --theme luxury --container # Luxury with container
"""
import argparse
import csv
import json
import os
import sys
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from PIL import Image, ImageDraw, ImageFilter, ImageOps
import qrcode
from qrcode.constants import ERROR_CORRECT_H
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers.pil import RoundedModuleDrawer
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Theme Definitions
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
THEMES = {
"classic": {
"fg_color": "#000000",
"bg_color": "#FFFFFF",
"rounded_modules": False,
"container": False,
},
"luxury": {
"fg_color": "#2D2D2D",
"bg_color": "#FFFFFF",
"rounded_modules": True,
"container": False,
},
"rose-gold": {
"fg_color": "#B76E79",
"bg_color": "#FFF9F5",
"rounded_modules": True,
"container": False,
},
"midnight": {
"fg_color": "#1B2838",
"bg_color": "#F8F9FA",
"rounded_modules": True,
"container": False,
},
"luxury-container": {
"fg_color": "#2D2D2D",
"bg_color": "#FFFFFF",
"rounded_modules": True,
"container": True,
},
"rose-gold-container": {
"fg_color": "#B76E79",
"bg_color": "#FFF9F5",
"rounded_modules": True,
"container": True,
},
"midnight-container": {
"fg_color": "#1B2838",
"bg_color": "#F8F9FA",
"rounded_modules": True,
"container": True,
},
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Default Configuration (fallback if config.json is missing)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DEFAULT_QR_STYLE = {
"theme": "classic",
"rounded_modules": False,
"container": False,
"container_padding_ratio": 0.15,
"container_radius": 16,
"shadow": True,
"shadow_blur": 10,
"shadow_opacity": 50,
"fg_color": "#000000",
"bg_color": "#FFFFFF",
}
DEFAULTS = {
"input_dir": "./input",
"output_dir": "./output",
"supported_extensions": [".jpg", ".jpeg", ".png", ".webp"],
"qr_size_ratio": 0.15,
"padding_ratio": 0.02,
"min_padding_px": 10,
"jpeg_quality": 95,
"qr_position": "bottom-right",
"qr_border_modules": 4,
"overwrite_existing": True,
"log_file": "processing_log.csv",
"workers": 1,
"qr_style": dict(DEFAULT_QR_STYLE),
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Helper: HEX to RGB
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def hex_to_rgb(hex_color: str) -> Tuple[int, int, int]:
"""Convert a hex color string (#RRGGBB) to an RGB tuple."""
h = hex_color.lstrip("#")
return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 1. Configuration Loading
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_config(cli_args: Optional[List[str]] = None) -> Dict[str, Any]:
"""
Load configuration with priority: CLI args > config.json > DEFAULTS.
Args:
cli_args: Optional list of CLI arguments (for testing).
Returns:
Merged configuration dictionary.
"""
# Start with defaults
config = dict(DEFAULTS)
config["qr_style"] = dict(DEFAULT_QR_STYLE)
# Layer 2: config.json (if exists)
config_path = Path(__file__).parent / "config.json"
if config_path.exists():
try:
with open(config_path, "r", encoding="utf-8") as f:
file_config = json.load(f)
# Extract qr_style separately to merge properly
file_qr_style = file_config.pop("qr_style", {})
config.update(file_config)
config["qr_style"].update(file_qr_style)
except (json.JSONDecodeError, IOError) as e:
print(f"β οΈ Warning: Could not read config.json β {e}")
print(" Using default configuration.\n")
# Layer 3: CLI arguments (highest priority)
parser = argparse.ArgumentParser(
description="QR Code Batch Image Processor β Watermark images with QR codes.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--input", type=str, help="Input directory path")
parser.add_argument("--output", type=str, help="Output directory path")
parser.add_argument("--quality", type=int, help="JPEG output quality (1-100)")
parser.add_argument("--qr-size", type=float, help="QR size ratio (0.0-1.0)")
parser.add_argument("--workers", type=int, help="Number of parallel workers")
parser.add_argument(
"--dry-run",
action="store_true",
help="Simulate processing without writing files",
)
parser.add_argument(
"--skip-existing",
action="store_true",
help="Skip files that already exist in output",
)
parser.add_argument(
"--theme",
type=str,
choices=list(THEMES.keys()),
help="QR code visual theme (classic, luxury, rose-gold, midnight, "
"luxury-container, rose-gold-container, midnight-container)",
)
parser.add_argument(
"--container",
action="store_true",
help="Add a rounded container with shadow around the QR code",
)
args = parser.parse_args(cli_args)
# Apply CLI overrides
if args.input:
config["input_dir"] = args.input
if args.output:
config["output_dir"] = args.output
if args.quality:
config["jpeg_quality"] = max(1, min(100, args.quality))
if args.qr_size:
config["qr_size_ratio"] = max(0.01, min(0.5, args.qr_size))
if args.workers:
config["workers"] = max(1, args.workers)
if args.dry_run:
config["dry_run"] = True
else:
config.setdefault("dry_run", False)
if args.skip_existing:
config["overwrite_existing"] = False
# Apply theme from CLI (overrides config.json qr_style)
if args.theme:
theme = THEMES[args.theme]
config["qr_style"]["theme"] = args.theme
config["qr_style"]["fg_color"] = theme["fg_color"]
config["qr_style"]["bg_color"] = theme["bg_color"]
config["qr_style"]["rounded_modules"] = theme["rounded_modules"]
config["qr_style"]["container"] = theme["container"]
# --container flag adds container to any theme
if args.container:
config["qr_style"]["container"] = True
# If theme is not "classic" or "custom", apply theme colors
theme_name = config["qr_style"].get("theme", "classic")
if theme_name in THEMES and not args.theme:
theme = THEMES[theme_name]
# Only apply theme defaults if user hasn't set custom colors in config
if config["qr_style"].get("fg_color") == DEFAULT_QR_STYLE["fg_color"]:
config["qr_style"]["fg_color"] = theme["fg_color"]
if config["qr_style"].get("bg_color") == DEFAULT_QR_STYLE["bg_color"]:
config["qr_style"]["bg_color"] = theme["bg_color"]
config["qr_style"].setdefault("rounded_modules", theme["rounded_modules"])
return config
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 2. Directory Setup
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def setup_directories(config: Dict[str, Any]) -> Tuple[Path, Path]:
"""
Ensure input and output directories exist and are accessible.
Returns:
Tuple of (input_path, output_path).
Raises:
SystemExit: If input directory doesn't exist or has no images.
"""
input_dir = Path(config["input_dir"]).resolve()
output_dir = Path(config["output_dir"]).resolve()
# Validate input directory
if not input_dir.exists():
input_dir.mkdir(parents=True, exist_ok=True)
print(f"β οΈ Input directory created: {input_dir}")
print(" Place your product images there and run again.\n")
sys.exit(0)
if not input_dir.is_dir():
print(f"β Error: '{input_dir}' is not a directory.")
sys.exit(1)
# Create output directory
output_dir.mkdir(parents=True, exist_ok=True)
return input_dir, output_dir
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 3. Image Scanning
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def scan_images(input_dir: Path, config: Dict[str, Any]) -> List[Path]:
"""
Scan input directory for supported image files.
Args:
input_dir: Path to the input directory.
config: Configuration dictionary.
Returns:
Sorted list of image file paths.
"""
supported = set(ext.lower() for ext in config["supported_extensions"])
all_files = [f for f in input_dir.iterdir() if f.is_file()]
images = [f for f in all_files if f.suffix.lower() in supported]
skipped = len(all_files) - len(images)
if skipped > 0:
print(f" βοΈ {skipped} non-image file(s) ignored.\n")
# Sort alphabetically for consistent ordering
images.sort(key=lambda p: p.name.lower())
return images
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 4. SKU Extraction
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def extract_sku(filepath: Path) -> str:
"""
Extract the product SKU from the image filename.
The SKU is the filename without its extension.
Example: 'BF-1012-1.jpg' β 'BF-1012-1'
Args:
filepath: Path to the image file.
Returns:
The extracted SKU string.
"""
return filepath.stem
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 5. QR Code Generation (with style support)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def generate_qr(
sku: str, size: int, border: int = 4, style: Optional[Dict[str, Any]] = None
) -> Image.Image:
"""
Generate a QR code image containing the SKU string.
Supports styled QR codes with rounded modules and custom colors.
Args:
sku: The SKU text to encode in the QR code.
size: Target size in pixels (width = height).
border: Number of quiet zone modules around the QR.
style: Optional style configuration dict with theme settings.
Returns:
PIL Image object of the QR code in RGBA mode.
"""
if style is None:
style = DEFAULT_QR_STYLE
fg_color = hex_to_rgb(style.get("fg_color", "#000000"))
bg_color = hex_to_rgb(style.get("bg_color", "#FFFFFF"))
use_rounded = style.get("rounded_modules", False)
qr = qrcode.QRCode(
version=1,
error_correction=ERROR_CORRECT_H, # 30% error correction
box_size=10,
border=border,
)
qr.add_data(sku)
qr.make(fit=True)
if use_rounded:
# Generate with rounded modules using default black/white first
qr_img = qr.make_image(
image_factory=StyledPilImage, module_drawer=RoundedModuleDrawer()
).convert("RGBA")
# Recolor pixels: dark β fg_color, light β bg_color
pixels = qr_img.load()
w, h = qr_img.size
for y in range(h):
for x in range(w):
r, g, b, a = pixels[x, y]
if r < 128 and g < 128 and b < 128:
pixels[x, y] = fg_color + (a,)
else:
pixels[x, y] = bg_color + (a,)
else:
# Classic square modules with custom colors
qr_img = qr.make_image(
fill_color=fg_color, back_color=bg_color
).convert("RGBA")
qr_img = qr_img.resize((size, size), Image.LANCZOS)
return qr_img
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 5b. QR Container with Shadow
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def create_qr_container(
qr_img: Image.Image, style: Dict[str, Any]
) -> Image.Image:
"""
Wrap a QR code image in an elegant container with rounded corners
and an optional drop shadow.
Args:
qr_img: The QR code PIL Image (RGBA).
style: Style configuration dict.
Returns:
PIL Image with the QR inside a styled container (RGBA).
"""
qr_size = qr_img.width
bg_color = hex_to_rgb(style.get("bg_color", "#FFFFFF"))
# Container dimensions
pad_ratio = style.get("container_padding_ratio", 0.15)
container_pad = max(int(qr_size * pad_ratio), 8)
radius = style.get("container_radius", 16)
use_shadow = style.get("shadow", True)
shadow_blur_r = style.get("shadow_blur", 10)
shadow_opacity = style.get("shadow_opacity", 50)
container_w = qr_size + container_pad * 2
container_h = qr_size + container_pad * 2
if use_shadow:
shadow_offset = max(shadow_blur_r // 3, 2)
total_w = container_w + shadow_blur_r * 2 + shadow_offset
total_h = container_h + shadow_blur_r * 2 + shadow_offset
else:
shadow_blur_r = 0
shadow_offset = 0
total_w = container_w
total_h = container_h
# Start with transparent canvas
result = Image.new("RGBA", (total_w, total_h), (0, 0, 0, 0))
if use_shadow:
# Draw shadow
shadow_layer = Image.new("RGBA", (total_w, total_h), (0, 0, 0, 0))
sd = ImageDraw.Draw(shadow_layer)
sx = shadow_blur_r + shadow_offset
sy = shadow_blur_r + shadow_offset
sd.rounded_rectangle(
[sx, sy, sx + container_w, sy + container_h],
radius=radius,
fill=(0, 0, 0, shadow_opacity),
)
shadow_layer = shadow_layer.filter(ImageFilter.GaussianBlur(shadow_blur_r))
result = Image.alpha_composite(result, shadow_layer)
# Draw container background
container_layer = Image.new("RGBA", (total_w, total_h), (0, 0, 0, 0))
cd = ImageDraw.Draw(container_layer)
cx = shadow_blur_r
cy = shadow_blur_r
cd.rounded_rectangle(
[cx, cy, cx + container_w, cy + container_h],
radius=radius,
fill=bg_color + (255,),
)
result = Image.alpha_composite(result, container_layer)
# Paste QR inside
qr_layer = Image.new("RGBA", (total_w, total_h), (0, 0, 0, 0))
qr_layer.paste(qr_img, (cx + container_pad, cy + container_pad), qr_img)
result = Image.alpha_composite(result, qr_layer)
return result
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 6. Single Image Processing
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def process_single_image(
filepath: Path, output_dir: Path, config: Dict[str, Any]
) -> Dict[str, Any]:
"""
Process a single image: generate QR code and composite it onto the image.
This function handles:
- EXIF orientation correction
- Alpha channel handling (PNG transparency)
- Dynamic QR sizing (15% of image width)
- Proportional padding (2% of width, min 10px)
- Styled QR codes with themes, containers, and shadows
- Format-aware saving (JPEGβRGB, PNGβRGBA)
Args:
filepath: Path to the source image.
output_dir: Path to the output directory.
config: Configuration dictionary.
Returns:
Dict with processing result: filename, sku, status, error, dimensions, qr_size.
"""
result = {
"timestamp": datetime.now().isoformat(),
"filename": filepath.name,
"sku": "",
"status": "failed",
"original_size": "",
"qr_size_px": 0,
"error": "",
}
output_path = output_dir / filepath.name
qr_style = config.get("qr_style", DEFAULT_QR_STYLE)
try:
# --- Check overwrite policy ---
if not config["overwrite_existing"] and output_path.exists():
result["status"] = "skipped"
result["error"] = "already exists"
return result
# --- Dry run mode ---
if config.get("dry_run", False):
# Open image briefly just to validate and get dimensions
with Image.open(filepath) as img:
result["original_size"] = f"{img.width}x{img.height}"
result["sku"] = extract_sku(filepath)
result["qr_size_px"] = int(img.width * config["qr_size_ratio"])
result["status"] = "dry-run"
return result
# --- Open and prepare the image ---
img = Image.open(filepath)
# Fix EXIF orientation (rotated photos from cameras)
img = ImageOps.exif_transpose(img)
img_width, img_height = img.size
result["original_size"] = f"{img_width}x{img_height}"
# --- Extract SKU ---
sku = extract_sku(filepath)
result["sku"] = sku
# --- Calculate QR size and padding ---
qr_size = int(img_width * config["qr_size_ratio"])
qr_size = max(qr_size, 50) # Minimum 50px to remain scannable
result["qr_size_px"] = qr_size
padding = max(
int(img_width * config["padding_ratio"]), config["min_padding_px"]
)
# --- Generate styled QR code ---
qr_img = generate_qr(sku, qr_size, config["qr_border_modules"], qr_style)
# --- Optionally wrap in container ---
use_container = qr_style.get("container", False)
if use_container:
final_qr = create_qr_container(qr_img, qr_style)
qr_img.close()
else:
final_qr = qr_img
final_w, final_h = final_qr.size
# --- Calculate position (bottom-right) ---
x = img_width - final_w - padding
y = img_height - final_h - padding
# Ensure position is not negative (for very small images)
x = max(0, x)
y = max(0, y)
# --- Composite QR onto image ---
if img.mode == "RGBA":
# Handle transparent PNG: use alpha compositing
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
overlay.paste(final_qr, (x, y), final_qr)
img = Image.alpha_composite(img, overlay)
else:
# Standard image: convert to RGB if needed, then paste
if img.mode not in ("RGB", "L"):
img = img.convert("RGB")
# Paste QR with its alpha channel as mask for clean edges
rgb_qr = final_qr.convert("RGB")
alpha_mask = final_qr.split()[3] # Alpha channel as mask
img.paste(rgb_qr, (x, y), alpha_mask)
# --- Save with format-appropriate settings ---
output_ext = filepath.suffix.lower()
if output_ext in (".jpg", ".jpeg"):
# JPEG doesn't support alpha β ensure RGB mode
if img.mode != "RGB":
img = img.convert("RGB")
img.save(output_path, "JPEG", quality=config["jpeg_quality"], optimize=True)
elif output_ext == ".png":
img.save(output_path, "PNG", optimize=True)
elif output_ext == ".webp":
img.save(
output_path, "WEBP", quality=config["jpeg_quality"], method=4
)
else:
# Fallback: save as JPEG
if img.mode != "RGB":
img = img.convert("RGB")
img.save(output_path, "JPEG", quality=config["jpeg_quality"], optimize=True)
# --- Cleanup ---
img.close()
final_qr.close()
result["status"] = "success"
except FileNotFoundError:
result["error"] = "File not found"
except PermissionError:
result["error"] = "Permission denied"
except Image.UnidentifiedImageError:
result["error"] = "Cannot identify image file (corrupted or unsupported)"
except Image.DecompressionBombError:
result["error"] = "Image too large (decompression bomb protection)"
except Exception as e:
result["error"] = str(e)
return result
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 7. Log Writer
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def init_log(log_path: Path) -> None:
"""Initialize the CSV log file with headers."""
with open(log_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(
f,
fieldnames=[
"timestamp",
"filename",
"sku",
"status",
"original_size",
"qr_size_px",
"error",
],
)
writer.writeheader()
def append_log(log_path: Path, result: Dict[str, Any]) -> None:
"""Append a single processing result to the CSV log."""
with open(log_path, "a", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(
f,
fieldnames=[
"timestamp",
"filename",
"sku",
"status",
"original_size",
"qr_size_px",
"error",
],
)
writer.writerow(result)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 8. Main Engine
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def print_banner(config: Dict[str, Any], image_count: int) -> None:
"""Print the startup banner with configuration info."""
qr_style = config.get("qr_style", {})
theme_name = qr_style.get("theme", "classic")
has_container = qr_style.get("container", False)
print()
print("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
print("β QR Code Batch Image Processor v1.1 β")
print("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
print()
print(f" π Input: {config['input_dir']} ({image_count} images found)")
print(f" π Output: {config['output_dir']}")
print(
f" βοΈ QR Size: {int(config['qr_size_ratio'] * 100)}%"
f" | Quality: {config['jpeg_quality']}"
f" | Workers: {config['workers']}"
)
# Display theme info
theme_display = theme_name
if has_container:
theme_display += " + container"
print(f" π¨ Theme: {theme_display}")
if config.get("dry_run"):
print(" π Mode: DRY RUN (no files will be written)")
if not config["overwrite_existing"]:
print(" βοΈ Policy: Skip existing files")
print()
print("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
def print_result(index: int, total: int, result: Dict[str, Any]) -> None:
"""Print a single image processing result to the terminal."""
idx_str = f"[{index:>{len(str(total))}}/{total}]"
if result["status"] == "success":
print(
f" {idx_str} β
{result['filename']}"
f" ({result['original_size']} β QR: {result['qr_size_px']}px)"
)
elif result["status"] == "skipped":
print(f" {idx_str} βοΈ {result['filename']} β skipped ({result['error']})")
elif result["status"] == "dry-run":
print(
f" {idx_str} π {result['filename']}"
f" ({result['original_size']} β QR: {result['qr_size_px']}px) [dry-run]"
)
else:
print(
f" {idx_str} β {result['filename']}"
f" β Error: {result['error']}"
)
def print_summary(
results: List[Dict[str, Any]], elapsed: float, log_path: Path
) -> None:
"""Print the final processing summary."""
success = sum(1 for r in results if r["status"] == "success")
failed = sum(1 for r in results if r["status"] == "failed")
skipped = sum(1 for r in results if r["status"] == "skipped")
dry_run = sum(1 for r in results if r["status"] == "dry-run")
total_processed = success + dry_run
speed = total_processed / elapsed if elapsed > 0 else 0
print()
print("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ")
print()
print(" π Summary:")
if dry_run > 0:
print(f" π Dry Run: {dry_run}")
else:
print(f" β
Processed: {success}")
print(f" β Failed: {failed}")
print(f" βοΈ Skipped: {skipped}")
print(f" β±οΈ Time: {elapsed:.1f}s ({speed:.1f} img/s)")
print(f" π Log: {log_path}")
print()
def main(cli_args: Optional[List[str]] = None) -> None:
"""
Main entry point for the batch image processor.
Orchestrates: config loading β directory setup β scanning β
processing (sequential or parallel) β logging β summary.
"""
# Load configuration
config = load_config(cli_args)
# Setup directories
input_dir, output_dir = setup_directories(config)
# Scan for images
images = scan_images(input_dir, config)
if not images:
print(" βΉοΈ No images found in the input directory.")
print(f" Place your images in: {input_dir}")
print()
sys.exit(0)
# Print startup banner
print_banner(config, len(images))
# Initialize log file
log_path = output_dir / config["log_file"]
if not config.get("dry_run"):
init_log(log_path)
# Start processing
start_time = time.time()
results: List[Dict[str, Any]] = []
total = len(images)
if config["workers"] > 1:
# ββ Parallel Processing ββ
with ProcessPoolExecutor(max_workers=config["workers"]) as executor:
future_to_img = {
executor.submit(
process_single_image, img_path, output_dir, config
): img_path
for img_path in images
}
completed = 0
for future in as_completed(future_to_img):
completed += 1
result = future.result()
results.append(result)
print_result(completed, total, result)
if not config.get("dry_run"):
append_log(log_path, result)
else:
# ββ Sequential Processing ββ
for idx, img_path in enumerate(images, 1):
result = process_single_image(img_path, output_dir, config)
results.append(result)
print_result(idx, total, result)
if not config.get("dry_run"):
append_log(log_path, result)
elapsed = time.time() - start_time
# Print summary
print_summary(results, elapsed, log_path)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Entry Point
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
main()