otowall 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- otowall/__init__.py +3 -0
- otowall/__main__.py +13 -0
- otowall/apply_timing.py +69 -0
- otowall/art_background_upgrade.py +130 -0
- otowall/art_cache.py +83 -0
- otowall/art_resolution.py +338 -0
- otowall/ascii_composer.py +875 -0
- otowall/auth.py +283 -0
- otowall/cli.py +429 -0
- otowall/compose_verify.py +99 -0
- otowall/composer.py +947 -0
- otowall/config.py +67 -0
- otowall/cover_art.py +55 -0
- otowall/env_loader.py +102 -0
- otowall/fonts/Inter-Bold.ttf +0 -0
- otowall/fonts/Inter-Medium.ttf +0 -0
- otowall/fonts/Inter-Regular.ttf +0 -0
- otowall/fonts/Inter-SemiBold.ttf +0 -0
- otowall/fonts/OFL.txt +92 -0
- otowall/fonts/__init__.py +1 -0
- otowall/logging_setup.py +104 -0
- otowall/platforms/__init__.py +44 -0
- otowall/platforms/autostart.py +310 -0
- otowall/platforms/base.py +60 -0
- otowall/platforms/linux.py +146 -0
- otowall/platforms/linux_backends.py +471 -0
- otowall/platforms/linux_de.py +90 -0
- otowall/platforms/linux_screen.py +142 -0
- otowall/platforms/macos.py +214 -0
- otowall/platforms/windows.py +328 -0
- otowall/platforms/windows_com.py +220 -0
- otowall/platforms/windows_com_ctypes.py +207 -0
- otowall/platforms/windows_console.py +42 -0
- otowall/platforms/windows_diag.py +238 -0
- otowall/platforms/windows_dpi.py +363 -0
- otowall/platforms/windows_monitors.py +440 -0
- otowall/platforms/windows_restore.py +477 -0
- otowall/platforms/windows_virtual_compose.py +127 -0
- otowall/playback_diag.py +102 -0
- otowall/playback_factory.py +46 -0
- otowall/playback_source.py +48 -0
- otowall/playback_types.py +35 -0
- otowall/poll_watchdog.py +65 -0
- otowall/runner.py +601 -0
- otowall/single_instance.py +172 -0
- otowall/sources/__init__.py +1 -0
- otowall/sources/base.py +21 -0
- otowall/sources/local/__init__.py +25 -0
- otowall/sources/local/base.py +22 -0
- otowall/sources/local/linux_mpris.py +79 -0
- otowall/sources/local/macos_spotify.py +65 -0
- otowall/sources/local/unsupported.py +15 -0
- otowall/sources/local/windows_smtc.py +42 -0
- otowall/sources/local/windows_smtc_async.py +110 -0
- otowall/sources/local/windows_smtc_thumbnail.py +76 -0
- otowall/sources/local/windows_smtc_winrt.py +29 -0
- otowall/sources/local/windows_smtc_worker.py +168 -0
- otowall/sources/spotify_provider.py +49 -0
- otowall/spotify_art.py +159 -0
- otowall/verification/__init__.py +1 -0
- otowall/verification/wallpaper_analysis.py +404 -0
- otowall/verification/windows_display.py +89 -0
- otowall/wallpaper_snapshot.py +155 -0
- otowall/wallpaper_state.py +72 -0
- otowall-1.1.0.dist-info/METADATA +341 -0
- otowall-1.1.0.dist-info/RECORD +69 -0
- otowall-1.1.0.dist-info/WHEEL +4 -0
- otowall-1.1.0.dist-info/entry_points.txt +7 -0
- otowall-1.1.0.dist-info/licenses/LICENSE +622 -0
otowall/__init__.py
ADDED
otowall/__main__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Allow ``python -m otowall``."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
if sys.platform == "win32":
|
|
6
|
+
from otowall.platforms.windows_dpi import set_process_dpi_aware
|
|
7
|
+
|
|
8
|
+
set_process_dpi_aware()
|
|
9
|
+
|
|
10
|
+
from otowall.cli import main
|
|
11
|
+
|
|
12
|
+
if __name__ == "__main__":
|
|
13
|
+
raise SystemExit(main())
|
otowall/apply_timing.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Wallpaper apply stage timings for profiling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ApplyTiming:
|
|
16
|
+
enabled: bool = True
|
|
17
|
+
fetch_seconds: float = 0.0
|
|
18
|
+
compose_seconds: float = 0.0
|
|
19
|
+
save_seconds: float = 0.0
|
|
20
|
+
set_seconds: float = 0.0
|
|
21
|
+
cache_status: str = "miss"
|
|
22
|
+
_stages: dict[str, float] = field(default_factory=dict)
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def disabled(cls) -> ApplyTiming:
|
|
26
|
+
return cls(enabled=False)
|
|
27
|
+
|
|
28
|
+
def note_cache(self, status: str) -> None:
|
|
29
|
+
self.cache_status = status
|
|
30
|
+
|
|
31
|
+
@contextmanager
|
|
32
|
+
def stage(self, name: str) -> Iterator[None]:
|
|
33
|
+
if not self.enabled:
|
|
34
|
+
yield
|
|
35
|
+
return
|
|
36
|
+
started = time.perf_counter()
|
|
37
|
+
try:
|
|
38
|
+
yield
|
|
39
|
+
finally:
|
|
40
|
+
elapsed = time.perf_counter() - started
|
|
41
|
+
self._stages[name] = self._stages.get(name, 0.0) + elapsed
|
|
42
|
+
if name == "fetch":
|
|
43
|
+
self.fetch_seconds += elapsed
|
|
44
|
+
elif name == "compose":
|
|
45
|
+
self.compose_seconds += elapsed
|
|
46
|
+
elif name == "save":
|
|
47
|
+
self.save_seconds += elapsed
|
|
48
|
+
elif name == "set":
|
|
49
|
+
self.set_seconds += elapsed
|
|
50
|
+
logger.debug("Apply stage %s took %.3fs", name, elapsed)
|
|
51
|
+
|
|
52
|
+
def log_summary(self, *, prefix: str | None = None) -> None:
|
|
53
|
+
if not self.enabled:
|
|
54
|
+
return
|
|
55
|
+
total = sum(self._stages.values())
|
|
56
|
+
for name, elapsed in sorted(self._stages.items()):
|
|
57
|
+
if name not in {"fetch", "compose", "save", "set"}:
|
|
58
|
+
logger.debug("Apply stage %s took %.3fs (detail)", name, elapsed)
|
|
59
|
+
lead = f"{prefix} " if prefix else ""
|
|
60
|
+
logger.info(
|
|
61
|
+
"%sApply took %.2fs (fetch=%.2fs, compose=%.2fs, save=%.2fs, set=%.2fs, cache=%s)",
|
|
62
|
+
lead,
|
|
63
|
+
total,
|
|
64
|
+
self.fetch_seconds,
|
|
65
|
+
self.compose_seconds,
|
|
66
|
+
self.save_seconds,
|
|
67
|
+
self.set_seconds,
|
|
68
|
+
self.cache_status,
|
|
69
|
+
)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Background iTunes art upgrade (never blocks the first SMTC apply)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import logging
|
|
7
|
+
import threading
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
from PIL import Image
|
|
12
|
+
|
|
13
|
+
from otowall.art_resolution import (
|
|
14
|
+
ITUNES_UPGRADE_OVER_SMTC_MIN_PX,
|
|
15
|
+
try_fetch_itunes_upgrade,
|
|
16
|
+
)
|
|
17
|
+
from otowall.playback_types import TrackPlayback
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class ArtUpgradeTicket:
|
|
24
|
+
generation: int
|
|
25
|
+
track_id: str
|
|
26
|
+
smtc_max_dim: int
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BackgroundArtUpgrader:
|
|
30
|
+
"""Fetches higher-res iTunes art off the apply hot path."""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self._lock = threading.Lock()
|
|
34
|
+
self._generation = 0
|
|
35
|
+
self._thread: threading.Thread | None = None
|
|
36
|
+
|
|
37
|
+
def cancel_pending(self) -> None:
|
|
38
|
+
with self._lock:
|
|
39
|
+
self._generation += 1
|
|
40
|
+
|
|
41
|
+
def should_schedule(self, track: TrackPlayback) -> bool:
|
|
42
|
+
if not track.art_bytes:
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
with Image.open(io.BytesIO(track.art_bytes)) as image:
|
|
47
|
+
smtc_max = max(image.size)
|
|
48
|
+
except OSError:
|
|
49
|
+
return False
|
|
50
|
+
return smtc_max < ITUNES_UPGRADE_OVER_SMTC_MIN_PX
|
|
51
|
+
|
|
52
|
+
def schedule(
|
|
53
|
+
self,
|
|
54
|
+
track: TrackPlayback,
|
|
55
|
+
*,
|
|
56
|
+
download_dir,
|
|
57
|
+
session: requests.Session | None,
|
|
58
|
+
on_upgraded,
|
|
59
|
+
is_still_valid,
|
|
60
|
+
) -> None:
|
|
61
|
+
if not self.should_schedule(track):
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
with Image.open(io.BytesIO(track.art_bytes)) as image:
|
|
66
|
+
smtc_max = max(image.size)
|
|
67
|
+
except OSError:
|
|
68
|
+
return
|
|
69
|
+
with self._lock:
|
|
70
|
+
self._generation += 1
|
|
71
|
+
generation = self._generation
|
|
72
|
+
ticket = ArtUpgradeTicket(
|
|
73
|
+
generation=generation,
|
|
74
|
+
track_id=track.track_id,
|
|
75
|
+
smtc_max_dim=smtc_max,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def _worker() -> None:
|
|
79
|
+
try:
|
|
80
|
+
upgraded = try_fetch_itunes_upgrade(
|
|
81
|
+
track,
|
|
82
|
+
smtc_max_dim=ticket.smtc_max_dim,
|
|
83
|
+
download_dir=download_dir,
|
|
84
|
+
session=session,
|
|
85
|
+
)
|
|
86
|
+
except Exception:
|
|
87
|
+
logger.warning(
|
|
88
|
+
"Background iTunes art upgrade failed for %s — %s",
|
|
89
|
+
track.artist,
|
|
90
|
+
track.title,
|
|
91
|
+
exc_info=True,
|
|
92
|
+
)
|
|
93
|
+
return
|
|
94
|
+
if upgraded is None:
|
|
95
|
+
return
|
|
96
|
+
with self._lock:
|
|
97
|
+
if ticket.generation != self._generation:
|
|
98
|
+
logger.debug("Ignoring stale iTunes upgrade (generation)")
|
|
99
|
+
return
|
|
100
|
+
if not is_still_valid(ticket):
|
|
101
|
+
logger.debug("Ignoring stale iTunes upgrade (playback changed)")
|
|
102
|
+
return
|
|
103
|
+
new_track = TrackPlayback(
|
|
104
|
+
track_id=track.track_id,
|
|
105
|
+
art_url=track.art_url,
|
|
106
|
+
title=track.title,
|
|
107
|
+
artist=track.artist,
|
|
108
|
+
album=track.album,
|
|
109
|
+
is_playing=True,
|
|
110
|
+
art_bytes=upgraded.image_bytes,
|
|
111
|
+
)
|
|
112
|
+
logger.info(
|
|
113
|
+
"Upgraded art via iTunes (%dx%d -> %dx%d) for %s — %s",
|
|
114
|
+
upgraded.smtc_width,
|
|
115
|
+
upgraded.smtc_height,
|
|
116
|
+
upgraded.width,
|
|
117
|
+
upgraded.height,
|
|
118
|
+
track.artist,
|
|
119
|
+
track.title,
|
|
120
|
+
)
|
|
121
|
+
on_upgraded(new_track, ticket)
|
|
122
|
+
|
|
123
|
+
thread = threading.Thread(
|
|
124
|
+
target=_worker,
|
|
125
|
+
name="itunes-art-upgrade",
|
|
126
|
+
daemon=True,
|
|
127
|
+
)
|
|
128
|
+
with self._lock:
|
|
129
|
+
self._thread = thread
|
|
130
|
+
thread.start()
|
otowall/art_cache.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Bounded on-disk cache for composed wallpapers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from otowall.config import COMPOSED_CACHE_MAX_ENTRIES, COMPOSED_CACHE_VERSION
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ComposedArtCache:
|
|
12
|
+
"""Maps track + resolution to a composed PNG on disk."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, cache_dir: Path, *, max_entries: int = COMPOSED_CACHE_MAX_ENTRIES) -> None:
|
|
15
|
+
self.cache_dir = cache_dir
|
|
16
|
+
self.max_entries = max_entries
|
|
17
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
18
|
+
|
|
19
|
+
def _key_path(
|
|
20
|
+
self,
|
|
21
|
+
track_id: str,
|
|
22
|
+
art_material_key: str,
|
|
23
|
+
width: int,
|
|
24
|
+
height: int,
|
|
25
|
+
*,
|
|
26
|
+
layout_signature: str | None = None,
|
|
27
|
+
) -> Path:
|
|
28
|
+
layout_part = f"|{layout_signature}" if layout_signature else ""
|
|
29
|
+
digest = hashlib.sha256(
|
|
30
|
+
f"{COMPOSED_CACHE_VERSION}{layout_part}|{track_id}|{art_material_key}|{width}x{height}".encode(),
|
|
31
|
+
).hexdigest()[:32]
|
|
32
|
+
return self.cache_dir / f"{digest}.png"
|
|
33
|
+
|
|
34
|
+
def get(
|
|
35
|
+
self,
|
|
36
|
+
track_id: str,
|
|
37
|
+
art_material_key: str,
|
|
38
|
+
width: int,
|
|
39
|
+
height: int,
|
|
40
|
+
*,
|
|
41
|
+
layout_signature: str | None = None,
|
|
42
|
+
) -> Path | None:
|
|
43
|
+
path = self._key_path(
|
|
44
|
+
track_id,
|
|
45
|
+
art_material_key,
|
|
46
|
+
width,
|
|
47
|
+
height,
|
|
48
|
+
layout_signature=layout_signature,
|
|
49
|
+
)
|
|
50
|
+
if path.is_file():
|
|
51
|
+
path.touch()
|
|
52
|
+
return path
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
def put(
|
|
56
|
+
self,
|
|
57
|
+
track_id: str,
|
|
58
|
+
art_material_key: str,
|
|
59
|
+
width: int,
|
|
60
|
+
height: int,
|
|
61
|
+
source: Path,
|
|
62
|
+
*,
|
|
63
|
+
layout_signature: str | None = None,
|
|
64
|
+
) -> Path:
|
|
65
|
+
dest = self._key_path(
|
|
66
|
+
track_id,
|
|
67
|
+
art_material_key,
|
|
68
|
+
width,
|
|
69
|
+
height,
|
|
70
|
+
layout_signature=layout_signature,
|
|
71
|
+
)
|
|
72
|
+
dest.write_bytes(source.read_bytes())
|
|
73
|
+
self._evict_if_needed()
|
|
74
|
+
return dest
|
|
75
|
+
|
|
76
|
+
def _evict_if_needed(self) -> None:
|
|
77
|
+
entries = sorted(
|
|
78
|
+
self.cache_dir.glob("*.png"),
|
|
79
|
+
key=lambda p: p.stat().st_mtime,
|
|
80
|
+
)
|
|
81
|
+
while len(entries) > self.max_entries:
|
|
82
|
+
oldest = entries.pop(0)
|
|
83
|
+
oldest.unlink(missing_ok=True)
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Resolve album art when SMTC bytes or Spotify URLs are missing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from urllib.parse import quote
|
|
13
|
+
|
|
14
|
+
import requests
|
|
15
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
16
|
+
|
|
17
|
+
from otowall.config import online_art_enabled
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
ITUNES_SEARCH_URL = "https://itunes.apple.com/search"
|
|
22
|
+
ITUNES_TIMEOUT_SECONDS = 5.0
|
|
23
|
+
ITUNES_BLOCKING_TIMEOUT_SECONDS = 2.5
|
|
24
|
+
PLACEHOLDER_SIZE = 1000
|
|
25
|
+
ITUNES_UPGRADE_OVER_SMTC_MIN_PX = 600
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class ResolvedArt:
|
|
30
|
+
image_bytes: bytes
|
|
31
|
+
source: str
|
|
32
|
+
width: int
|
|
33
|
+
height: int
|
|
34
|
+
detail: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class ItunesUpgradeResult:
|
|
39
|
+
image_bytes: bytes
|
|
40
|
+
width: int
|
|
41
|
+
height: int
|
|
42
|
+
smtc_width: int
|
|
43
|
+
smtc_height: int
|
|
44
|
+
detail: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _normalize_name(value: str) -> str:
|
|
48
|
+
lowered = value.casefold().strip()
|
|
49
|
+
return re.sub(r"[^a-z0-9]+", "", lowered)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def artist_names_match(expected: str, candidate: str) -> bool:
|
|
53
|
+
expected_norm = _normalize_name(expected)
|
|
54
|
+
candidate_norm = _normalize_name(candidate)
|
|
55
|
+
if not expected_norm or not candidate_norm:
|
|
56
|
+
return False
|
|
57
|
+
if expected_norm == candidate_norm:
|
|
58
|
+
return True
|
|
59
|
+
if expected_norm in candidate_norm or candidate_norm in expected_norm:
|
|
60
|
+
return True
|
|
61
|
+
expected_tokens = {t for t in re.split(r"[^a-z0-9]+", expected.casefold()) if t}
|
|
62
|
+
candidate_tokens = {t for t in re.split(r"[^a-z0-9]+", candidate.casefold()) if t}
|
|
63
|
+
if not expected_tokens or not candidate_tokens:
|
|
64
|
+
return False
|
|
65
|
+
overlap = expected_tokens & candidate_tokens
|
|
66
|
+
return len(overlap) >= min(len(expected_tokens), len(candidate_tokens), 1)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _itunes_cache_path(cache_dir: Path, artist: str, title: str) -> Path:
|
|
70
|
+
key = hashlib.sha256(f"{artist}\0{title}".encode()).hexdigest()[:32]
|
|
71
|
+
return cache_dir / "itunes" / f"{key}.json"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def lookup_itunes_artwork_url(
|
|
75
|
+
artist: str,
|
|
76
|
+
title: str,
|
|
77
|
+
*,
|
|
78
|
+
session: requests.Session,
|
|
79
|
+
cache_dir: Path,
|
|
80
|
+
) -> str | None:
|
|
81
|
+
if not online_art_enabled():
|
|
82
|
+
return None
|
|
83
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
cache_path = _itunes_cache_path(cache_dir, artist, title)
|
|
85
|
+
if cache_path.is_file():
|
|
86
|
+
try:
|
|
87
|
+
payload = json.loads(cache_path.read_text(encoding="utf-8"))
|
|
88
|
+
cached_url = payload.get("artwork_url")
|
|
89
|
+
if isinstance(cached_url, str) and cached_url:
|
|
90
|
+
return cached_url
|
|
91
|
+
except (OSError, json.JSONDecodeError, TypeError):
|
|
92
|
+
logger.warning("Could not read iTunes art cache at %s", cache_path, exc_info=True)
|
|
93
|
+
|
|
94
|
+
term = quote(f"{artist} {title}")
|
|
95
|
+
url = f"{ITUNES_SEARCH_URL}?term={term}&entity=song&limit=5"
|
|
96
|
+
try:
|
|
97
|
+
response = session.get(url, timeout=ITUNES_TIMEOUT_SECONDS)
|
|
98
|
+
response.raise_for_status()
|
|
99
|
+
data = response.json()
|
|
100
|
+
except Exception:
|
|
101
|
+
logger.warning("iTunes artwork lookup failed for %s — %s", artist, title, exc_info=True)
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
results = data.get("results") or []
|
|
105
|
+
for entry in results:
|
|
106
|
+
if not isinstance(entry, dict):
|
|
107
|
+
continue
|
|
108
|
+
candidate_artist = str(entry.get("artistName") or "")
|
|
109
|
+
if not artist_names_match(artist, candidate_artist):
|
|
110
|
+
continue
|
|
111
|
+
artwork = entry.get("artworkUrl100")
|
|
112
|
+
if not isinstance(artwork, str) or not artwork:
|
|
113
|
+
continue
|
|
114
|
+
hi_res = artwork.replace("100x100bb", "1000x1000bb")
|
|
115
|
+
try:
|
|
116
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
117
|
+
cache_path.write_text(
|
|
118
|
+
json.dumps({"artwork_url": hi_res}),
|
|
119
|
+
encoding="utf-8",
|
|
120
|
+
)
|
|
121
|
+
except OSError:
|
|
122
|
+
logger.warning("Could not write iTunes art cache at %s", cache_path, exc_info=True)
|
|
123
|
+
return hi_res
|
|
124
|
+
logger.info("iTunes artwork lookup found no match for %s — %s", artist, title)
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _placeholder_colors(
|
|
129
|
+
artist: str,
|
|
130
|
+
title: str,
|
|
131
|
+
) -> tuple[tuple[int, int, int], tuple[int, int, int]]:
|
|
132
|
+
digest = hashlib.sha256(f"{artist}\0{title}".encode()).digest()
|
|
133
|
+
base = (
|
|
134
|
+
40 + digest[0] % 120,
|
|
135
|
+
45 + digest[1] % 110,
|
|
136
|
+
70 + digest[2] % 100,
|
|
137
|
+
)
|
|
138
|
+
accent = (
|
|
139
|
+
min(base[0] + 80, 255),
|
|
140
|
+
min(base[1] + 60, 255),
|
|
141
|
+
min(base[2] + 40, 255),
|
|
142
|
+
)
|
|
143
|
+
return base, accent
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def render_placeholder_cover(
|
|
147
|
+
title: str,
|
|
148
|
+
artist: str,
|
|
149
|
+
*,
|
|
150
|
+
size: int = PLACEHOLDER_SIZE,
|
|
151
|
+
) -> Image.Image:
|
|
152
|
+
top_rgb, bottom_rgb = _placeholder_colors(artist, title)
|
|
153
|
+
image = Image.new("RGB", (size, size))
|
|
154
|
+
draw = ImageDraw.Draw(image)
|
|
155
|
+
for y in range(size):
|
|
156
|
+
blend = y / max(size - 1, 1)
|
|
157
|
+
color = tuple(
|
|
158
|
+
int(top_rgb[channel] * (1 - blend) + bottom_rgb[channel] * blend)
|
|
159
|
+
for channel in range(3)
|
|
160
|
+
)
|
|
161
|
+
draw.line([(0, y), (size, y)], fill=color)
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
title_font = ImageFont.truetype("DejaVuSans-Bold.ttf", size=size // 14)
|
|
165
|
+
except OSError:
|
|
166
|
+
title_font = ImageFont.load_default()
|
|
167
|
+
|
|
168
|
+
margin = size // 10
|
|
169
|
+
text = title.strip() or "Unknown Title"
|
|
170
|
+
subtitle = artist.strip() or "Unknown Artist"
|
|
171
|
+
draw.multiline_text(
|
|
172
|
+
(margin, size // 2 - size // 8),
|
|
173
|
+
f"{text}\n{subtitle}",
|
|
174
|
+
fill=(245, 245, 250),
|
|
175
|
+
font=title_font,
|
|
176
|
+
spacing=8,
|
|
177
|
+
)
|
|
178
|
+
return image.convert("RGBA")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _image_to_png_bytes(image: Image.Image) -> bytes:
|
|
182
|
+
buffer = io.BytesIO()
|
|
183
|
+
image.save(buffer, format="PNG")
|
|
184
|
+
return buffer.getvalue()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _download_itunes_art(
|
|
188
|
+
track,
|
|
189
|
+
*,
|
|
190
|
+
download_dir: Path,
|
|
191
|
+
session: requests.Session,
|
|
192
|
+
timeout_seconds: float = ITUNES_TIMEOUT_SECONDS,
|
|
193
|
+
) -> ResolvedArt | None:
|
|
194
|
+
if not online_art_enabled():
|
|
195
|
+
return None
|
|
196
|
+
itunes_url = lookup_itunes_artwork_url(
|
|
197
|
+
track.artist,
|
|
198
|
+
track.title,
|
|
199
|
+
session=session,
|
|
200
|
+
cache_dir=download_dir,
|
|
201
|
+
)
|
|
202
|
+
if not itunes_url:
|
|
203
|
+
return None
|
|
204
|
+
try:
|
|
205
|
+
response = session.get(itunes_url, timeout=timeout_seconds)
|
|
206
|
+
response.raise_for_status()
|
|
207
|
+
data = response.content
|
|
208
|
+
with Image.open(io.BytesIO(data)) as image:
|
|
209
|
+
width, height = image.size
|
|
210
|
+
return ResolvedArt(
|
|
211
|
+
image_bytes=data,
|
|
212
|
+
source="itunes",
|
|
213
|
+
width=width,
|
|
214
|
+
height=height,
|
|
215
|
+
detail=itunes_url,
|
|
216
|
+
)
|
|
217
|
+
except (requests.RequestException, OSError):
|
|
218
|
+
logger.warning(
|
|
219
|
+
"Failed to download iTunes artwork for %s — %s",
|
|
220
|
+
track.artist,
|
|
221
|
+
track.title,
|
|
222
|
+
exc_info=True,
|
|
223
|
+
)
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def try_fetch_itunes_upgrade(
|
|
228
|
+
track,
|
|
229
|
+
*,
|
|
230
|
+
smtc_max_dim: int,
|
|
231
|
+
download_dir: Path,
|
|
232
|
+
session: requests.Session | None = None,
|
|
233
|
+
) -> ItunesUpgradeResult | None:
|
|
234
|
+
"""Return iTunes bytes only when strictly larger than the current SMTC thumbnail."""
|
|
235
|
+
if not online_art_enabled() or not track.art_bytes:
|
|
236
|
+
return None
|
|
237
|
+
http = session or requests.Session()
|
|
238
|
+
upgraded = _download_itunes_art(
|
|
239
|
+
track,
|
|
240
|
+
download_dir=download_dir,
|
|
241
|
+
session=http,
|
|
242
|
+
timeout_seconds=ITUNES_TIMEOUT_SECONDS,
|
|
243
|
+
)
|
|
244
|
+
if upgraded is None:
|
|
245
|
+
return None
|
|
246
|
+
upgraded_max = max(upgraded.width, upgraded.height)
|
|
247
|
+
if upgraded_max <= smtc_max_dim:
|
|
248
|
+
return None
|
|
249
|
+
with Image.open(io.BytesIO(track.art_bytes)) as image:
|
|
250
|
+
smtc_w, smtc_h = image.size
|
|
251
|
+
return ItunesUpgradeResult(
|
|
252
|
+
image_bytes=upgraded.image_bytes,
|
|
253
|
+
width=upgraded.width,
|
|
254
|
+
height=upgraded.height,
|
|
255
|
+
smtc_width=smtc_w,
|
|
256
|
+
smtc_height=smtc_h,
|
|
257
|
+
detail=upgraded.detail,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def resolve_track_art(
|
|
262
|
+
track,
|
|
263
|
+
*,
|
|
264
|
+
download_dir: Path,
|
|
265
|
+
session: requests.Session | None = None,
|
|
266
|
+
) -> ResolvedArt:
|
|
267
|
+
"""Resolve cover bytes using SMTC, Spotify URL, iTunes, then placeholder."""
|
|
268
|
+
http = session or requests.Session()
|
|
269
|
+
|
|
270
|
+
if track.art_bytes:
|
|
271
|
+
with Image.open(io.BytesIO(track.art_bytes)) as image:
|
|
272
|
+
width, height = image.size
|
|
273
|
+
return ResolvedArt(
|
|
274
|
+
image_bytes=track.art_bytes,
|
|
275
|
+
source="smtc_thumbnail",
|
|
276
|
+
width=width,
|
|
277
|
+
height=height,
|
|
278
|
+
detail=f"{len(track.art_bytes)} bytes",
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if track.art_url and online_art_enabled():
|
|
282
|
+
from otowall.spotify_art import download_album_art
|
|
283
|
+
|
|
284
|
+
download_path = download_dir / f"{track.track_id}.jpg"
|
|
285
|
+
download_album_art(track.art_url, download_path, session=http)
|
|
286
|
+
data = download_path.read_bytes()
|
|
287
|
+
with Image.open(download_path) as image:
|
|
288
|
+
width, height = image.size
|
|
289
|
+
return ResolvedArt(
|
|
290
|
+
image_bytes=data,
|
|
291
|
+
source="spotify_url",
|
|
292
|
+
width=width,
|
|
293
|
+
height=height,
|
|
294
|
+
detail=track.art_url,
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
itunes = _download_itunes_art(
|
|
298
|
+
track,
|
|
299
|
+
download_dir=download_dir,
|
|
300
|
+
session=http,
|
|
301
|
+
timeout_seconds=ITUNES_BLOCKING_TIMEOUT_SECONDS,
|
|
302
|
+
)
|
|
303
|
+
if itunes is not None:
|
|
304
|
+
return itunes
|
|
305
|
+
|
|
306
|
+
placeholder = render_placeholder_cover(track.title, track.artist)
|
|
307
|
+
png_bytes = _image_to_png_bytes(placeholder)
|
|
308
|
+
return ResolvedArt(
|
|
309
|
+
image_bytes=png_bytes,
|
|
310
|
+
source="placeholder",
|
|
311
|
+
width=placeholder.width,
|
|
312
|
+
height=placeholder.height,
|
|
313
|
+
detail="generated gradient cover",
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def describe_resolved_art_for_diag(
|
|
318
|
+
track,
|
|
319
|
+
*,
|
|
320
|
+
download_dir: Path,
|
|
321
|
+
session: requests.Session | None = None,
|
|
322
|
+
) -> str:
|
|
323
|
+
"""Lightweight art summary for diagnostics (may perform iTunes lookup)."""
|
|
324
|
+
if track.art_bytes:
|
|
325
|
+
with Image.open(io.BytesIO(track.art_bytes)) as image:
|
|
326
|
+
width, height = image.size
|
|
327
|
+
return f"smtc_thumbnail {width}x{height} ({len(track.art_bytes)} bytes)"
|
|
328
|
+
if track.art_url:
|
|
329
|
+
return f"spotify_url {track.art_url}"
|
|
330
|
+
try:
|
|
331
|
+
resolved = resolve_track_art(
|
|
332
|
+
track,
|
|
333
|
+
download_dir=download_dir,
|
|
334
|
+
session=session,
|
|
335
|
+
)
|
|
336
|
+
except Exception as exc:
|
|
337
|
+
return f"unresolved ({exc})"
|
|
338
|
+
return f"{resolved.source} {resolved.width}x{resolved.height} ({resolved.detail})"
|