-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathframes
More file actions
executable file
·1793 lines (1524 loc) · 70 KB
/
frames
File metadata and controls
executable file
·1793 lines (1524 loc) · 70 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
#!/usr/bin/env python3
"""frames — Apple Frames CLI
Frame device screenshots with Apple product bezels. Auto-detects devices from
screenshot dimensions, applies colored frames with masks, merges multiple
screenshots side by side. Replicates Apple Frames shortcut functionality for
use in terminal workflows and AI agent pipelines.
Assets default to the Apple Frames Shortcuts location on macOS and standard
app data directories elsewhere.
"""
import argparse
import json
import os
import random
import shutil
import ssl
import stat
import subprocess
import sys
import tempfile
import warnings
from functools import lru_cache
from pathlib import Path, PurePosixPath
try:
from PIL import Image, UnidentifiedImageError
except ImportError:
print("Error: Pillow is required. Install with: pip3 install Pillow", file=sys.stderr)
sys.exit(1)
warnings.simplefilter("error", Image.DecompressionBombWarning)
VERSION = "1.2.7"
APP_NAME = "frames"
HOME = Path.home()
CONFIG_DIR = HOME / ".config" / "frames"
CONFIG_FILE = CONFIG_DIR / "config.json"
ASSETS_URL = "https://cdn.macstories.net/AppleFrames40.zip"
ASSETS_MIN_VERSION = 4
LARGE_IMAGE_WARN_DIMENSION = 20000
LARGE_IMAGE_MAX_DIMENSION = 50000
VALID_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".heic", ".tiff", ".webp"}
def get_shortcuts_assets_dir(home=None):
"""Return the Apple Frames Shortcuts asset location on macOS."""
home = Path(home) if home is not None else HOME
return home / "Library/Mobile Documents/iCloud~is~workflow~my~workflows/Documents/Frames"
def get_app_data_assets_dir(home=None, platform=None, environ=None):
"""Return the standard per-platform app data assets directory."""
home = Path(home) if home is not None else HOME
platform = platform or sys.platform
environ = environ or os.environ
if platform == "darwin":
return Path(environ.get("FRAMES_DATA_HOME", home / "Library/Application Support")) / APP_NAME / "assets"
if platform.startswith("win"):
return Path(environ.get("LOCALAPPDATA", home / "AppData/Local")) / APP_NAME / "assets"
return Path(environ.get("XDG_DATA_HOME", home / ".local/share")) / APP_NAME / "assets"
def get_default_assets_dir(home=None, platform=None, environ=None):
"""Return the preferred default assets directory for the current platform."""
platform = platform or sys.platform
if platform == "darwin":
return get_shortcuts_assets_dir(home)
return get_app_data_assets_dir(home, platform, environ)
SHORTCUTS_ASSETS = get_shortcuts_assets_dir()
APPDATA_ASSETS = get_app_data_assets_dir()
DEFAULT_ASSETS = get_default_assets_dir()
def _expand_path(path_value):
return Path(path_value).expanduser()
def _get_config_assets_dir():
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, encoding="utf-8") as f:
cfg = json.load(f)
if "assets_path" in cfg:
return _expand_path(cfg["assets_path"])
except (json.JSONDecodeError, KeyError, OSError):
pass
return None
def read_config_file():
"""Read config file without swallowing errors."""
if not CONFIG_FILE.exists():
return None, None
try:
with open(CONFIG_FILE, encoding="utf-8") as f:
return json.load(f), None
except (json.JSONDecodeError, OSError) as e:
return None, str(e)
def validate_subfolder_name(name):
"""Allow only a single relative directory component for --subfolder."""
candidate = str(name).strip()
if not candidate:
raise ValueError("Subfolder name cannot be empty.")
pure = PurePosixPath(candidate.replace("\\", "/"))
if pure.is_absolute() or len(pure.parts) != 1 or pure.parts[0] in {".", ".."}:
raise ValueError(
"Subfolder must be a single directory name without path separators or '..'."
)
return pure.parts[0]
def resolve_assets_dir(args_assets=None):
"""Resolve assets directory and report which source won."""
if args_assets is not None:
return _expand_path(args_assets), "--assets"
env = os.environ.get("FRAMES_ASSETS")
if env:
return _expand_path(env), "FRAMES_ASSETS"
configured = _get_config_assets_dir()
if configured is not None:
return configured, "config"
if check_assets_version(DEFAULT_ASSETS)[0]:
return DEFAULT_ASSETS, "default"
if DEFAULT_ASSETS != APPDATA_ASSETS and check_assets_version(APPDATA_ASSETS)[0]:
return APPDATA_ASSETS, "app-data"
return DEFAULT_ASSETS, "default"
def get_assets_dir(args_assets=None):
"""Resolve assets directory: CLI flag > env var > config file > default."""
return resolve_assets_dir(args_assets)[0]
def get_subfolder_setting(args, config=None):
"""Get subfolder name if enabled. Returns folder name string or None.
CLI flag > config > default (None). -f alone = 'framed', -f custom = 'custom'."""
if hasattr(args, 'subfolder') and args.subfolder is not None:
return validate_subfolder_name(args.subfolder)
cfg = config if config is not None else load_config()
sub = cfg.get("use_subfolder", False)
if sub is True:
return "framed"
elif isinstance(sub, str):
return validate_subfolder_name(sub)
return None
# ── Asset Management ────────────────────────────────────────────────────────
def check_assets_version(assets_dir):
"""Check if assets directory has valid Apple Frames 4+ assets.
Returns (ok, version_or_none)."""
assets_dir = Path(assets_dir)
json_path = assets_dir / "NewFrames.json"
if not assets_dir.exists() or not json_path.exists():
return False, None
version_path = assets_dir / "version.txt"
if version_path.exists():
try:
ver = version_path.read_text(encoding="utf-8").strip().split('\n')[0].strip()
major = int(ver.split('.')[0])
return major >= ASSETS_MIN_VERSION, major
except (ValueError, IndexError):
pass
# No version.txt — check for v4 indicators in JSON
try:
with open(json_path, encoding="utf-8") as f:
data = json.load(f)
if "variants" in data:
return True, 4
return False, None
except (json.JSONDecodeError, IOError):
return False, None
def _zip_member_is_symlink(member):
unix_mode = member.external_attr >> 16
return stat.S_ISLNK(unix_mode)
def _iter_safe_zip_members(zip_file):
members = []
top_items = set()
for member in zip_file.infolist():
filename = member.filename.replace("\\", "/")
if not filename or filename.startswith("__MACOSX/"):
continue
members.append((member, filename))
top_items.add(filename.split("/", 1)[0])
prefix = ""
if len(top_items) == 1:
prefix = next(iter(top_items)) + "/"
for member, filename in members:
relative_name = filename
if prefix and relative_name.startswith(prefix):
relative_name = relative_name[len(prefix):]
if not relative_name:
continue
relative_path = PurePosixPath(relative_name)
if relative_path.is_absolute() or ".." in relative_path.parts:
raise ValueError(f"Archive contains unsafe path: {filename}")
if _zip_member_is_symlink(member):
raise ValueError(f"Archive contains unsupported symlink: {filename}")
yield member, relative_path
def _extract_zip_to_dir(zip_file, destination):
for member, relative_path in _iter_safe_zip_members(zip_file):
target = destination.joinpath(*relative_path.parts)
if member.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
with zip_file.open(member) as src, open(target, "wb") as dst:
shutil.copyfileobj(src, dst)
def _find_assets_root(path):
json_path = path / "NewFrames.json"
if json_path.exists():
return path
found = list(path.rglob("NewFrames.json"))
if found:
return found[0].parent
return None
def _is_ssl_download_error(exc):
reason = getattr(exc, "reason", exc)
if isinstance(reason, ssl.SSLError):
return True
text = str(reason).lower()
ssl_markers = (
"certificate verify failed",
"self-signed certificate",
"tlsv1 alert",
"ssl:",
)
return any(marker in text for marker in ssl_markers)
def _download_with_urllib(tmp_path, reporthook):
import urllib.request
urllib.request.urlretrieve(ASSETS_URL, tmp_path, reporthook=reporthook)
def _download_with_curl(tmp_path, curl_path=None):
curl_path = curl_path or shutil.which("curl")
if curl_path is None:
raise FileNotFoundError("curl is not installed")
result = subprocess.run(
[curl_path, "--location", "--fail", "--progress-bar", "--show-error", "-o", tmp_path, ASSETS_URL],
check=False,
)
if result.returncode != 0:
raise OSError(f"curl download failed with exit code {result.returncode}")
def download_assets(dest_dir):
"""Download and extract Apple Frames 4 assets. Returns True on success."""
import urllib.request, urllib.error, zipfile
dest_dir = Path(dest_dir)
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:
tmp_path = tmp.name
try:
def progress(block_num, block_size, total_size):
if total_size > 0:
pct = min(100, int(block_num * block_size * 100 / total_size))
filled = int(25 * pct / 100)
bar = '\u2588' * filled + '\u2591' * (25 - filled)
mb = total_size / (1024 * 1024)
print(f"\r Downloading [{C.rgb(232,114,42, bar)}] {pct}% of {mb:.0f} MB ", end="", flush=True)
print(f" {C.dim('Connecting to cdn.macstories.net...')}", flush=True)
try:
_download_with_urllib(tmp_path, progress)
print()
except urllib.error.URLError as e:
if not _is_ssl_download_error(e):
raise
curl_path = shutil.which("curl")
if curl_path is None:
raise
print()
print(f" {C.dim('Python SSL verification failed; retrying with curl...')}", flush=True)
_download_with_curl(tmp_path, curl_path=curl_path)
print()
print(f" {C.dim('Extracting...')}", end=" ", flush=True)
with tempfile.TemporaryDirectory(prefix="frames-assets-") as stage_dir:
stage_path = Path(stage_dir)
with zipfile.ZipFile(tmp_path, "r") as zf:
_extract_zip_to_dir(zf, stage_path)
source_root = _find_assets_root(stage_path)
if source_root is None:
print(C.red('failed'))
print(f" {C.red('Error')}: NewFrames.json not found in archive.", file=sys.stderr)
return False
dest_dir.mkdir(parents=True, exist_ok=True)
for item in source_root.iterdir():
target = dest_dir / item.name
if item.is_dir():
shutil.copytree(item, target, dirs_exist_ok=True)
else:
shutil.copy2(item, target)
pngs = list(dest_dir.glob("*.png"))
print(C.green('done!'))
print(f" {C.bold(str(len(pngs)))} frame assets installed")
return True
except urllib.error.URLError as e:
print(f"\n {C.red('Download failed')}: {e.reason}", file=sys.stderr)
return False
except zipfile.BadZipFile:
print(f"\n {C.red('Error')}: Downloaded file is corrupted.", file=sys.stderr)
return False
except ValueError as e:
print(C.red("failed"))
print(f" {C.red('Error')}: {e}", file=sys.stderr)
return False
except OSError as e:
print(f"\n {C.red('Error')}: {e}", file=sys.stderr)
return False
finally:
try:
os.unlink(tmp_path)
except OSError:
pass
def guided_setup(reason=None):
"""Interactive guided setup — download and install Apple Frames 4 assets.
Returns True on success, False if cancelled or failed."""
default_path = get_default_assets_dir()
short_default = str(default_path).replace(str(HOME), "~")
print()
if reason:
print(f" {C.bold('Apple Frames 4')} assets {reason}.")
else:
print(f" {C.bold('Apple Frames 4')} asset setup")
print()
print(f" Download device frames from {C.cyan('cdn.macstories.net')}? (~40 MB)")
print()
print(f" Install to {C.cyan(short_default)}")
print()
print(f" {C.bold('Enter')} {C.dim('to confirm |')} {C.bold('q')} {C.dim('to cancel | or type a different path')}")
print()
try:
choice = input(f" {C.bold('›')} ").strip()
except (EOFError, KeyboardInterrupt):
print(f"\n\n {C.dim('Cancelled.')}\n")
return False
if choice.lower() in ('q', 'quit', 'n', 'no'):
print(f"\n {C.dim('Cancelled.')}\n")
return False
dest = Path(choice).expanduser().resolve() if choice else default_path
print()
if not download_assets(dest):
return False
config = load_config()
config["assets_path"] = str(dest)
save_config(config)
short_dest = str(dest).replace(str(HOME), "~")
print()
print(f" {C.green('Setup complete!')}")
print(f" {C.bold('Assets:')} {short_dest}")
print(f" {C.bold('Config:')} {CONFIG_FILE}")
print()
print(f" {C.dim('Run')} {C.cyan('frames')} screenshot.png {C.dim('to get started.')}")
print()
return True
# ── Color System ─────────────────────────────────────────────────────────────
class C:
"""ANSI color helpers. Respects NO_COLOR env and --no-color flag."""
enabled = True
@staticmethod
def _c(code, text):
return f"\033[{code}m{text}\033[0m" if C.enabled else str(text)
@staticmethod
def red(t): return C._c("31", t)
@staticmethod
def green(t): return C._c("32", t)
@staticmethod
def yellow(t): return C._c("33", t)
@staticmethod
def blue(t): return C._c("34", t)
@staticmethod
def magenta(t): return C._c("35", t)
@staticmethod
def cyan(t): return C._c("36", t)
@staticmethod
def dim(t): return C._c("2", t)
@staticmethod
def bold(t): return C._c("1", t)
@staticmethod
def rgb(r, g, b, t):
return f"\033[38;2;{r};{g};{b}m{t}\033[0m" if C.enabled else str(t)
# ── Splash Screen ────────────────────────────────────────────────────────────
LOGO_LINES = [
r" █████ ██████ ██████ ██ ███████ ",
r"██ ██ ██ ██ ██ ██ ██ ██ ",
r"███████ ██████ ██████ ██ █████ ",
r"██ ██ ██ ██ ██ ██ ",
r"██ ██ ██ ██ ███████ ███████ ",
r"",
r"███████ ██████ █████ ███ ███ ███████ ███████ ",
r"██ ██ ██ ██ ██ ████ ████ ██ ██ ",
r"█████ ██████ ███████ ██ ████ ██ █████ ███████ ",
r"██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ",
r"██ ██ ██ ██ ██ ██ ██ ███████ ███████ ",
]
LOGO_COLORS = [
(232, 114, 42), # Cosmic Orange
(235, 125, 50),
(238, 136, 58),
(235, 125, 50),
(232, 114, 42),
(0, 0, 0),
(232, 114, 42),
(235, 125, 50),
(238, 136, 58),
(235, 125, 50),
(232, 114, 42),
]
def show_splash():
"""Display colored ASCII art splash screen."""
print()
for line, (r, g, b) in zip(LOGO_LINES, LOGO_COLORS):
if line:
print(f" {C.rgb(r, g, b, line)}")
else:
print()
ver = C.dim(f"v{VERSION}")
author = C.dim("by Federico Viticci")
print(f"\n {C.bold('Apple Frames CLI')} {ver} {author}")
print(f" {C.dim('Frame screenshots with Apple device bezels')}\n")
print(f" {C.dim('Quick start:')}")
print(f" {C.cyan('frames')} screenshot.png {C.dim('Frame a screenshot')}")
print(f" {C.cyan('frames')} *.png {C.dim('Frame all PNGs in directory')}")
print(f" {C.cyan('frames')} -m *.png {C.dim('Merge side by side (proportional)')}")
print(f" {C.cyan('frames')} -b 3 *.png {C.dim('Merge in batches of 3')}")
print(f" {C.cyan('frames')} -m --no-scale *.png {C.dim('Merge without proportional scaling')}")
print(f" {C.cyan('frames')} -c random *.png {C.dim('Random frame colors')}")
print(f" {C.cyan('frames')} ~/Screenshots/ {C.dim('Frame all images in a folder')}")
print(f" {C.cyan('frames')} -f *.png {C.dim('Save to /framed/ subfolder')}")
print(f" {C.cyan('frames')} --subfolder mockups *.png {C.dim('Save to custom subfolder')}")
print(f" {C.cyan('frames')} info shot.png {C.dim('Identify device, colors, variants')}")
print(f" {C.cyan('frames')} info ~/Screenshots/ {C.dim('Scan folder for device matches')}")
print(f" {C.cyan('frames')} colors {C.dim('Pick default colors per device')}")
print(f" {C.cyan('frames')} list {C.dim('Show supported devices')}")
print(f" {C.cyan('frames')} setup {C.dim('Download + configure assets')}")
# Show asset status
assets_dir = get_assets_dir()
ok, ver = check_assets_version(assets_dir)
if ok:
short = str(assets_dir).replace(str(HOME), "~")
pngs = len(list(assets_dir.glob("*.png")))
print(f" {C.green('Assets installed')} {C.dim(f'(v{ver}, {pngs} frames)')}")
print(f" {C.dim(short)}")
else:
print(f" {C.yellow('Assets not installed.')} Run {C.cyan('frames setup')} to download device frames.")
print()
# ── Frame Colors Dictionary ──────────────────────────────────────────────────
FRAME_COLORS = {
"iPhone 17 Pro Portrait": ["Cosmic Orange", "Deep Blue", "Silver"],
"iPhone 17 Pro Landscape": ["Cosmic Orange", "Deep Blue", "Silver"],
"iPhone 17 Pro Max Portrait": ["Cosmic Orange", "Deep Blue", "Silver"],
"iPhone 17 Pro Max Landscape": ["Cosmic Orange", "Deep Blue", "Silver"],
"iPhone 17 Portrait": ["Black", "Lavender", "Mist Blue", "Sage", "White"],
"iPhone 17 Landscape": ["Black", "Lavender", "Mist Blue", "Sage", "White"],
"iPhone Air Portrait": ["Black", "White", "Gold", "Blue"],
"iPhone Air Landscape": ["Black", "White", "Gold", "Blue"],
"MacBook Pro M5 14": ["Silver", "Space Black"],
"MacBook Pro M5 16": ["Silver", "Space Black"],
"MacBook Neo": ["Blush", "Citrus", "Indigo", "Silver"],
"iPhone 16 Pro Portrait": ["Natural", "Desert", "Black", "White"],
"iPhone 16 Pro Landscape": ["Natural", "Desert", "Black", "White"],
"iPhone 16 Pro Max Portrait": ["White", "Desert", "Natural", "Black"],
"iPhone 16 Pro Max Landscape": ["Black", "Desert", "Natural", "White"],
"iPhone 16 Portrait": ["Ultramarine", "Teal", "Pink", "Black", "White"],
"iPhone 16 Landscape": ["Ultramarine", "Teal", "Pink", "Black", "White"],
"iPhone 16 Plus Portrait": ["Ultramarine", "White", "Teal", "Pink", "Black"],
"iPhone 16 Plus Landscape": ["Ultramarine", "Teal", "Pink", "Black", "White"],
"Watch Ultra 3": ["Black + Alpine Loop Black", "Black + Alpine Loop Light Blue", "Black + Milanese Loop", "Black + Ocean Band Anchor Blue", "Black + Ocean Band Black", "Black + Trail Loop Black Charcoal", "Natural + Alpine Loop Light Blue", "Natural + Alpine Loop Terra Cotta", "Natural + Milanese Loop", "Natural + Ocean Band Anchor Blue", "Natural + Ocean Band Neon Green", "Natural + Trail Loop Blue Bright Blue", "Natural + Trail Loop Green Neon"],
"Watch Ultra 2024": ["Orange Beige Trail Loop", "Blue Alpine Loop", "Orange Ocean Band", "Black + Alpine Loop Dark Green", "Black + Alpine Loop Navy", "Black + Alpine Loop Tan", "Black + Ocean Band Black", "Black + Ocean Band Ice Blue", "Black + Ocean Band Navy", "Black + Titanium Milanese Loop", "Black + Trail Loop Black", "Black + Trail Loop Blue", "Black + Trail Loop Green", "Natural + Alpine Loop Dark Green", "Natural + Alpine Loop Navy", "Natural + Alpine Loop Tan", "Natural + Ocean Band Black", "Natural + Ocean Band Ice Blue", "Natural + Ocean Band Navy", "Natural + Titanium Milanese Loop", "Natural + Trail Loop Black", "Natural + Trail Loop Blue"],
"MacBook Air M5 13": ["Midnight", "Silver", "Sky Blue", "Starlight"],
"MacBook Air M5 15": ["Midnight", "Silver", "Sky Blue", "Starlight"],
"iMac M4": ["Silver", "Blue", "Green", "Orange", "Pink", "Purple", "Yellow"],
"Studio Display": ["Light", "Dark"],
"Studio Display XDR": ["Light", "Dark"],
"Watch Series 11 42": ["Aluminum Jet Black + Sport Band Black", "Aluminum Jet Black + Sport Loop Dark Gray", "Aluminum Rose Gold + Sport Band Light Blush", "Aluminum Rose Gold + Sport Loop Purple Fog", "Aluminum Silver + Sport Band Neon Yellow", "Aluminum Silver + Sport Band Purple Fog", "Aluminum Silver + Sport Loop Forest", "Aluminum Silver + Sport Loop Neon Yellow", "Aluminum Space Gray + Sport Band Anchor Blue", "Aluminum Space Gray + Sport Band Black", "Aluminum Space Gray + Sport Loop Anchor Blue", "Aluminum Space Gray + Sport Loop Forest", "Titanium Gold + Magnetic Link Sage Gray", "Titanium Gold + Milanese Loop", "Titanium Gold + Sport Band Light Blush", "Titanium Gold + Sport Band Purple Fog", "Titanium Natural + Magnetic Link Caramel", "Titanium Natural + Milanese Loop", "Titanium Natural + Sport Band Stone Gray", "Titanium Slate + Magnetic Link Navy", "Titanium Slate + Milanese Loop", "Titanium Slate + Sport Band Black"],
"Watch Series 11 46": ["Aluminum Jet Black + Sport Band Black", "Aluminum Jet Black + Sport Loop Dark Gray", "Aluminum Rose Gold + Sport Band Light Blush", "Aluminum Rose Gold + Sport Loop Purple Fog", "Aluminum Silver + Sport Band Neon Yellow", "Aluminum Silver + Sport Band Purple Fog", "Aluminum Silver + Sport Loop Forest", "Aluminum Silver + Sport Loop Neon Yellow", "Aluminum Space Gray + Sport Band Anchor Blue", "Aluminum Space Gray + Sport Band Black", "Aluminum Space Gray + Sport Loop Anchor Blue", "Aluminum Space Gray + Sport Loop Forest", "Titanium Gold + Magnetic Link Sage Gray", "Titanium Gold + Milanese Loop", "Titanium Gold + Sport Band Light Blush", "Titanium Gold + Sport Band Purple Fog", "Titanium Natural + Magnetic Link Caramel", "Titanium Natural + Milanese Loop", "Titanium Natural + Sport Band Stone Gray", "Titanium Slate + Magnetic Link Navy", "Titanium Slate + Milanese Loop", "Titanium Slate + Sport Band Black"],
}
# Frame Variants: first item = default device
FRAME_VARIANTS = {
"iPhone 17 Portrait": ["iPhone 17 Pro Portrait", "iPhone 17 Portrait", "iPhone 16 Pro Portrait"],
"iPhone 17 Landscape": ["iPhone 17 Pro Landscape", "iPhone 17 Landscape", "iPhone 16 Pro Landscape"],
"iPhone 17 Pro Max Portrait": ["iPhone 17 Pro Max Portrait", "iPhone 16 Pro Max Portrait"],
"iPhone 17 Pro Max Landscape": ["iPhone 17 Pro Max Landscape", "iPhone 16 Pro Max Landscape"],
"iPhone 16 Portrait": ["iPhone 16 Portrait", "iPhone 15 Pro Portrait"],
"iPhone 16 Landscape": ["iPhone 16 Landscape", "iPhone 15 Pro Landscape"],
"iPhone 16 Plus Portrait": ["iPhone 16 Plus Portrait", "iPhone 15 Pro Max Portrait"],
"iPhone 16 Plus Landscape": ["iPhone 16 Plus Landscape", "iPhone 15 Pro Max Landscape"],
"MacBook Pro M5 14": ["MacBook Pro M5 14", "MacBook Pro 2021 14"],
"MacBook Pro M5 16": ["MacBook Pro M5 16", "MacBook Pro 2021 16"],
"MacBook Air M5 13": ["MacBook Air M5 13", "MacBook Air 2022"],
"Studio Display": ["Studio Display", "Studio Display XDR"],
"Watch Series 11 42": ["Watch Series 11 42", "Watch Series 10 42"],
"Watch Series 11 46": ["Watch Series 11 46", "Watch Series 10 46"],
}
# ── Core Engine ──────────────────────────────────────────────────────────────
def load_json(assets_dir):
"""Load the device dictionary from NewFrames.json."""
json_path = assets_dir / "NewFrames.json"
if not json_path.exists():
print(f"{C.red('Error')}: NewFrames.json not found at {json_path}", file=sys.stderr)
sys.exit(1)
try:
with open(json_path, encoding="utf-8") as f:
return json.load(f)
except json.JSONDecodeError as e:
print(f"{C.red('Error')}: Invalid JSON in {json_path}: {e}", file=sys.stderr)
sys.exit(1)
def detect_device(img, device_dict):
"""Detect device from screenshot dimensions using width + overlap height check."""
w, h = img.size
width_key = str(w)
if width_key not in device_dict:
return None, None
entry = device_dict[width_key]
# Check overlap (height disambiguation)
if "overlap" in entry:
height_key = str(h)
if height_key in entry["overlap"]:
entry = entry["overlap"][height_key]
else:
return None, None
return entry, entry["name"]
def resolve_variant(model_name, device_dict):
"""Apply variant resolution — first item in variant array is the default."""
if model_name not in FRAME_VARIANTS:
return None, model_name
variants = FRAME_VARIANTS[model_name]
default_variant = variants[0]
if default_variant != model_name:
# Load variant device data from JSON
if "variants" in device_dict and default_variant in device_dict["variants"]:
variant_data = device_dict["variants"][default_variant]
return variant_data, variant_data["name"]
return None, model_name
def load_config():
"""Load user config from ~/.config/frames/config.json."""
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
pass
return {}
def save_config(config):
"""Save user config."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile("w", dir=CONFIG_DIR, delete=False, encoding="utf-8") as tmp:
json.dump(config, tmp, indent=2)
tmp.write("\n")
tmp_path = Path(tmp.name)
os.replace(tmp_path, CONFIG_FILE)
def get_color(model_name, color_arg, user_defaults=None):
"""Resolve frame color for a device. Checks: CLI arg > user config > first in list."""
if model_name not in FRAME_COLORS:
return None
colors = FRAME_COLORS[model_name]
if not colors:
return None
if color_arg == "random":
return random.choice(colors)
elif color_arg:
for c in colors:
if c.lower() == color_arg.lower():
return c
try:
idx = int(color_arg) - 1
if 0 <= idx < len(colors):
return colors[idx]
except ValueError:
pass
print(f"{C.yellow('Warning')}: Color '{color_arg}' not found for {model_name}. Using default.", file=sys.stderr)
# Check user config for saved default
user_defaults = user_defaults or {}
# Strip orientation for lookup (user sets "iPhone 17 Pro" not "iPhone 17 Pro Portrait")
base = model_name.replace(" Portrait", "").replace(" Landscape", "")
if base in user_defaults:
saved = user_defaults[base]
if saved in colors:
return saved
return colors[0] # Fallback = first color
@lru_cache(maxsize=512)
def _load_rgba_asset_cached(path_str):
with Image.open(path_str) as image:
return image.convert("RGBA")
def load_frame(assets_dir, model_name, color):
"""Load the frame PNG for a device + color."""
if color:
frame_path = assets_dir / f"{model_name} {color}.png"
if not frame_path.exists():
# Fall back to colorless
frame_path = assets_dir / f"{model_name}.png"
else:
frame_path = assets_dir / f"{model_name}.png"
if not frame_path.exists():
return None, str(frame_path)
return _load_rgba_asset_cached(str(frame_path)).copy(), str(frame_path)
def load_mask(assets_dir, model_name):
"""Load mask PNG if it exists."""
mask_path = assets_dir / f"{model_name}_mask.png"
if mask_path.exists():
return _load_rgba_asset_cached(str(mask_path)).copy()
return None
def apply_mask(screenshot, mask):
"""Apply mask to screenshot — black pixels in mask make screenshot transparent."""
r, g, b, a = screenshot.split()
mask_r = mask.split()[0] # R channel: 0=clip, 255=keep
return Image.merge("RGBA", (r, g, b, mask_r))
def composite(screenshot, frame, x, y):
"""Alpha-composite: place screenshot on canvas, composite frame on top.
Produces fully opaque output at semi-transparent bezel inner edges."""
canvas = Image.new("RGBA", frame.size, (0, 0, 0, 0))
canvas.paste(screenshot, (x, y))
return Image.alpha_composite(canvas, frame)
def merge_images(images, spacing=60, physical_heights=None):
"""Merge multiple images horizontally with spacing.
When physical_heights is provided and values differ, images are scaled
proportionally (tallest = 1.0) and bottom-aligned. Otherwise, original
center-aligned behavior is preserved."""
if len(images) == 1:
return images[0]
do_scale = (
physical_heights is not None
and len(physical_heights) == len(images)
and len(set(physical_heights)) > 1
)
if do_scale:
# Normalize all frames to the same pixels-per-mm ratio.
# The device with the lowest px/mm (coarsest frame) keeps native size;
# everything else scales down. This avoids upscaling artifacts.
px_per_mm = [img.height / ph for img, ph in zip(images, physical_heights)]
ref_ppm = min(px_per_mm)
scaled = []
for img, ph in zip(images, physical_heights):
target_h = round(ph * ref_ppm)
scale = target_h / img.height
if scale < 0.999:
new_w = max(1, round(img.width * scale))
new_h = max(1, target_h)
scaled.append(img.resize((new_w, new_h), Image.LANCZOS))
else:
scaled.append(img)
images = scaled
total_width = sum(img.width for img in images) + spacing * (len(images) - 1)
max_height = max(img.height for img in images)
merged = Image.new("RGBA", (total_width, max_height), (0, 0, 0, 0))
x_offset = 0
for img in images:
if do_scale:
y_offset = max_height - img.height # Bottom-align
else:
y_offset = (max_height - img.height) // 2 # Center-align
merged.paste(img, (x_offset, y_offset), img)
x_offset += img.width + spacing
return merged
def ensure_output_dir(path):
"""Create output directory or raise a clean write error."""
try:
path.mkdir(parents=True, exist_ok=True)
except OSError as e:
raise OSError(f"Could not create output directory {path}: {e}") from e
def save_png(image, path):
"""Save a PNG or raise a clean write error."""
try:
image.save(path, "PNG")
except OSError as e:
raise OSError(f"Could not save {path}: {e}") from e
def guard_image_size(width, height, source):
"""Warn on very large images and reject extreme dimensions."""
largest = max(width, height)
if largest > LARGE_IMAGE_MAX_DIMENSION:
raise ValueError(
f"Refusing to process {source}: image dimensions exceed "
f"{LARGE_IMAGE_MAX_DIMENSION}px ({width}x{height})."
)
if largest > LARGE_IMAGE_WARN_DIMENSION:
print(
f"{C.yellow('Warning')}: Large image {source} ({width}x{height}) "
f"may use significant memory.",
file=sys.stderr,
)
def build_device_name_index(device_dict):
"""Build a name→device-entry lookup for exact --device matches."""
index = {}
for key, val in device_dict.items():
if key == "variants":
continue
sub_entries = list(val.get("overlap", {}).values()) or [val]
for entry in sub_entries:
index[entry["name"]] = entry
for name, entry in device_dict.get("variants", {}).items():
index[name] = entry
return index
def frame_screenshot(
img_path,
assets_dir,
device_dict,
color_arg=None,
force_device=None,
verbose=False,
user_defaults=None,
device_index=None,
):
"""Frame a single screenshot. Returns (framed_image, device_info_dict) or raises."""
with Image.open(img_path) as opened:
w, h = opened.size
guard_image_size(w, h, img_path)
img = opened.convert("RGBA")
# 1. Device detection
if force_device:
entry = (device_index or build_device_name_index(device_dict)).get(force_device)
if not entry:
raise ValueError(f"Device '{force_device}' not found in dictionary")
model_name = entry["name"]
else:
entry, model_name = detect_device(img, device_dict)
if not entry:
raise ValueError(f"Unknown device for {w}x{h} screenshot. Use 'frames list' to see supported devices.")
# 2. Variant resolution (skip auto-resolution when --device explicitly selects a frame)
if not force_device:
variant_data, model_name = resolve_variant(model_name, device_dict)
if variant_data:
entry = variant_data
if verbose:
print(f" {C.dim('Variant resolved:')} {model_name}")
# 3. Color
has_colors = entry.get("colors") == "yes"
color = get_color(model_name, color_arg, user_defaults=user_defaults) if has_colors else None
# 4. Resize (for More Space resolutions)
resize_width = entry.get("resizeWidth")
if resize_width:
resize_width = int(resize_width)
ratio = resize_width / img.width
new_h = int(img.height * ratio)
img = img.resize((resize_width, new_h), Image.LANCZOS)
if verbose:
print(f" {C.dim('Resized:')} {w}x{h} → {resize_width}x{new_h}")
# 5. Load frame
frame, frame_path = load_frame(assets_dir, model_name, color)
if not frame:
raise FileNotFoundError(f"Frame asset not found: {frame_path}")
# 6. Apply mask
has_mask = entry.get("mask") == "yes"
mask_missing = False
if has_mask:
mask = load_mask(assets_dir, model_name)
if mask:
# Ensure mask matches screenshot dimensions
if mask.size != img.size:
mask = mask.resize(img.size, Image.LANCZOS)
img = apply_mask(img, mask)
if verbose:
print(f" {C.dim('Mask applied')}")
else:
mask_missing = True
print(f" {C.yellow('Warning')}: mask file missing for {model_name} "
f"(expected {model_name}_mask.png). Rendering without mask — "
f"corners may show screenshot bleed.", file=sys.stderr)
# 7. Composite
x, y = int(entry["x"]), int(entry["y"])
result = composite(img, frame, x, y)
info = {
"source": str(img_path),
"device": model_name,
"color": color,
"dimensions": f"{w}x{h}",
"frame_size": f"{result.width}x{result.height}",
"resized": bool(resize_width),
"masked": has_mask and not mask_missing,
"mask_missing": mask_missing,
"physicalHeight": float(entry.get("physicalHeight", 0)),
}
return result, info
# ── CLI Commands ─────────────────────────────────────────────────────────────
def cmd_frame(args):
"""Frame one or more screenshots."""
assets_dir = Path(args.assets) if hasattr(args, 'assets') and args.assets else get_assets_dir()
device_dict = load_json(assets_dir)
config = load_config()
user_defaults = config.get("default_colors", {})
device_index = build_device_name_index(device_dict)
if not args.files:
print(f"{C.red('Error')}: No input files specified.", file=sys.stderr)
sys.exit(1)
batch_size = getattr(args, 'batch', None)
if batch_size is not None and batch_size < 2:
print(f"{C.red('Error')}: --batch must be at least 2.", file=sys.stderr)
sys.exit(1)
if args.spacing < 0:
print(f"{C.red('Error')}: --spacing must be 0 or greater.", file=sys.stderr)
sys.exit(1)
# Expand directories into image files
expanded = _gather_image_paths(args.files)
if not expanded:
print(f"{C.red('Error')}: No images found in the specified paths.", file=sys.stderr)
sys.exit(1)
try:
subfolder = get_subfolder_setting(args, config=config)
except ValueError as e:
print(f"{C.red('Error')}: {e}", file=sys.stderr)
sys.exit(1)
framed = []
infos = []
for p in expanded:
try:
if not args.json:
print(f" {C.dim('Framing')} {p.name}...", end=" ", flush=True)
result, info = frame_screenshot(
p, assets_dir, device_dict,
color_arg=args.color,
force_device=args.device,
verbose=args.verbose,
user_defaults=user_defaults,
device_index=device_index,
)
framed.append((result, p, info))
infos.append(info)
if not args.json:
color_str = f" ({C.rgb(235, 125, 40, info['color'])})" if info["color"] else ""
print(f"{C.green(info['device'])}{color_str}")
except (
ValueError,
FileNotFoundError,
OSError,
UnidentifiedImageError,
Image.DecompressionBombWarning,
Image.DecompressionBombError,
) as e:
print(f"{C.red('Error')}: {e}", file=sys.stderr)
continue
if not framed:
print(f"{C.red('No screenshots were framed.')}", file=sys.stderr)
sys.exit(1)
# Merge if requested (--merge or --batch implies merge)
do_merge = args.merge or batch_size
if do_merge and len(framed) > 1:
# Split into batches
if batch_size and batch_size > 0:
batches = [framed[i:i+batch_size] for i in range(0, len(framed), batch_size)]
else:
batches = [framed] # Single batch = merge all
if args.output:
out_dir = Path(args.output)
elif subfolder:
out_dir = framed[0][1].parent / subfolder
else:
out_dir = framed[0][1].parent
try:
ensure_output_dir(out_dir)
except OSError as e:
print(f"{C.red('Error')}: {e}", file=sys.stderr)
sys.exit(1)
merged_outputs = []
for batch_idx, batch in enumerate(batches):
images = [f[0] for f in batch]
# Collect physical heights for proportional scaling
no_scale = getattr(args, 'no_scale', False)
if not no_scale:
phs = [f[2].get("physicalHeight", 0) for f in batch]
physical_heights = phs if all(ph > 0 for ph in phs) else None
else:
physical_heights = None
if len(images) == 1:
merged = images[0]
else:
merged = merge_images(images, spacing=args.spacing, physical_heights=physical_heights)
if len(batches) == 1:
out_name = "merged_framed.png"
else:
out_name = f"merged_{batch_idx + 1}_framed.png"
out_path = out_dir / out_name
try: