Randomize YouTube time-slot rotation instead of even 24/N splits.
Daily-stable shuffle + uneven window lengths reduce bot-like equal channel schedules while keeping relay decisions consistent within a Beijing day. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
e8bc7764b6
commit
31a249ed90
@ -6,6 +6,8 @@ shorts_channels for OAuth profile cards on /youtube.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import random
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
@ -309,6 +311,67 @@ def _beijing_hour_fraction(ts: float | None = None) -> float:
|
||||
return dt.hour + dt.minute / 60.0 + dt.second / 3600.0
|
||||
|
||||
|
||||
def _beijing_day_key(ts: float | None = None) -> str:
|
||||
from .timeutil import beijing_from_ts
|
||||
|
||||
dt = beijing_from_ts(ts if ts is not None else time.time())
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _slot_active(now_h: float, start_h: float, end_h: float) -> bool:
|
||||
"""True if now_h is in [start_h, end_h) on a 24h clock (supports wrap past midnight)."""
|
||||
now_h = float(now_h) % 24.0
|
||||
start_h = float(start_h) % 24.0
|
||||
end_h = float(end_h) % 24.0
|
||||
if abs(end_h - start_h) < 1e-9:
|
||||
return True # full day
|
||||
if start_h < end_h:
|
||||
return start_h <= now_h < end_h
|
||||
# wraps midnight
|
||||
return now_h >= start_h or now_h < end_h
|
||||
|
||||
|
||||
def _daily_random_windows(n: int, *, seed: str) -> list[tuple[float, float, float]]:
|
||||
"""Uneven random 24h partition for N channels.
|
||||
|
||||
Stable for a given seed (Beijing day + channel set). Order of returned
|
||||
windows matches the already-shuffled channel list. Avoids equal 24/N
|
||||
splits that look bot-like to YouTube.
|
||||
"""
|
||||
if n <= 0:
|
||||
return []
|
||||
rng = random.Random(seed)
|
||||
if n == 1:
|
||||
return [(0.0, 24.0, 24.0)]
|
||||
# Broken-stick spacings → uneven lengths; reject if any slice too short.
|
||||
min_h = min(0.75, max(0.35, 24.0 / (n * 4.0)))
|
||||
hours: list[float] = []
|
||||
for _ in range(40):
|
||||
pts = [0.0] + sorted(rng.random() for _ in range(n - 1)) + [1.0]
|
||||
hours = [(pts[i + 1] - pts[i]) * 24.0 for i in range(n)]
|
||||
if min(hours) >= min_h - 1e-9:
|
||||
break
|
||||
else:
|
||||
# Fallback: soft-jitter equal split so we never stall
|
||||
base = 24.0 / n
|
||||
jitter = [rng.uniform(0.65, 1.35) for _ in range(n)]
|
||||
s = sum(jitter)
|
||||
hours = [base * j * n / s for j in jitter]
|
||||
# renormalize exact 24
|
||||
s2 = sum(hours)
|
||||
hours = [h * 24.0 / s2 for h in hours]
|
||||
# Random day offset so boundaries don't always sit on the hour / midnight
|
||||
offset = rng.uniform(0.0, 24.0)
|
||||
out: list[tuple[float, float, float]] = []
|
||||
t = offset
|
||||
for h in hours:
|
||||
start = t % 24.0
|
||||
end = (t + h) % 24.0
|
||||
out.append((start, end, h))
|
||||
t += h
|
||||
return out
|
||||
|
||||
|
||||
ASSIGN_CATEGORIES = ("normal", "time_slot")
|
||||
ASSIGN_CATEGORY_LABELS = {"normal": "普通", "time_slot": "时间段"}
|
||||
|
||||
@ -1773,7 +1836,11 @@ def build_rotation_schedule(
|
||||
groups: list[dict[str, Any]] | None = None,
|
||||
keyed_only: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""24h Beijing rotation: N channels → 24/N hours each, no overlap.
|
||||
"""24h Beijing rotation with daily-stable random order & uneven lengths.
|
||||
|
||||
Anti-bot: NOT equal 24/N splits and NOT fixed channel order. Seeded by
|
||||
Beijing calendar day + channel id set so the board stays stable within a
|
||||
day (and while relay polls) but reshuffles overnight.
|
||||
|
||||
keyed_only=True (时间段模式): enabled groups with a stream key, deduped by YouTube channel
|
||||
(same channel + different keys still counts as one slot; keys may be wrong/backups).
|
||||
@ -1800,30 +1867,47 @@ def build_rotation_schedule(
|
||||
rotation_rows = [(g, []) for g in enabled]
|
||||
n = len(rotation_rows)
|
||||
now_h = _beijing_hour_fraction()
|
||||
day_key = _beijing_day_key()
|
||||
if n == 0:
|
||||
return {
|
||||
"ok": True,
|
||||
"channel_count": 0,
|
||||
"slot_hours": 0,
|
||||
"slot_hours_min": 0,
|
||||
"slot_hours_max": 0,
|
||||
"now_hour": round(now_h, 3),
|
||||
"now_label": _fmt_hour(now_h),
|
||||
"keyed_only": bool(keyed_only),
|
||||
"time_slot_mode": bool(keyed_only),
|
||||
"randomized": True,
|
||||
"schedule_day": day_key,
|
||||
"channels": [],
|
||||
}
|
||||
slot_h = 24.0 / n
|
||||
|
||||
# Daily-stable shuffle (do not use sort_order as wall-clock order)
|
||||
id_key = ",".join(
|
||||
sorted(str((g.get("id") or "")) for g, _aliases in rotation_rows)
|
||||
)
|
||||
seed = hashlib.sha256(f"yt-slot-v2|{day_key}|{id_key}".encode("utf-8")).hexdigest()
|
||||
rng = random.Random(seed)
|
||||
shuffled = list(rotation_rows)
|
||||
rng.shuffle(shuffled)
|
||||
windows = _daily_random_windows(n, seed=seed + "|win")
|
||||
|
||||
channels: list[dict[str, Any]] = []
|
||||
for i, (g, alias_ids) in enumerate(rotation_rows):
|
||||
start_h = i * slot_h
|
||||
end_h = (i + 1) * slot_h
|
||||
active = start_h <= now_h < end_h if end_h <= 24 else (now_h >= start_h or now_h < (end_h % 24))
|
||||
hour_vals: list[float] = []
|
||||
for i, (g, alias_ids) in enumerate(shuffled):
|
||||
start_h, end_h, slot_h = windows[i]
|
||||
hour_vals.append(slot_h)
|
||||
active = _slot_active(now_h, start_h, end_h)
|
||||
slots_raw = list(g.get("slots") or [])
|
||||
m = len(slots_raw)
|
||||
sub_h = slot_h / m if m else 0.0
|
||||
slot_items: list[dict[str, Any]] = []
|
||||
# Sub-windows follow the channel arc (may wrap); keep relative fractions
|
||||
for j, s in enumerate(slots_raw):
|
||||
u_start = start_h + j * sub_h
|
||||
u_end = start_h + (j + 1) * sub_h
|
||||
u_start = (start_h + j * sub_h) % 24.0
|
||||
u_end = (start_h + (j + 1) * sub_h) % 24.0
|
||||
slot_items.append(
|
||||
{
|
||||
**s,
|
||||
@ -1854,14 +1938,19 @@ def build_rotation_schedule(
|
||||
"slots": slot_items,
|
||||
}
|
||||
)
|
||||
avg_h = (sum(hour_vals) / n) if n else 0.0
|
||||
return {
|
||||
"ok": True,
|
||||
"channel_count": n,
|
||||
"slot_hours": round(slot_h, 2),
|
||||
"slot_hours": round(avg_h, 2),
|
||||
"slot_hours_min": round(min(hour_vals), 2) if hour_vals else 0,
|
||||
"slot_hours_max": round(max(hour_vals), 2) if hour_vals else 0,
|
||||
"now_hour": round(now_h, 3),
|
||||
"now_label": _fmt_hour(now_h),
|
||||
"keyed_only": bool(keyed_only),
|
||||
"time_slot_mode": bool(keyed_only),
|
||||
"randomized": True,
|
||||
"schedule_day": day_key,
|
||||
"channels": channels,
|
||||
}
|
||||
|
||||
|
||||
@ -130,10 +130,14 @@ type ScheduleChannel = {
|
||||
type RotationSchedule = {
|
||||
channel_count?: number;
|
||||
slot_hours?: number;
|
||||
slot_hours_min?: number;
|
||||
slot_hours_max?: number;
|
||||
now_hour?: number;
|
||||
now_label?: string;
|
||||
keyed_only?: boolean;
|
||||
time_slot_mode?: boolean;
|
||||
randomized?: boolean;
|
||||
schedule_day?: string;
|
||||
channels?: ScheduleChannel[];
|
||||
};
|
||||
|
||||
@ -1530,7 +1534,7 @@ export function YtAssignPanel({
|
||||
value={newCategory}
|
||||
onChange={(e) => setNewCategory((e.target.value as AssignCategory) || "normal")}
|
||||
disabled={busy}
|
||||
title="分组分类:普通=关排班时自动听直播地址;时间段=24/N 排班"
|
||||
title="分组分类:普通=关排班时自动听直播地址;时间段=日随机错峰排班"
|
||||
className="rounded-xl border border-white/10 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none ring-rose-400/0 transition focus:ring-2 focus:ring-rose-400/30"
|
||||
>
|
||||
<option value="normal">普通</option>
|
||||
@ -1546,7 +1550,7 @@ export function YtAssignPanel({
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-2 text-[10px] text-slate-500">
|
||||
普通 = 关「时间段排班」且开「自动推流」时监听直播地址列表;时间段 = 24/N + 监控在播抖音。单路独占时只跑最先开播的那一路。
|
||||
普通 = 关「时间段排班」且开「自动推流」时监听直播地址列表;时间段 = 日随机错峰(不均分)+ 监控在播抖音。单路独占时只跑最先开播的那一路。
|
||||
</p>
|
||||
{channels.length === 0 ? (
|
||||
<p className="mt-3 text-xs text-amber-200">
|
||||
@ -1592,7 +1596,11 @@ export function YtAssignPanel({
|
||||
时间段排班 ·「时间段」分类频道(北京时间)
|
||||
</h4>
|
||||
<p className="mt-0.5 text-[11px] text-teal-200/65">
|
||||
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "}
|
||||
{schedule.channel_count} 个频道 · 日随机错峰{" "}
|
||||
{schedule.slot_hours_min != null && schedule.slot_hours_max != null
|
||||
? `${schedule.slot_hours_min}–${schedule.slot_hours_max}h`
|
||||
: `约 ${schedule.slot_hours}h`}
|
||||
{schedule.schedule_day ? ` · ${schedule.schedule_day}` : ""} · 当前{" "}
|
||||
{schedule.now_label} · 源=在播抖音
|
||||
</p>
|
||||
</div>
|
||||
@ -1932,7 +1940,7 @@ export function YtAssignPanel({
|
||||
? "border-teal-400/35 bg-teal-500/15 text-teal-100"
|
||||
: "border-white/15 bg-black/40 text-slate-200"
|
||||
}`}
|
||||
title="普通=关排班时自动推流;时间段=24/N 排班"
|
||||
title="普通=关排班时自动推流;时间段=日随机错峰排班"
|
||||
>
|
||||
<option value="normal">普通</option>
|
||||
<option value="time_slot">时间段</option>
|
||||
|
||||
@ -164,7 +164,7 @@ export function YtRelayOpsHero({
|
||||
</h3>
|
||||
<p className="mt-1.5 text-sm leading-relaxed text-slate-400">
|
||||
{timeSlotModeOn
|
||||
? `排班中:${keyedChannelCount || "N"} 个「时间段」频道平分 24h(北京时间),源取监控里当前在播抖音。`
|
||||
? `排班中:${keyedChannelCount || "N"} 个「时间段」频道按日随机错峰(时长不均、顺序打乱,防机器人指纹),源取监控在播抖音。`
|
||||
: "普通模式:开「自动推流」后各普通频道监听直播地址列表,房间开播即推。"}
|
||||
{exclusiveLiveOn
|
||||
? " 「单路独占」:只保留最先开播的一路 FFmpeg + Neko,该路真正停播后再进下一轮。"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user