openlive 0.1.3__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.
openlive/chatview.py ADDED
@@ -0,0 +1,456 @@
1
+ """Draws the chat sidebar as an image (Pillow), so it can show colour emoji and Twitch emotes, which mpv's own
2
+ text renderer can't. The chat bridge hands each frame to mpv with overlay-add.
3
+
4
+ ChatView keeps up to 2000 messages, a scroll position and a paused state; render() returns the panel and
5
+ click() maps a click on it to an action.
6
+ """
7
+ import glob
8
+ import os
9
+ import re
10
+ import sys
11
+ from collections import deque
12
+
13
+ from PIL import Image, ImageDraw, ImageFont
14
+
15
+ RATIO = 0.27 # share of the window the sidebar takes (same as openlive_ui.lua)
16
+ KEEP = 2000
17
+
18
+
19
+ def _rgb(h):
20
+ return tuple(int(h[i:i + 2], 16) for i in (1, 3, 5)) + (255,)
21
+
22
+
23
+ BG, SURF, PANEL, BORDER = _rgb("#0f1420"), _rgb("#141b2a"), _rgb("#1a2335"), _rgb("#263044")
24
+ FG, BRIGHT, MUTED, DIM = _rgb("#d6deeb"), _rgb("#eef2fa"), _rgb("#7c879f"), _rgb("#4b5570")
25
+ ACCENT, INFO = _rgb("#f2cc8f"), _rgb("#9cc8e8")
26
+ NAME_COLORS = [_rgb(h) for h in ("#9cc8e8", "#a5d68f", "#c3a6ff", "#f4a98a", "#63d3c4", "#e8d36a", "#ff9fb2", "#7fb2ff")]
27
+
28
+
29
+ # ───────────────────────── fonts ─────────────────────────
30
+
31
+ def _first(*patterns):
32
+ for p in patterns:
33
+ hits = sorted(glob.glob(p, recursive=True))
34
+ if hits:
35
+ return hits[0]
36
+ return None
37
+
38
+
39
+ def font_files():
40
+ """(regular, bold, fallback for other scripts, colour emoji) font paths for this system; any may be None."""
41
+ if sys.platform == "darwin":
42
+ return (("/System/Library/Fonts/HelveticaNeue.ttc", 0), ("/System/Library/Fonts/HelveticaNeue.ttc", 1),
43
+ (_first("/System/Library/Fonts/Supplemental/Arial Unicode.ttf", "/Library/Fonts/Arial Unicode.ttf"), 0),
44
+ (_first("/System/Library/Fonts/Apple Color Emoji.ttc"), 0))
45
+ if sys.platform == "win32":
46
+ f = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts")
47
+ return ((os.path.join(f, "segoeui.ttf"), 0), (os.path.join(f, "segoeuib.ttf"), 0),
48
+ (_first(os.path.join(f, "seguisym.ttf"), os.path.join(f, "msyh.ttc")), 0), (os.path.join(f, "seguiemj.ttf"), 0))
49
+ roots = ["/usr/share/fonts/**/", "/usr/local/share/fonts/**/", os.path.expanduser("~/.local/share/fonts/**/")]
50
+ find = lambda *names: _first(*[r + n for r in roots for n in names])
51
+ return ((find("NotoSans-Regular.ttf", "DejaVuSans.ttf"), 0), (find("NotoSans-Bold.ttf", "DejaVuSans-Bold.ttf"), 0),
52
+ (find("NotoSansCJK-Regular.ttc", "DejaVuSans.ttf"), 0), (find("NotoColorEmoji.ttf"), 0))
53
+
54
+
55
+ class Fonts:
56
+ def __init__(self, size, files=None):
57
+ reg, bold, other, emoji = files or font_files()
58
+ self.size = size
59
+ self.reg = self._load(reg, size)
60
+ self.bold = self._load(bold, size) if bold and bold[0] else self.reg
61
+ self.other = self._load(other, size) if other and other[0] else None
62
+ self.emoji_path = emoji[0] if emoji and emoji[0] and os.path.exists(emoji[0]) else None
63
+ self._emoji_font, self._emoji_cache = None, {}
64
+
65
+ @staticmethod
66
+ def _load(spec, size):
67
+ if spec and spec[0]:
68
+ try:
69
+ return ImageFont.truetype(spec[0], size, index=spec[1])
70
+ except OSError:
71
+ pass
72
+ return ImageFont.load_default(size)
73
+
74
+ def emoji(self, cluster, height):
75
+ """A colour emoji scaled to height px, or None when the system has no emoji font."""
76
+ key = (cluster, height)
77
+ if key in self._emoji_cache:
78
+ return self._emoji_cache[key]
79
+ img = None
80
+ if self.emoji_path:
81
+ if self._emoji_font is None: # bitmap emoji fonts only come in a few sizes
82
+ for s in (64, 109, 96, 160, 48, 40, 32):
83
+ try:
84
+ self._emoji_font = ImageFont.truetype(self.emoji_path, s)
85
+ break
86
+ except OSError:
87
+ continue
88
+ if self._emoji_font:
89
+ s = self._emoji_font.size
90
+ canvas = Image.new("RGBA", (s * 2, s * 2))
91
+ try:
92
+ ImageDraw.Draw(canvas).text((0, 0), cluster, font=self._emoji_font, embedded_color=True)
93
+ except (OSError, ValueError):
94
+ canvas = None
95
+ box = canvas.getbbox() if canvas else None
96
+ if box:
97
+ g = canvas.crop(box)
98
+ img = g.resize((max(1, round(g.width * height / g.height)), height), Image.LANCZOS)
99
+ self._emoji_cache[key] = img
100
+ return img
101
+
102
+
103
+ # ───────────────────────── text → pieces ─────────────────────────
104
+
105
+ def _is_emoji(cp):
106
+ return cp >= 0x1F000 and cp <= 0x1FAFF or 0x2600 <= cp <= 0x27BF or 0x2300 <= cp <= 0x23FF or 0x2B00 <= cp <= 0x2BFF
107
+
108
+
109
+ def _skip(cp):
110
+ """Joiners, variation selectors, skin tones and tags: without text shaping they'd draw as boxes."""
111
+ return (cp in (0x200D, 0xFE0F, 0xFE0E, 0x20E3, 0x034F, 0x00AD) or 0x1F3FB <= cp <= 0x1F3FF or 0xE0000 <= cp <= 0xE0FFF
112
+ or 0x200B <= cp <= 0x200F or 0x2060 <= cp <= 0x2064) # chatters add U+E0000 to dodge the duplicate filter
113
+
114
+
115
+ def emote_ranges(tag):
116
+ """Twitch's emotes tag ("25:0-4,12-16/1902:6-10") → [(start, end, id)] sorted by position."""
117
+ out = []
118
+ for part in (tag or "").split("/"):
119
+ eid, _, spans = part.partition(":")
120
+ if not re.fullmatch(r"[A-Za-z0-9_]+", eid or ""):
121
+ continue
122
+ for sp in spans.split(","):
123
+ a, _, b = sp.partition("-")
124
+ if a.isdigit() and b.isdigit():
125
+ out.append((int(a), int(b), eid))
126
+ return sorted(out)
127
+
128
+
129
+ def pieces(text, emotes=""):
130
+ """Split a message into ("text", s), ("emoji", s) and ("emote", id) pieces."""
131
+ out, buf = [], []
132
+
133
+ def flush():
134
+ if buf:
135
+ out.append(("text", "".join(buf)))
136
+ buf.clear()
137
+
138
+ ranges = {a: (b, eid) for a, b, eid in emote_ranges(emotes)}
139
+ i, after_zwj = 0, False
140
+ while i < len(text):
141
+ if i in ranges:
142
+ b, eid = ranges[i]
143
+ flush()
144
+ out.append(("emote", eid))
145
+ i = b + 1
146
+ continue
147
+ ch = text[i]
148
+ cp = ord(ch)
149
+ if _skip(cp):
150
+ after_zwj = cp == 0x200D
151
+ elif _is_emoji(cp):
152
+ if not after_zwj: # a joined emoji (👩‍💻) shows its first part only
153
+ flush()
154
+ if 0x1F1E6 <= cp <= 0x1F1FF and i + 1 < len(text) and 0x1F1E6 <= ord(text[i + 1]) <= 0x1F1FF:
155
+ out.append(("emoji", text[i:i + 2])) # a flag
156
+ i += 1
157
+ else:
158
+ out.append(("emoji", ch))
159
+ after_zwj = False
160
+ else:
161
+ after_zwj = False
162
+ buf.append(ch)
163
+ i += 1
164
+ flush()
165
+ return out
166
+
167
+
168
+ def name_color(name, color):
169
+ if color and re.fullmatch(r"#[0-9a-fA-F]{6}", color):
170
+ r, g, b, _ = _rgb(color)
171
+ if r * 0.3 + g * 0.59 + b * 0.11 > 70: # very dark name colours are unreadable on the panel
172
+ return _rgb(color)
173
+ h = 0
174
+ for ch in name or "":
175
+ h = (h * 31 + ord(ch)) % 1000003
176
+ return NAME_COLORS[h % len(NAME_COLORS)]
177
+
178
+
179
+ # ───────────────────────── the panel ─────────────────────────
180
+
181
+ class ChatView:
182
+ def __init__(self, emote_image=None, files=None):
183
+ self.msgs = deque(maxlen=KEEP)
184
+ self.status = None # None (connecting) / "joined" / "offline"
185
+ self.text = {} # localized strings from the session
186
+ self.channel = ""
187
+ self.can_write = False
188
+ self.paused = False
189
+ self.scroll = 0 # px scrolled up from the newest message
190
+ self.new = 0 # messages that arrived while paused or scrolled up
191
+ self.emote_image = emote_image or (lambda eid: None)
192
+ self.files = files
193
+ self._fonts = {}
194
+ self._layout = {} # id(msg) → (width, height, lines)
195
+ self.hits = []
196
+ self.max_scroll = None
197
+
198
+ def tr(self, key, fallback):
199
+ return self.text.get(key) or fallback
200
+
201
+ @property
202
+ def frozen(self):
203
+ return self.paused or self.scroll > 0
204
+
205
+ def add(self, msg):
206
+ if len(self.msgs) == self.msgs.maxlen:
207
+ self._layout.pop(id(self.msgs[0]), None)
208
+ self.msgs.append(msg)
209
+ if self.frozen:
210
+ self.new += 1
211
+ if self._last_w: # keep the same messages in view
212
+ self.scroll += self._measure(msg, self._last_w)[0] + self._gap
213
+ return True
214
+
215
+ _last_w, _gap = 0, 0
216
+
217
+ def forget_layouts(self):
218
+ """An emote image arrived: sizes change."""
219
+ self._layout.clear()
220
+
221
+ def scroll_by(self, lines):
222
+ step = lines * (self._fonts_for(self._last_h).size * 1.45 if self._last_h else 20)
223
+ self.scroll = max(0, round(self.scroll + step))
224
+ if self.max_scroll is not None:
225
+ self.scroll = min(self.scroll, self.max_scroll)
226
+ if self.scroll == 0 and not self.paused:
227
+ self.new = 0
228
+
229
+ def resume(self):
230
+ self.paused, self.scroll, self.new = False, 0, 0
231
+
232
+ def toggle_pause(self):
233
+ if self.frozen:
234
+ self.resume()
235
+ else:
236
+ self.paused = True
237
+
238
+ # geometry
239
+ _last_h = 0
240
+
241
+ def _fonts_for(self, h):
242
+ fs = max(14, round(17 * h / 720))
243
+ if fs not in self._fonts:
244
+ self._fonts = {fs: Fonts(fs, self.files)}
245
+ self._layout.clear()
246
+ return self._fonts[fs]
247
+
248
+ def _atoms(self, m, f):
249
+ """Drawable units of a message: (kind, payload, font, colour, width, is_space)."""
250
+ lh = round(f.size * 1.45)
251
+ out = []
252
+
253
+ def add_text(s, font, color):
254
+ for word in re.findall(r"\S+|\s+", s):
255
+ if word.isspace():
256
+ out.append(("text", " ", font, color, font.getlength(" "), True))
257
+ continue
258
+ run, run_font = "", None
259
+ for ch in word: # characters the main font lacks go to the fallback font
260
+ use = f.other if f.other and ord(ch) > 0x24F else font
261
+ if run and use is not run_font:
262
+ out.append(("text", run, run_font, color, run_font.getlength(run), False))
263
+ run = ""
264
+ run, run_font = run + ch, use
265
+ if run:
266
+ out.append(("text", run, run_font, color, run_font.getlength(run), False))
267
+
268
+ if m.get("note"):
269
+ add_text(m["note"], f.reg, INFO)
270
+ return out
271
+ nc = name_color(m.get("n", ""), m.get("c", ""))
272
+ add_text(m.get("n", ""), f.bold, nc)
273
+ if not m.get("me"):
274
+ add_text(":", f.bold, nc)
275
+ out.append(("text", " ", f.reg, FG, f.reg.getlength(" "), True))
276
+ body = nc if m.get("me") else FG
277
+ for kind, val in pieces(m.get("t", ""), m.get("e", "")):
278
+ if kind == "text":
279
+ add_text(val, f.reg, body)
280
+ elif kind == "emoji":
281
+ img = f.emoji(val, round(f.size * 1.15))
282
+ if img:
283
+ out.append(("img", img, None, None, img.width, False))
284
+ else:
285
+ img = self.emote_image(val)
286
+ w = round(img.width * lh / img.height) if img else lh
287
+ out.append(("emote", val, None, None, w, False))
288
+ return out
289
+
290
+ def _measure(self, m, width):
291
+ """(height, lines) of a message wrapped to width; lines = [[(x, atom), …], …]."""
292
+ f = self._fonts_for(self._last_h)
293
+ cached = self._layout.get(id(m))
294
+ if cached and cached[0] == width:
295
+ return cached[1], cached[2]
296
+ lh = round(f.size * 1.45)
297
+ lines, line, x = [], [], 0
298
+ words, word = [], []
299
+ for a in self._atoms(m, f):
300
+ word.append(a)
301
+ if a[5]:
302
+ words.append(word)
303
+ word = []
304
+ if word:
305
+ words.append(word)
306
+ for word in words:
307
+ ww = sum(a[4] for a in word if not a[5])
308
+ if x + ww > width and line:
309
+ lines.append(line)
310
+ line, x = [], 0
311
+ for a in word:
312
+ if a[5] and not line:
313
+ continue # no space at the start of a line
314
+ if a[4] > width - x and not a[5] and (line or a[4] > width): # doesn't fit: cut it or wrap
315
+ if a[0] == "text" and len(a[1]) > 1 and a[4] > width:
316
+ for ch in a[1]:
317
+ cw = a[2].getlength(ch)
318
+ if x + cw > width and line:
319
+ lines.append(line)
320
+ line, x = [], 0
321
+ line.append((x, ("text", ch, a[2], a[3], cw, False)))
322
+ x += cw
323
+ continue
324
+ if line:
325
+ lines.append(line)
326
+ line, x = [], 0
327
+ line.append((x, a))
328
+ x += a[4]
329
+ if line:
330
+ lines.append(line)
331
+ h = max(1, len(lines)) * lh
332
+ self._layout[id(m)] = (width, h, lines)
333
+ return h, lines
334
+
335
+ def _draw_msg(self, img, d, lines, x0, y0, f):
336
+ lh = round(f.size * 1.45)
337
+ for i, line in enumerate(lines):
338
+ y = y0 + i * lh
339
+ for x, a in line:
340
+ kind = a[0]
341
+ if kind == "text":
342
+ d.text((x0 + x, y + lh / 2), a[1], font=a[2], fill=a[3], anchor="lm")
343
+ elif kind == "img":
344
+ im = a[1]
345
+ img.alpha_composite(im, (round(x0 + x), round(y + (lh - im.height) / 2)))
346
+ else:
347
+ em = self.emote_image(a[1])
348
+ if em:
349
+ em = em.resize((max(1, round(a[4])), lh), Image.LANCZOS) if em.size != (round(a[4]), lh) else em
350
+ img.alpha_composite(em.convert("RGBA"), (round(x0 + x), round(y)))
351
+
352
+ def render(self, w, h):
353
+ """The sidebar for a w×h window: (RGBA image, its x position)."""
354
+ pw, x0 = int(w * RATIO), w - int(w * RATIO)
355
+ self._last_h = h
356
+ f = self._fonts_for(h)
357
+ u = h / 720
358
+ pad = max(6, round(12 * u))
359
+ head = round(f.size * 2.6)
360
+ lh = round(f.size * 1.45)
361
+ self._gap = gap = round(lh * 0.25)
362
+ inner = pw - 2 * pad
363
+ self._last_w = inner
364
+ img = Image.new("RGBA", (pw, h), SURF)
365
+ d = ImageDraw.Draw(img)
366
+ line_w = max(1, round(u))
367
+ self.hits = []
368
+
369
+ # messages, newest at the bottom
370
+ top, bottom = head + pad // 2, h - pad
371
+ if not self.msgs:
372
+ status = {"offline": self.tr("chat_offline", "Can't reach the chat, retrying…"),
373
+ "joined": self.tr("chat_quiet", "Nobody has written yet.")}.get(
374
+ self.status, self.tr("chat_connecting", "Connecting to the chat…"))
375
+ d.text((pad, top + pad), status, font=f.reg, fill=DIM)
376
+ y = bottom + self.scroll
377
+ total = 0
378
+ self.max_scroll = None # known only once the oldest message is reached
379
+ for m in reversed(self.msgs):
380
+ mh, lines = self._measure(m, inner)
381
+ y -= mh
382
+ if y < bottom and y + mh > top:
383
+ self._draw_msg(img, d, lines, pad, y, f)
384
+ total += mh + gap
385
+ if y < top and total > self.scroll + (bottom - top):
386
+ break
387
+ y -= gap
388
+ else: # reached the oldest message: that's as far as scrolling goes
389
+ self.max_scroll = max(0, total - (bottom - top))
390
+ if self.scroll > self.max_scroll:
391
+ self.scroll = self.max_scroll
392
+ d.rectangle((0, 0, pw, top - 1), fill=SURF) # nothing scrolls over the header
393
+ d.rectangle((0, 0, line_w - 1, h), fill=BORDER)
394
+ d.rectangle((0, head - line_w, pw, head), fill=BORDER)
395
+
396
+ # header: title, then buttons from the right: hide, pause, write
397
+ bh = round(head * 0.62)
398
+ bx = pw - pad
399
+ by = (head - bh) // 2
400
+
401
+ def button(width, action, draw):
402
+ nonlocal bx
403
+ box = (bx - width, by, bx, by + bh)
404
+ d.rounded_rectangle(box, radius=max(3, bh // 4), fill=PANEL)
405
+ draw(box)
406
+ self.hits.append((x0 + box[0], box[1], x0 + box[2], box[3], action))
407
+ bx -= width + round(6 * u)
408
+
409
+ def x_icon(b):
410
+ cx, cy, r = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2, bh * 0.2
411
+ for s in (1, -1):
412
+ d.line((cx - r, cy - r * s, cx + r, cy + r * s), fill=MUTED, width=max(2, round(2 * u)))
413
+
414
+ def pause_icon(b):
415
+ cx, cy, r = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2, bh * 0.2
416
+ if self.frozen: # play triangle: back to the live chat
417
+ d.polygon([(cx - r * 0.8, cy - r), (cx - r * 0.8, cy + r), (cx + r, cy)], fill=ACCENT)
418
+ else:
419
+ bw = max(2, round(r * 0.55))
420
+ d.rectangle((cx - r * 0.75, cy - r, cx - r * 0.75 + bw, cy + r), fill=FG)
421
+ d.rectangle((cx + r * 0.75 - bw, cy - r, cx + r * 0.75, cy + r), fill=FG)
422
+
423
+ button(bh, "hide", x_icon)
424
+ button(bh, "pause", pause_icon)
425
+ label = self.tr("write", "Write")
426
+ lw = round(f.reg.getlength(label)) + 2 * pad
427
+ button(lw, "write", lambda b: d.text(((b[0] + b[2]) / 2, (b[1] + b[3]) / 2), label, font=f.reg,
428
+ fill=FG if self.can_write else DIM, anchor="mm"))
429
+ title_room = bx - pad
430
+ d.text((pad, head / 2), self.tr("chat", "Chat"), font=f.bold, fill=MUTED, anchor="lm")
431
+ tx = pad + f.bold.getlength(self.tr("chat", "Chat")) + f.size * 0.6
432
+ name = self.channel
433
+ while name and tx + f.bold.getlength(name) > title_room:
434
+ name = name[:-2] + "…" if len(name) > 2 else ""
435
+ d.text((tx, head / 2), name, font=f.bold, fill=FG, anchor="lm")
436
+
437
+ # "N new messages" / "back to the live chat" pill
438
+ if self.frozen:
439
+ label = self.tr("new_msgs", "{n} new messages").replace("{n}", str(self.new)) if self.new \
440
+ else self.tr("paused", "Chat paused")
441
+ pw_ = round(f.bold.getlength(label) + f.size * 2.8)
442
+ ph = round(f.size * 2)
443
+ px, py = (pw - pw_) // 2, h - pad - ph
444
+ d.rounded_rectangle((px, py, px + pw_, py + ph), radius=ph // 2, fill=ACCENT)
445
+ d.text((px + f.size * 0.9, py + ph / 2), label, font=f.bold, fill=BG, anchor="lm")
446
+ ax, ay, r = px + pw_ - f.size * 0.9, py + ph / 2, f.size * 0.3
447
+ d.polygon([(ax - r, ay - r * 0.5), (ax + r, ay - r * 0.5), (ax, ay + r * 0.6)], fill=BG)
448
+ self.hits.append((x0 + px, py, x0 + px + pw_, py + ph, "resume"))
449
+ return img, x0
450
+
451
+ def click(self, x, y):
452
+ """What a click at window position (x, y) does: an action name or None."""
453
+ for x1, y1, x2, y2, action in self.hits:
454
+ if x1 <= x <= x2 and y1 <= y <= y2:
455
+ return action
456
+ return None
openlive/cli.py ADDED
@@ -0,0 +1,43 @@
1
+ """Command line entry point."""
2
+ import argparse
3
+ import shutil
4
+ import sys
5
+ import tempfile
6
+
7
+ from . import __version__, config, i18n
8
+ from .i18n import t
9
+
10
+
11
+ def main(argv=None):
12
+ pre = argparse.ArgumentParser(add_help=False)
13
+ pre.add_argument("--lang", choices=i18n.SUPPORTED)
14
+ known, _ = pre.parse_known_args(argv)
15
+ if known.lang:
16
+ i18n.set_lang(known.lang)
17
+
18
+ ap = argparse.ArgumentParser(prog="openlive", description=t("Who you watch is live on Twitch, Kick and YouTube, in the terminal."))
19
+ ap.add_argument("--text", action="store_true", help=t("print who is live and exit, no TUI"))
20
+ ap.add_argument("--demo", action="store_true", help=t("explore with made-up channels (reads nothing, writes nothing)"))
21
+ ap.add_argument("--lang", choices=i18n.SUPPORTED, help=t("interface language"))
22
+ ap.add_argument("-V", "--version", action="version", version=f"openlive {__version__}")
23
+ args = ap.parse_args(argv)
24
+
25
+ if args.demo:
26
+ config.set_data_dir(tempfile.mkdtemp(prefix="openlive-demo-"))
27
+ config.OFFLINE = True
28
+ if args.text or not sys.stdout.isatty():
29
+ try: # titles carry emoji; a Windows console or pipe may use a code page without them
30
+ sys.stdout.reconfigure(errors="replace")
31
+ except (AttributeError, ValueError):
32
+ pass
33
+ from .text import run
34
+ return run(args.demo, out=lambda s: print(s))
35
+ from .tui import make_app
36
+ make_app(args.demo).run()
37
+ if args.demo:
38
+ shutil.rmtree(config.DATA, ignore_errors=True)
39
+ return 0
40
+
41
+
42
+ if __name__ == "__main__":
43
+ sys.exit(main())
openlive/common.py ADDED
@@ -0,0 +1,64 @@
1
+ """Palette, constants and formatting helpers."""
2
+ import zlib
3
+ from datetime import UTC, datetime
4
+
5
+ from . import i18n
6
+
7
+ BG, SURF, PANEL, BORDER = "#0f1420", "#141b2a", "#1a2335", "#263044"
8
+ FG, BRIGHT, MUTED, DIM = "#d6deeb", "#eef2fa", "#7c879f", "#4b5570"
9
+ ACCENT, OK_C, WARN_C, ERR_C, INFO_C = "#f2cc8f", "#a5d68f", "#f2cc8f", "#f28b82", "#9cc8e8"
10
+ LIVE_C = "#f28b82" # the red "live" dot
11
+ TWITCH_C = "#b39ddb" # soft Twitch purple for the brand bits
12
+
13
+ # one fixed colour per game/category, picked by name so it is the same everywhere and on every run
14
+ GAME_COLORS = ("#9cc8e8", "#a5d68f", "#c3a6ff", "#f4a98a", "#63d3c4", "#e8d36a", "#ff9fb2", "#7fb2ff",
15
+ "#b8c4d6", "#d9a6ff", "#8fd6c1", "#f2b880")
16
+
17
+
18
+ def game_color(name):
19
+ if not name:
20
+ return MUTED
21
+ return GAME_COLORS[zlib.crc32(name.lower().encode()) % len(GAME_COLORS)]
22
+
23
+
24
+ def human(n):
25
+ n = int(n or 0)
26
+ if n >= 1_000_000_000: return f"{n / 1e9:.2f}B"
27
+ if n >= 1_000_000: return f"{n / 1e6:.2f}M"
28
+ if n >= 10_000: return f"{n / 1e3:.0f}k"
29
+ if n >= 1_000: return f"{n / 1e3:.1f}k"
30
+ return str(n)
31
+
32
+
33
+ def human_full(n):
34
+ s = f"{int(n or 0):,}"
35
+ return s.replace(",", ".") if i18n.LANG == "es" else s
36
+
37
+
38
+ def parse_time(s):
39
+ try:
40
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
41
+ except (AttributeError, ValueError):
42
+ return None
43
+
44
+
45
+ def uptime(started_at, now=None):
46
+ """'3h 05m' since the stream started."""
47
+ st = parse_time(started_at)
48
+ if not st:
49
+ return ""
50
+ secs = max(0, int(((now or datetime.now(UTC)) - st).total_seconds()))
51
+ h, m = divmod(secs // 60, 60)
52
+ if h >= 24:
53
+ return f"{h // 24}d {h % 24}h"
54
+ return f"{h}h {m:02d}m" if h else f"{m}m"
55
+
56
+
57
+ def uptime_secs(started_at, now=None):
58
+ st = parse_time(started_at)
59
+ return int(((now or datetime.now(UTC)) - st).total_seconds()) if st else 0
60
+
61
+
62
+ def clip(s, n):
63
+ s = " ".join((s or "").split())
64
+ return s if len(s) <= n else s[: max(0, n - 1)] + "…"