mirror of
https://github.com/RustyRaptor/doge_cogs.git
synced 2026-12-03 15:55:21 -07:00
doge_alignment: guess times in Mountain Time instead of UTC
Activity hours, late nights, weekends and transcript headers use ALIGNMENT_TIMEZONE (default America/Denver, so MST/MDT) until per-person zones come from the timezone cog. tzdata is a requirement for hosts without a system zone database. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GUebqhE8dK19vyn4Ct5g1L
This commit is contained in:
1 parent
d15e76ebd7
commit
db621d671a
10 files changed
+130
-19
No files matched your search
@@ -51,7 +51,7 @@ How a guess works (`core/sampling.py`, `gather.py`, `core/conversations.py`, `co
|
||||
replies stay with what they answer. Others are anonymised as A, B, …, and anyone who blocked guesses is shown
|
||||
as hidden. Bots are left out.
|
||||
3. An activity profile: posting rate between the sampled pages over the years and how steady it is, busiest
|
||||
UTC hours, late-night and weekend shares, burstiness, typical run length, message length, and style (links,
|
||||
hours, late-night and weekend shares, burstiness, typical run length, message length, and style (links,
|
||||
caps, emoji, questions, replies…).
|
||||
4. The profile picture: its main colours (ImageMagick) and a short description from the model's vision.
|
||||
5. Conversations are packed into the budget round-robin across pages (so the whole history is covered) and
|
||||
@@ -60,6 +60,10 @@ How a guess works (`core/sampling.py`, `gather.py`, `core/conversations.py`, `co
|
||||
|
||||
The system prompt asks for a fair, candid judgement: patterns over single jokes, no default cell, activity and
|
||||
avatar as hints only, nothing about protected traits, and a reason that's a friendly roast in good taste.
|
||||
Times (busiest hours, late night, weekends, transcript headers) are in Mountain Time (`America/Denver`, MST/MDT)
|
||||
for everyone for now; `ALIGNMENT_TIMEZONE` or the `timezone` key of the `alignment_model` API tokens changes it.
|
||||
Per-person zones from the timezone cog are on the TODO list.
|
||||
|
||||
`ALIGNMENT_CONTEXT_TOKENS` (default 32,000; Qwen3.5-9B allows 131,072 on yveltal) sets the budget. On yveltal's
|
||||
GTX 1080 + 1060 the model reads about 400-600 tokens/s, so a 32k guess takes around 1.5-2 minutes in all; the
|
||||
message shows progress meanwhile.
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
|
||||
4. Guess sampling: cache the dossier per person for an hour so repeat guesses are instant, and include
|
||||
thread messages (search filtered by parent channel ids leaves them out).
|
||||
5. Know people's time zones (aikaterna's timezone cog stores them) so the activity profile can say "posts at
|
||||
3am" instead of in UTC.
|
||||
5. Per-person time zones from aikaterna's timezone cog (it stores each user's zone). For now everyone is
|
||||
assumed to be in Mountain Time (`ALIGNMENT_TIMEZONE`, default `America/Denver`).
|
||||
|
||||
## Done on 2026-11-05 (second round)
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ import os
|
||||
import re
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable, Mapping
|
||||
from datetime import UTC, tzinfo
|
||||
from typing import Literal
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
@@ -178,6 +180,25 @@ def spec_summary(spec: ChartSpec) -> str:
|
||||
)
|
||||
|
||||
|
||||
# Until per-person zones come from the timezone cog, everyone is assumed to
|
||||
# be here (ALIGNMENT_TIMEZONE overrides)
|
||||
DEFAULT_TIMEZONE = "America/Denver"
|
||||
|
||||
|
||||
def guess_timezone(env: Mapping[str, str], tokens: Mapping[str, str]) -> tzinfo:
|
||||
"""Return the time zone guesses use; UTC if the name is unknown.
|
||||
|
||||
From ``ALIGNMENT_TIMEZONE``, else the ``alignment_model`` API
|
||||
token ``timezone``, else Mountain Time.
|
||||
"""
|
||||
name = env.get("ALIGNMENT_TIMEZONE") or tokens.get("timezone")
|
||||
try:
|
||||
return ZoneInfo(name or DEFAULT_TIMEZONE)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
log.warning("Unknown time zone %r; using UTC", name)
|
||||
return UTC
|
||||
|
||||
|
||||
def model_config(
|
||||
env: Mapping[str, str], tokens: Mapping[str, str]
|
||||
) -> ModelConfig | None:
|
||||
@@ -970,6 +991,12 @@ class AlignmentCog(commands.Cog):
|
||||
avatar=avatar,
|
||||
palette=palette,
|
||||
hidden=await self._blocked_users(),
|
||||
tz=guess_timezone(
|
||||
os.environ,
|
||||
await self.bot.get_shared_api_tokens(
|
||||
"alignment_model"
|
||||
),
|
||||
),
|
||||
)
|
||||
prompt = build_prompt(
|
||||
dossier, chart.spec, config.context_tokens
|
||||
|
||||
@@ -7,7 +7,8 @@ the history down at that point, so two pages give the posting rate between
|
||||
them, and all pages together sketch how it changed over the years, without
|
||||
fetching anything else.
|
||||
|
||||
Hours are UTC, since the bot doesn't know anyone's time zone.
|
||||
Hours and weekdays are in the time zone the front end passes (for now one
|
||||
for everyone; per-person zones can come from a timezone cog later).
|
||||
"""
|
||||
|
||||
import math
|
||||
@@ -16,7 +17,7 @@ import statistics
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from datetime import UTC, date, datetime, tzinfo
|
||||
|
||||
from .messages import Message, by_time
|
||||
|
||||
@@ -56,6 +57,7 @@ class Activity:
|
||||
median_burst: float
|
||||
average_length: float
|
||||
shares: dict[str, float]
|
||||
zone: str = "UTC"
|
||||
|
||||
|
||||
def rates_between(anchors: Sequence[Anchor]) -> tuple[Rate, ...]:
|
||||
@@ -132,6 +134,17 @@ def _share(
|
||||
return sum(1 for m in messages if test(m)) / len(messages)
|
||||
|
||||
|
||||
def _fraction(
|
||||
times: Sequence[datetime], test: Callable[[datetime], bool]
|
||||
) -> float:
|
||||
return sum(1 for t in times if test(t)) / len(times) if times else 0.0
|
||||
|
||||
|
||||
def zone_name(tz: tzinfo) -> str:
|
||||
"""Name a time zone: its IANA key (America/Denver) or its name."""
|
||||
return str(getattr(tz, "key", None) or tz.tzname(None) or "UTC")
|
||||
|
||||
|
||||
def _shouty(text: str) -> bool:
|
||||
letters = LETTERS.findall(text)
|
||||
return (
|
||||
@@ -160,9 +173,14 @@ def activity(
|
||||
anchors: Sequence[Anchor],
|
||||
total: int,
|
||||
joined: date | None = None,
|
||||
tz: tzinfo = UTC,
|
||||
) -> Activity:
|
||||
"""Summarise ``own`` messages (the sampled pages) and the anchors."""
|
||||
hours = Counter(m.created.hour for m in own)
|
||||
"""Summarise ``own`` messages (the sampled pages) and the anchors.
|
||||
|
||||
Hours, nights and weekends are counted in ``tz``.
|
||||
"""
|
||||
local = [m.created.astimezone(tz) for m in own]
|
||||
hours = Counter(t.hour for t in local)
|
||||
gaps = gaps_seconds(own)
|
||||
lengths = [len(m.content) for m in own if m.content]
|
||||
return Activity(
|
||||
@@ -170,12 +188,13 @@ def activity(
|
||||
joined=joined,
|
||||
rates=rates_between(anchors),
|
||||
hours=tuple(hours.get(h, 0) for h in range(24)),
|
||||
weekend_share=_share(own, lambda m: m.created.weekday() >= 5), # noqa: PLR2004
|
||||
night_share=_share(own, lambda m: m.created.hour < 6), # noqa: PLR2004
|
||||
weekend_share=_fraction(local, lambda t: t.weekday() >= 5), # noqa: PLR2004
|
||||
night_share=_fraction(local, lambda t: t.hour < 6), # noqa: PLR2004
|
||||
burstiness=burstiness(gaps),
|
||||
median_burst=median_burst(gaps) if own else 0,
|
||||
average_length=statistics.fmean(lengths) if lengths else 0.0,
|
||||
shares=style_shares(own),
|
||||
zone=zone_name(tz),
|
||||
)
|
||||
|
||||
|
||||
@@ -228,11 +247,11 @@ def describe(a: Activity) -> str:
|
||||
),
|
||||
*(rate_lines or [" not enough samples"]),
|
||||
(
|
||||
f"Busiest hours (UTC): {_busiest_hours(a.hours)}; "
|
||||
f"Busiest hours ({a.zone}): {_busiest_hours(a.hours)}; "
|
||||
f"{_hour_spread(a.hours)}"
|
||||
),
|
||||
(
|
||||
f"Late night (00-06 UTC): {a.night_share:.0%}; "
|
||||
f"Late night (00-06 {a.zone}): {a.night_share:.0%}; "
|
||||
f"weekends: {a.weekend_share:.0%}"
|
||||
),
|
||||
(
|
||||
|
||||
@@ -14,7 +14,7 @@ channel separation, reply links and time gaps get most of the way.
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta, tzinfo
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .messages import Message, by_time
|
||||
@@ -194,9 +194,12 @@ def render_segment(
|
||||
target_id: str,
|
||||
target_name: str,
|
||||
hidden_authors: frozenset[str] = frozenset(),
|
||||
tz: tzinfo = UTC,
|
||||
) -> str:
|
||||
"""Return a transcript: a date and channel line, then the turns.
|
||||
|
||||
The date is local to ``tz``, with its abbreviation (MST, MDT, ...).
|
||||
|
||||
Other people are anonymised as letters; anyone in
|
||||
``hidden_authors`` has their words replaced by :data:`HIDDEN`.
|
||||
"""
|
||||
@@ -204,7 +207,8 @@ def render_segment(
|
||||
return ""
|
||||
first = segment[0].messages[0]
|
||||
labels = speaker_labels(segment, target_id, target_name)
|
||||
header = f"[{first.created:%Y-%m-%d %H:%M} UTC, #{first.channel_name}]"
|
||||
local = first.created.astimezone(tz)
|
||||
header = f"[{local:%Y-%m-%d %H:%M %Z}, #{first.channel_name}]"
|
||||
lines = [
|
||||
f"{labels[t.author_id]}: "
|
||||
+ (
|
||||
|
||||
@@ -8,7 +8,7 @@ conversation, grouped by page so packing can spread over the history.
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import date
|
||||
from datetime import UTC, date, tzinfo
|
||||
|
||||
from .activity import Anchor, activity, describe
|
||||
from .conversations import conversations_with, render_segment
|
||||
@@ -36,6 +36,7 @@ def evidence(
|
||||
target_id: str,
|
||||
target_name: str,
|
||||
hidden: frozenset[str] = frozenset(),
|
||||
tz: tzinfo = UTC,
|
||||
) -> tuple[Evidence, ...]:
|
||||
"""Return one evidence item per conversation the target was in.
|
||||
|
||||
@@ -46,7 +47,9 @@ def evidence(
|
||||
return tuple(
|
||||
Evidence(
|
||||
segment[0].start,
|
||||
render_segment(segment, target_id, target_name, hidden),
|
||||
render_segment(
|
||||
segment, target_id, target_name, hidden, tz
|
||||
),
|
||||
group,
|
||||
)
|
||||
for group, page in enumerate(pages)
|
||||
@@ -68,13 +71,19 @@ def build_dossier( # noqa: PLR0913 (it gathers everything)
|
||||
avatar: str = "",
|
||||
palette: str = "",
|
||||
hidden: frozenset[str] = frozenset(),
|
||||
tz: tzinfo = UTC,
|
||||
) -> Dossier:
|
||||
"""Return the dossier for ``name`` from the fetched pages."""
|
||||
"""Return the dossier for ``name`` from the fetched pages.
|
||||
|
||||
Times in the activity profile and transcripts are local to ``tz``.
|
||||
"""
|
||||
own = [m for page in pages for m in page.items]
|
||||
return Dossier(
|
||||
name=name,
|
||||
activity=describe(activity(own, anchors(pages), total, joined)),
|
||||
activity=describe(
|
||||
activity(own, anchors(pages), total, joined, tz)
|
||||
),
|
||||
avatar=avatar,
|
||||
palette=palette,
|
||||
evidence=evidence(pages, contexts, target_id, name, hidden),
|
||||
evidence=evidence(pages, contexts, target_id, name, hidden, tz),
|
||||
)
|
||||
@@ -8,7 +8,8 @@
|
||||
"name": "doge_alignment",
|
||||
"short": "D&D alignment chart for your server, drawn with members' avatars",
|
||||
"requirements": [
|
||||
"Wand==0.7.2"
|
||||
"Wand==0.7.2",
|
||||
"tzdata"
|
||||
],
|
||||
"description": "A 3x3 D&D alignment chart per server, drawn as one picture or as a gallery of nine, with members' avatars. Custom labels and colours, suggestions that members accept or reject, guesses from a local language model, alignment admins, YAML export and import. Slash and text commands (`alignment`). Needs ImageMagick (libmagickwand, plus its Pango coder for emoji) on the bot's host; without it the chart is shown as text.",
|
||||
"tags": [
|
||||
|
||||
@@ -76,3 +76,21 @@ def test_night_and_weekend_shares() -> None:
|
||||
a = activity([msg(1, minutes=offset), msg(2)], [], total=2)
|
||||
assert a.night_share == 0.5 # noqa: PLR2004
|
||||
assert a.weekend_share == 0.5 # noqa: PLR2004
|
||||
|
||||
|
||||
def test_hours_nights_and_weekends_in_mountain_time() -> None:
|
||||
"""Times are counted in the given zone, daylight saving included."""
|
||||
from zoneinfo import ZoneInfo # noqa: PLC0415
|
||||
|
||||
denver = ZoneInfo("America/Denver")
|
||||
# 2024-01-06 09:00 UTC is Saturday 02:00 MST: night and weekend
|
||||
saturday_2am = datetime(2024, 1, 6, 9, 0, tzinfo=UTC)
|
||||
offset = (saturday_2am - START).total_seconds() / 60
|
||||
a = activity([msg(1, minutes=offset)], [], total=1, tz=denver)
|
||||
assert a.hours[2] == 1
|
||||
assert (a.night_share, a.weekend_share) == (1, 1)
|
||||
assert a.zone == "America/Denver"
|
||||
assert "Busiest hours (America/Denver): 02:00" in describe(a)
|
||||
# The same UTC instant counted in UTC is 09:00, not night
|
||||
utc = activity([msg(1, minutes=offset)], [], total=1)
|
||||
assert (utc.hours[9], utc.night_share) == (1, 0)
|
||||
@@ -204,3 +204,19 @@ def test_model_config_from_env_then_tokens() -> None:
|
||||
)
|
||||
assert thinking_off is not None
|
||||
assert thinking_off.extra == {"reasoning_effort": "none"}
|
||||
|
||||
|
||||
def test_guess_timezone() -> None:
|
||||
"""Mountain Time unless set; unknown names fall back to UTC."""
|
||||
from datetime import UTC # noqa: PLC0415
|
||||
|
||||
from doge_alignment.cog import guess_timezone # noqa: PLC0415
|
||||
|
||||
assert str(guess_timezone({}, {})) == "America/Denver"
|
||||
assert str(guess_timezone({}, {"timezone": "Europe/Paris"})) == (
|
||||
"Europe/Paris"
|
||||
)
|
||||
assert str(
|
||||
guess_timezone({"ALIGNMENT_TIMEZONE": "Asia/Tokyo"}, {})
|
||||
) == ("Asia/Tokyo")
|
||||
assert guess_timezone({"ALIGNMENT_TIMEZONE": "Mars/Base"}, {}) is UTC
|
||||
@@ -99,3 +99,16 @@ def test_tidy() -> None:
|
||||
)
|
||||
assert tidy("<@!5>", {"5": "A"}) == "@A"
|
||||
assert tidy("http://x") == "<link: x>"
|
||||
|
||||
|
||||
def test_transcript_header_in_local_time() -> None:
|
||||
"""Headers show local time with MST or MDT."""
|
||||
from zoneinfo import ZoneInfo # noqa: PLC0415
|
||||
|
||||
denver = ZoneInfo("America/Denver")
|
||||
winter = segments(merge_bursts([msg(1, "55")]))[0]
|
||||
assert render_segment(winter, "55", "Doge", tz=denver).startswith(
|
||||
"[2024-01-01 05:00 MST, #chan-c1]"
|
||||
)
|
||||
summer = segments(merge_bursts([msg(1, "55", 60 * 24 * 182)]))[0]
|
||||
assert "06:00 MDT" in render_segment(summer, "55", "Doge", tz=denver)
|
||||
Reference in new issue
Block a user