Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.
Add the animated Space clock face
click6067-ship-itca59bef9cd7c
diff --git a/README.ko.md b/README.ko.mdindex 79a2bf1..6a36e9c 100644--- a/README.ko.md+++ b/README.ko.md@@ -29,9 +29,10 @@ cp config.example.json .runtime/config.json### 화면 스타일-웹의 **Clock display**에서 시계 화면 5종을 미리 보고 고릅니다.+웹의 **Clock display**에서 시계 화면 6종을 미리 보고 고릅니다.**Digital / Neon / Pixel Retro / Sci-Fi HUD**는 같은 이름의 웹 테마와 같은 글꼴·장식·게이지를-쓰고, 원래의 **Pixel**도 남아 있습니다. **Apply to clock**을 누르면 선택을 저장하고 같은 계정+쓰고, 원래의 **Pixel**도 남아 있습니다. **Space**는 세 봇이 유리 헬멧을 쓰고 밤하늘을+떠다니는 움직이는 화면(GIF)이며, 사용률이 바뀌거나 30분이 지나면 새로 보냅니다. **Apply to clock**을 누르면 선택을 저장하고 같은 계정캐시로 기기에 전송합니다. 미리보기만 선택하면 시계에는 적용되지 않습니다.| Theme | 240×240 화면 표현 |@@ -43,12 +44,12 @@ cp config.example.json .runtime/config.json기존 Pixel(5×7 비트맵 글꼴과 픽셀 마스코트)도 같은 목록에서 고를 수 있습니다.각 스타일은 Claude·Codex·Grok 한 계정과 10% 단위 10칸 게이지를 표시합니다.-설정의 `display_style`은 `digital`, `neon`, `retro`, `hud`, `pixel`을 지원하며 재시작 후에도 유지됩니다. 미설정 기본값은 `pixel`입니다.+설정의 `display_style`은 `digital`, `neon`, `retro`, `hud`, `pixel`, `space`를 지원하며 재시작 후에도 유지됩니다. 미설정 기본값은 `pixel`입니다.숫자는 테마 내 공통 중성색입니다.로고 색은 공급자별로 유지하며 게이지는 0–49% / 50–79% / 80–89% / 90–100% 구간마다 같은 색 계열의 두 색 그라데이션으로 표시합니다.색만으로 상태를 전달하지 않으며 실제 숫자, 칸 수, 미인증/오래된 값 표기를 함께 제공합니다.-+새 화면은 참고 이미지를 바탕으로 코드로 그렸습니다. 원본 이미지의 가상 통계나 정적인 숫자는 포함하지 않습니다.이미지를 자동으로 테마로 바꾸는 기능이나 테마 편집기는 현재 구현돼 있지 않습니다.diff --git a/README.md b/README.mdindex d14eda4..85767a9 100644--- a/README.md+++ b/README.md@@ -11,6 +11,8 @@ Claude · Codex · Grok — multiple accounts — no firmware flashing</p><p align="center"><img src="docs/images/real-clock.jpg" alt="TokenTV on a real $5 clock: Digital, Pixel Retro and Sci-Fi HUD faces"></p>+<p align="center"><img src="docs/images/space.gif" width="480" alt="Space face: the Claude, Codex and Grok bots drift in glass helmets, each with its usage"></p>+<p align="center"><a href="https://token-tv.vercel.app"><img src="docs/images/web-demo.png" alt="Web dashboard in four themes. Click to open the live demo"></a></p><p align="center"><img src="docs/images/how-it-works.png" alt="Your CLI logins → TokenTV on your computer → a picture over Wi-Fi → the $5 clock"></p>@@ -25,13 +27,14 @@ mkdir -p .runtime && cp config.example.json .runtime/config.json # add accounts```<details>-<summary><b>All five clock faces</b></summary>+<summary><b>All six clock faces</b></summary><br>-+-Pick one under **Clock display** in the dashboard, then press **Apply to clock**.+Pick one under **Clock display** in the dashboard, then press **Apply to clock**. Space is an animated+GIF that the stock photo album plays; it is re-sent only when a number changes or every 30 minutes.</details><details>diff --git a/docs/images/clock-faces.png b/docs/images/clock-faces.pngindex b89dcaf..f9c6545 100644Binary files a/docs/images/clock-faces.png and b/docs/images/clock-faces.png differdiff --git a/docs/images/space.gif b/docs/images/space.gifnew file mode 100644index 0000000..8b2ca0aBinary files /dev/null and b/docs/images/space.gif differdiff --git a/scripts/build_demo.py b/scripts/build_demo.pyindex ec3ab43..d65d2a8 100644--- a/scripts/build_demo.py+++ b/scripts/build_demo.py@@ -67,13 +67,17 @@ def build(out, site):for notice in WEB.glob('*-LICENSE.txt'):shutil.copy2(notice, assets / notice.name)(out / 'demo-snapshot.json').write_text(json.dumps(snapshot(), separators=(',', ':')))- display = {'style': 'digital', 'applied_style': 'digital', 'status': 'preview_only', 'styles': list(STYLES)}- (out / 'demo-display.json').write_text(json.dumps(display))frames = out / 'frames'frames.mkdir()rendered = snapshot(time.time())+ paths = {}for style in STYLES:- (frames / f'{style}.jpg').write_bytes(render_page(rendered, style=style))+ image = render_page(rendered, style=style)+ name = f"{style}.{'gif' if image[:4] == b'GIF8' else 'jpg'}" # Space is animated+ (frames / name).write_bytes(image)+ paths[style] = f'/frames/{name}'+ display = {'style': 'digital', 'applied_style': 'digital', 'status': 'preview_only', 'styles': list(STYLES), 'frames': paths}+ (out / 'demo-display.json').write_text(json.dumps(display))shutil.copy2(ROOT / 'docs' / 'images' / 'social-preview.png', out / 'og.png')return sorted(str(p.relative_to(out)) for p in out.rglob('*') if p.is_file() and '.vercel' not in p.parts)diff --git a/tests/test_device.py b/tests/test_device.pyindex ddde039..988cb20 100644--- a/tests/test_device.py+++ b/tests/test_device.py@@ -52,13 +52,23 @@ class DisplayTests(unittest.TestCase):display.upload("tokentv.jpg", b"EXACT-JPEG")display.activate(original)self.assertEqual([p["name"] for p in photos["files"] if p["enabled"]], ["tokentv.jpg"])+ # Switching to the animated face shows only the GIF; switching back restores the JPEG.+ photos["files"].append({"name": "tokentv.gif", "enabled": False})+ display.upload("tokentv.gif", b"GIF89a-EXACT")+ display.activate(original, "tokentv.gif")+ self.assertEqual([p["name"] for p in photos["files"] if p["enabled"]], ["tokentv.gif"])+ display.activate(original, "tokentv.jpg")+ self.assertEqual([p["name"] for p in photos["files"] if p["enabled"]], ["tokentv.jpg"])+ with self.assertRaises(ValueError):+ display.upload("other.gif", b"GIF89a")display.restore(original)self.assertEqual([p["name"] for p in photos["files"] if p["enabled"]], ["original.jpg", "space man.gif"])uploads = [c for c in calls if c[0] == "POST"]- self.assertEqual(len(uploads), 1)+ self.assertEqual(len(uploads), 2)self.assertEqual(uploads[0][1], "/photo/upload")self.assertIn(b'name="file"; filename="tokentv.jpg"', uploads[0][2])self.assertIn(b"\r\n\r\nEXACT-JPEG\r\n", uploads[0][2])+ self.assertIn(b'filename="tokentv.gif"\r\nContent-Type: image/gif', uploads[1][2])paths = [c[1] for c in calls]self.assertIn("/theme/toggle?id=2&state=1", paths)self.assertIn("/theme/toggle?id=0&state=0", paths)diff --git a/tests/test_display_styles.py b/tests/test_display_styles.pyindex 2ad65ce..21ce7a2 100644--- a/tests/test_display_styles.py+++ b/tests/test_display_styles.py@@ -78,8 +78,14 @@ class DisplayStyleTests(unittest.TestCase):for frame in frames:image = Image.open(io.BytesIO(frame))self.assertEqual(image.size, (240, 240))- self.assertEqual(image.format, 'JPEG')- self.assertLess(len(frame), 60000)+ if frame[:4] == b'GIF8': # the animated Space face+ self.assertEqual(image.format, 'GIF')+ self.assertGreater(image.n_frames, 1)+ self.assertLess(len(frame), 400000)+ else:+ self.assertEqual(image.format, 'JPEG')+ self.assertLess(len(frame), 60000)+ self.assertEqual(sum(f[:4] == b'GIF8' for f in frames[:len(STYLES)]), 1)with self.assertRaises(ValueError):render_page(sample, style='unknown')diff --git a/token_tv/device.py b/token_tv/device.pyindex 28417b1..c75b461 100644--- a/token_tv/device.py+++ b/token_tv/device.py@@ -5,7 +5,9 @@ from urllib.parse import quote, urlencode, urlparsefrom urllib.request import Request, urlopen-FILES = ("tokentv.jpg",)+FILES = ("tokentv.jpg", "tokentv.gif")+# The album page accepts GIFs up to 240×240; keep both well under the free space.+LIMITS = {"tokentv.jpg": (60000, "image/jpeg"), "tokentv.gif": (400000, "image/gif")}LEGACY_FILES = ("tokentv-c.jpg", "tokentv-m.jpg")@@ -32,28 +34,28 @@ class PhotoDisplay:"files": [{"name": f["name"], "enabled": f["enabled"]} for f in photos["files"]],"photo_interval": photos["interval"]}- def upload(self, name, jpeg):- if name not in FILES or len(jpeg) > 60000:+ def upload(self, name, image):+ limit, mime = LIMITS.get(name, (0, ""))+ if not image or len(image) > limit:raise ValueError("Unexpected display image")boundary = "TokenTV" + uuid.uuid4().hexbody = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\n'- 'Content-Type: image/jpeg\r\n\r\n').encode() + jpeg + f"\r\n--{boundary}--\r\n".encode()+ f'Content-Type: {mime}\r\n\r\n').encode() + image + f"\r\n--{boundary}--\r\n".encode()status, _ = self.request("/photo/upload", body,{"Content-Type": "multipart/form-data; boundary=" + boundary})- return {"file": name, "status": status, "bytes": len(jpeg)}+ return {"file": name, "status": status, "bytes": len(image)}def toggle(self, category, key, value, enabled):self.request("/" + category + "/toggle?" + urlencode({key: value, "state": int(enabled)}, quote_via=quote))- def activate(self, original):- # Select our files first, then select the photo theme; retain old files.+ def activate(self, original, name=FILES[0]):+ # Show only our current file, then select the photo theme; retain old files.current = self.capture()enabled = {f['name']: f['enabled'] for f in current['files']}- for name in FILES:- if not enabled.get(name):- self.toggle("photo", "name", name, True)+ if not enabled.get(name):+ self.toggle("photo", "name", name, True)for f in current['files']:- if f["name"] not in FILES and f['enabled']:+ if f["name"] != name and f['enabled']:self.toggle("photo", "name", f["name"], False)if current['photo_interval'] != 10:self.request("/photo/interval?val=10")diff --git a/token_tv/display.py b/token_tv/display.pyindex 4ad7d88..6c27473 100644--- a/token_tv/display.py+++ b/token_tv/display.py@@ -23,7 +23,7 @@ PROVIDER_INK = {'claude': '#d68e68', 'codex': '#a799e5', 'grok': '#cbd1d7'}ICON_PAPER = PROVIDER_INK['grok']FONT_MAIN = '/usr/share/fonts/truetype/dejavu/DejaVuSans'FONT_NUMBERS = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono'-STYLES = ('pixel', 'digital', 'neon', 'retro', 'hud')+STYLES = ('pixel', 'digital', 'neon', 'retro', 'hud', 'space')# Gauge-only levels; labels/percentages always use TEXT, logos retain provider ink.GAUGE_LEVELS = ((50, '#76a99a'), (80, '#93c9b9'), (90, '#d1b275'), (101, '#d8877e'))STATUS = {'loading': 'WAIT', 'auth_required': 'LOGIN', 'identity_mismatch': 'CHECK',@@ -226,6 +226,9 @@ def render_page(snapshot, page=0, style='pixel'):raise IndexError('Unknown frame')if style not in STYLES:raise ValueError('Unknown display style')+ if style == 'space': # animated: returns GIF bytes+ from token_tv.space import render_space+ return render_space(snapshot)from token_tv.themes import RENDERERSrenderer = {'pixel': render_pixel, **RENDERERS}[style]image = renderer(snapshot)diff --git a/token_tv/live.py b/token_tv/live.pyindex 5909940..8d86ba8 100644--- a/token_tv/live.py+++ b/token_tv/live.py@@ -85,7 +85,7 @@ def handler(store, preferences=None):self.send_error(400, 'Unknown display style')returnbody = render_page(snapshot, int(path[7]), style)- content_type = "image/jpeg"+ content_type = "image/gif" if body[:4] == b"GIF8" else "image/jpeg"elif path == '/display':body = json.dumps(display).encode()elif path == "/health":@@ -160,10 +160,11 @@ def main():interval = max(60, int(config.get("poll_seconds", 300)))stopping = threading.Event()original = None- activated = False+ active_file = None+ last_upload = Nonedef cycle(refresh=True):- nonlocal original, activated+ nonlocal original, active_file, last_uploadif refresh:store.refresh()snapshot = store.snapshot()@@ -177,14 +178,17 @@ def main():if not backup_path.is_file():write_json(backup_path, original)phase = "upload"- for page, name in enumerate(FILES):- jpeg = render_page(snapshot, page, style)- (state_dir / name).write_bytes(jpeg)- receipts.append(dict(device.upload(name, jpeg), sha256=hashlib.sha256(jpeg).hexdigest()))- if not activated:+ image = render_page(snapshot, 0, style)+ name = FILES[1] if image[:4] == b"GIF8" else FILES[0]+ digest = hashlib.sha256(image).hexdigest()+ if (name, digest) != last_upload: # identical frames are not rewritten to flash+ (state_dir / name).write_bytes(image)+ receipts.append(dict(device.upload(name, image), sha256=digest))+ last_upload = (name, digest)+ if active_file != name:phase = "activate"- device.activate(original)- activated = True+ device.activate(original, name)+ active_file = namewrite_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})preferences.delivered(style, True)except (OSError, ValueError, KeyError) as error:diff --git a/token_tv/space.py b/token_tv/space.pynew file mode 100644index 0000000..30d36ea--- /dev/null+++ b/token_tv/space.py@@ -0,0 +1,237 @@+"""Space: the three mascots drift in glass helmets across a dotted night sky.++The face is an animated 240×240 GIF for the clock's photo album (stock firmware plays+GIFs up to 240×240). The drifting is decorative; each bot carries its provider's used %+and a ten-cell gauge. A few events (dash, hop, spin, sparkles, shooting star, huddle) start+at seeded random times. The seed follows the shown values and a 30-minute bucket, so equal+readings give identical bytes (no re-upload) while the choreography still changes over time.+"""+import functools+import hashlib+import io+import math+import random+import time++from PIL import Image, ImageDraw++from token_tv.display import ASSETS, overview_rows, pixel_text, primary_window++SIZE = 240+FPS = 10+FRAMES = 10 * FPS # one 10-second loop, matching the album's photo interval+BG = (8, 12, 30)+GLASS = (22, 30, 64)+RIM = (150, 182, 232)+SHINE = (236, 244, 255)+TAG = (255, 243, 214)+DIM = (128, 140, 178)+EMPTY = (38, 48, 90)+SPARK = (255, 216, 107)+MOON = (233, 226, 200)+GROK_GLASS = (64, 78, 140)+STARS = ((92, 104, 150), (170, 182, 220), (255, 255, 255))+# Used-quota bands (below 50, 50–79, 80–89, 90–100): start and tip of each cell ramp.+BANDS = (((42, 168, 74), (94, 224, 106)), ((143, 201, 58), (211, 232, 74)),+ ((255, 122, 31), (255, 171, 61)), ((214, 43, 60), (255, 90, 95)))+RADIUS = 20+BOX = (50, 78) # bubble plus tag footprint used for spacing+EVENTS = ('dash', 'hop', 'spin', 'sparkle', 'shooting_star', 'huddle')++[email protected]_cache(maxsize=None)+def sprite(provider):+ """Project mascot with hard alpha and at most eight colours, for a compact GIF."""+ image = Image.open(ASSETS / f'{provider}-pixel.png').convert('RGBA')+ image = image.crop(image.getbbox())+ alpha = image.getchannel('A').point(lambda a: 255 if a >= 128 else 0)+ flat = Image.new('RGB', image.size)+ flat.paste(image.convert('RGB'), mask=alpha)+ flat = flat.quantize(colors=8, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE).convert('RGB')+ out = Image.new('RGBA', image.size, (0, 0, 0, 0))+ out.paste(flat, mask=alpha)+ return out++[email protected]_cache(maxsize=1)+def backdrop():+ """Static sky: dotted stars and a dotted crescent moon; returns (image, twinkling stars)."""+ rnd = random.Random(7)+ image = Image.new('RGB', (SIZE, SIZE), BG)+ draw = ImageDraw.Draw(image)+ for _ in range(46):+ x, y = rnd.randrange(SIZE), rnd.randrange(SIZE)+ draw.point((x, y), fill=rnd.choice(STARS[:2]))+ for x, y in ((34, 22), (206, 128), (58, 168), (150, 206)):+ draw.point([(x, y), (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)], fill=STARS[1])+ cx, cy, r = 196, 34, 15+ for y in range(cy - r, cy + r + 1):+ for x in range(cx - r, cx + r + 1):+ inside = (x - cx) ** 2 + (y - cy) ** 2 <= r * r+ cut = (x - cx - 7) ** 2 + (y - cy + 3) ** 2 <= (r - 2) ** 2+ if inside and not cut and (x + y) % 2 == 0:+ draw.point((x, y), fill=MOON)+ twinkles = [(rnd.randrange(SIZE), rnd.randrange(SIZE), rnd.choice((10, 20, 25, 50)), rnd.randrange(50))+ for _ in range(6)]+ return image, twinkles+++def readings(snapshot):+ rows = []+ for row in overview_rows(snapshot):+ value = primary_window(row)+ used = max(0, min(100, value['used_percent'])) if value else None+ rows.append((row['provider'], used, bool(value) and row['status'] != 'ok'))+ return rows+++def seed_for(rows, now=None):+ bucket = int((time.time() if now is None else now) // 1800)+ key = repr([(p, None if u is None else round(u), old) for p, u, old in rows]) + f'|{bucket}'+ return int(hashlib.sha256(key.encode()).hexdigest()[:12], 16)+++def ease(p):+ return p * p * (3 - 2 * p)+++def schedule(rnd):+ """Two or three events at irregular, non-overlapping times inside the loop."""+ events, start = [], rnd.uniform(0.6, 2.5)+ for kind in rnd.sample(EVENTS, rnd.choice((2, 3))):+ duration = {'dash': 1.6, 'hop': 0.9, 'spin': 0.9, 'sparkle': 1.3, 'shooting_star': 1.0, 'huddle': 2.2}[kind]+ if start + duration > 9.6:+ break+ events.append({'kind': kind, 'start': start, 'end': start + duration, 'bot': rnd.randrange(3),+ 'y': rnd.uniform(20, 120), 'angles': [rnd.uniform(0, 2 * math.pi) for _ in range(6)]})+ start += duration + rnd.uniform(0.9, 3.2)+ return events+++def positions(t, paths, events):+ """Bubble centres at loop time t (seconds): periodic drift, events, soft separation."""+ points = []+ for i, (ax, ay, fx, fy, px, py, cx, cy) in enumerate(paths):+ x = cx + ax * math.sin(2 * math.pi * fx * t / 10 + px)+ y = cy + ay * math.sin(2 * math.pi * fy * t / 10 + py) + 2 * math.sin(2 * math.pi * 3 * t / 10 + i)+ points.append([x, y])+ for event in events:+ if not event['start'] <= t < event['end']:+ continue+ p = (t - event['start']) / (event['end'] - event['start'])+ if event['kind'] == 'huddle':+ pull = math.sin(math.pi * ease(p)) * 0.8+ for point in points:+ point[0] += (120 - point[0]) * pull+ point[1] += (106 - point[1]) * pull+ elif event['kind'] == 'hop':+ points[event['bot']][1] -= 15 * abs(math.sin(2 * math.pi * p))+ for _ in range(10): # a bubble and its tag form one box; resolve box overlaps+ for a in range(3):+ for b in range(a + 1, 3):+ dx, dy = points[b][0] - points[a][0], points[b][1] - points[a][1]+ ox, oy = BOX[0] - abs(dx), BOX[1] - abs(dy)+ if ox > 0 and oy > 0:+ axis, overlap, d = (0, ox, dx) if ox < oy else (1, oy, dy)+ shift = overlap / 2 * (1 if d >= 0 else -1)+ points[a][axis] -= shift+ points[b][axis] += shift+ for point in points:+ point[0] = min(max(point[0], 26), 214)+ point[1] = min(max(point[1], 24), 182)+ for event in events: # the dash wraps around the screen and lands back on its path+ if event['kind'] == 'dash' and event['start'] <= t < event['end']:+ p = (t - event['start']) / (event['end'] - event['start'])+ point = points[event['bot']]+ point[0] = (point[0] + 300 * ease(p) + 30) % 300 - 30+ return points+++def bubble(frame, draw, provider, x, y, mirrored):+ # The black Grok bot needs lighter glass to stay visible on the night sky.+ draw.ellipse((x - RADIUS, y - RADIUS, x + RADIUS, y + RADIUS), fill=GROK_GLASS if provider == 'grok' else GLASS, outline=RIM)+ art = sprite(provider)+ if mirrored:+ art = art.transpose(Image.Transpose.FLIP_LEFT_RIGHT)+ frame.paste(art, (x - art.width // 2, y - art.height // 2), art)+ draw.arc((x - RADIUS + 4, y - RADIUS + 4, x + RADIUS - 4, y + RADIUS - 4), 200, 250, fill=SHINE)+++def tag(draw, x, y, used, old):+ text = '--' if used is None else f'{round(used)}%'+ width = (len(text) * 6 - 1) * 2+ pixel_text(draw, (x - width // 2, y + RADIUS + 5), text, scale=2, color=DIM if old else TAG)+ left, top = x - 19, y + RADIUS + 23+ band = BANDS[0 if (used or 0) < 50 else 1 if used < 80 else 2 if used < 90 else 3]+ lit = 0 if used is None else max(1, math.ceil(used / 10)) if used > 0 else 0+ for cell in range(10):+ start, tip = band+ k = cell / 9+ color = tuple(round(start[i] + (tip[i] - start[i]) * k) for i in range(3)) if cell < lit else EMPTY+ draw.rectangle((left + cell * 4, top, left + cell * 4 + 2, top + 2), fill=color)+ if old:+ pixel_text(draw, (x - 8, top + 5), 'OLD', color=DIM)+++def render_frames(snapshot, now=None):+ rows = readings(snapshot)+ rnd = random.Random(seed_for(rows, now))+ paths = [(rnd.uniform(60, 82), rnd.uniform(24, 40), rnd.choice((1, 2)), 1,+ rnd.uniform(0, 6.3), rnd.uniform(0, 6.3), 120, cy) for cy in (54, 110, 160)]+ events = schedule(rnd)+ sky, twinkles = backdrop()+ frames = []+ for f in range(FRAMES):+ t = f / FPS+ frame = sky.copy()+ draw = ImageDraw.Draw(frame)+ for x, y, period, offset in twinkles:+ lit = ((f + offset) // (period // 2)) % 2 == 0+ draw.point((x, y), fill=STARS[2] if lit else STARS[0])+ for event in events:+ if event['kind'] == 'shooting_star' and event['start'] <= t < event['end']:+ p = (t - event['start']) / (event['end'] - event['start'])+ hx, hy = -20 + 290 * p, event['y'] + 70 * p+ for k, color in enumerate((STARS[2], STARS[1], STARS[0])):+ draw.line((hx - 7 * k, hy - 1.7 * k, hx - 7 * (k + 1), hy - 1.7 * (k + 1)), fill=color)+ points = positions(t, paths, events)+ order = sorted(range(3), key=lambda i: points[i][1])+ for i in order:+ provider, used, old = rows[i]+ x, y = round(points[i][0]), round(points[i][1])+ mirrored = any(e['kind'] == 'spin' and e['bot'] == i and e['start'] <= t < e['end']+ and int((t - e['start']) / (e['end'] - e['start']) * 6) % 2 == 1 for e in events)+ bubble(frame, draw, provider, x, y, mirrored)+ tag(draw, x, y, used, old)+ for event in events:+ if event['kind'] == 'sparkle' and event['bot'] == i and event['start'] <= t < event['end']:+ p = (t - event['start']) / (event['end'] - event['start'])+ for k, angle in enumerate(event['angles']):+ phase = p * 3 - k * 0.3+ if 0 < phase < 1:+ size = 2 if 0.3 < phase < 0.7 else 1+ sx = round(x + math.cos(angle) * (RADIUS + 6 + 6 * phase))+ sy = round(y + math.sin(angle) * (RADIUS + 6 + 6 * phase))+ draw.line((sx - size, sy, sx + size, sy), fill=SPARK)+ draw.line((sx, sy - size, sx, sy + size), fill=SPARK)+ frames.append(frame)+ return frames+++def render_space(snapshot, now=None, scale=1):+ frames = render_frames(snapshot, now)+ if scale != 1: # crisp enlargements for README and posts+ frames = [f.resize((SIZE * scale, SIZE * scale), Image.Resampling.NEAREST) for f in frames]+ colours = set()+ for frame in frames:+ colours.update(c for _, c in frame.getcolors(maxcolors=frame.width * frame.height))+ palette = sorted(colours)+ if len(palette) > 256:+ raise ValueError('Space face needs at most 256 colours')+ reference = Image.new('P', (1, 1))+ reference.putpalette([v for c in palette for v in c] + [0] * (768 - 3 * len(palette)))+ indexed = [f.quantize(palette=reference, dither=Image.Dither.NONE) for f in frames]+ buffer = io.BytesIO()+ indexed[0].save(buffer, format='GIF', save_all=True, append_images=indexed[1:],+ duration=1000 // FPS, loop=0, disposal=1, optimize=False)+ return buffer.getvalue()diff --git a/token_tv/web/app.js b/token_tv/web/app.jsindex ed2ea3a..16f7669 100644--- a/token_tv/web/app.js+++ b/token_tv/web/app.js@@ -238,7 +238,7 @@ function paintClock(forceImage = false) {$('#clock-style').disabled = applying || !displayInfo; $('#apply').disabled = DEMO || applying || !displayInfo || (style === displayInfo.style && displayInfo.status !== 'error' && !clockError);$('#apply').textContent = applying ? 'Sending image…' : 'Apply to clock'; $('#apply').dataset.state = applying ? 'loading' : clockError || displayInfo?.status === 'error' ? 'error' : displayInfo?.status === 'ok' ? 'success' : 'default';$('#display-state').textContent = DEMO ? 'Demo · install TokenTV to drive a real clock' : clockError ? 'Could not apply. Please retry.' : !displayInfo ? 'Clock status unavailable' : style !== displayInfo.style ? 'Preview only · Apply to send' : displayInfo.status === 'queued' ? 'Sending image…' : displayInfo.status === 'error' ? 'Clock upload failed. Please retry.' : displayInfo.status === 'preview_only' ? 'Preview only · No clock connected' : 'Image sent · ' + styleName(displayInfo.applied_style);- if (style && !$('#clock-panel').hidden && (forceImage || style !== lastImageStyle || Date.now() - lastImageAt > 30000)) {lastImageStyle = style; lastImageAt = Date.now(); $('#frame').src = DEMO ? `/frames/${encodeURIComponent(style)}.jpg` : '/frame/0.jpg?style=' + encodeURIComponent(style) + '&t=' + lastImageAt; $('#frame').alt = styleName(style) + ' live clock preview'}+ if (style && !$('#clock-panel').hidden && (forceImage || style !== lastImageStyle || Date.now() - lastImageAt > 30000)) {lastImageStyle = style; lastImageAt = Date.now(); $('#frame').src = DEMO ? displayInfo.frames?.[style] || `/frames/${encodeURIComponent(style)}.jpg` : '/frame/0.jpg?style=' + encodeURIComponent(style) + '&t=' + lastImageAt; $('#frame').alt = styleName(style) + ' live clock preview'}}const styleName = s => s === 'retro' ? 'Pixel Retro' : s === 'hud' ? 'Sci-Fi HUD' : s ? s[0].toUpperCase() + s.slice(1) : 'Unknown';let displayPolling = false;