Extend balanced commercial scheduling to all episode channels

This commit is contained in:
Josh
2026-11-13 17:13:42 -05:00
parent 9978d3bb08
commit 19c0751a4a
2 changed files with 25 additions and 21 deletions

View File

@@ -19,9 +19,9 @@ Place commercial clips in `data/commercials/`. Compose mounts that folder read-o
Scan the source after adding clips, then create a **Commercials** filler list under **Library → Fillers**. For breaks between episodes, assign the list as **Post** filler in a slot schedule. For breaks during episodes, assign it as **Mid** filler and set the break timing. Channel-level Flex uses filler only when the lineup contains Flex time.
On this host, channel 3 uses `scripts/south-park-commercials.py` from the user's crontab every minute. The script scans changed files after their sizes and modification times stabilize and applies the refreshed lineup when channel 3 has no active session. It uses one clip of at least 60 seconds between episodes and two clips of at most 30 seconds at the 25%, 50%, and 75% marks. Each duration group uses shuffled rounds with equal play counts to within one per lineup cycle. Clips longer than 30 seconds and shorter than 60 seconds are outside both groups.
On this host, channels 1–11 use `scripts/channel-commercials.py` from the user's crontab every minute. The script scans changed files after their sizes and modification times stabilize and applies the refreshed lineup when each channel has no active session. It uses one clip of at least 60 seconds between episodes and two clips of at most 30 seconds at the 25%, 50%, and 75% marks. Each duration group uses shuffled rounds with equal play counts to within one per lineup cycle. Clips longer than 30 seconds and shorter than 60 seconds are outside both groups.
The script reads the original ordered episode lineup from `data/south-park-commercials/episodes.json`, which is local deployment state. Run `python3 scripts/south-park-commercials.py --apply-active` for an immediate update that can restart channel 3 if the indexed library has changed.
The script reads the original ordered episode lineups from `data/channel-commercials/`, which is local deployment state. Run `python3 scripts/channel-commercials.py --apply-active` for an immediate update that can restart affected channels if the indexed library has changed.
YouTube watch links use YouTube's web player. To put videos in a retroLabs channel, obtain playable files from the creator or another authorized download source and add them to a Tunarr **Other Videos** library. Keep a separate library for clips intended as regular programming.

View File

@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Refresh channel 3 from the local Commercials library."""
"""Refresh configured episode channels from the local Commercials library."""
import argparse
import collections
import fcntl
@@ -12,8 +12,7 @@ import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / "data" / "south-park-commercials"
CHANNEL = "563f25bd-b9e7-4749-ae07-0fec0a6eb24b"
STATE = ROOT / "data" / "channel-commercials"
MEDIA_EXTENSIONS = {".mp4", ".mkv", ".mov", ".m4v", ".webm", ".avi", ".ts"}
@@ -39,10 +38,10 @@ def save_json(path, value):
temporary.replace(path)
def stored_items():
def stored_items(channel_id):
result = subprocess.check_output(
["docker", "compose", "exec", "-T", "tunarr", "cat",
f"/config/tunarr/channel-lineups/{CHANNEL}.json"], cwd=ROOT,
f"/config/tunarr/channel-lineups/{channel_id}.json"], cwd=ROOT,
)
return json.loads(result)["items"]
@@ -122,12 +121,6 @@ def refresh(apply_active):
return
signature = [[clip["uuid"], clip["duration"]] for clip in clips]
applied = STATE / "applied.json"
if applied.exists() and signature == json.loads(applied.read_text()):
return
if api(f"/channels/{CHANNEL}")["sessions"] and not apply_active:
return
filler = next(item for item in api("/filler-lists") if item["name"] == "Commercials")
filler_path = f'/filler-lists/{filler["id"]}'
members = [{"type": "content", "id": clip["uuid"], "duration": clip["duration"],
@@ -136,25 +129,36 @@ def refresh(apply_active):
if {item["id"] for item in current} != {clip["uuid"] for clip in clips}:
api(filler_path, {"programs": members}, method="PUT")
episodes = json.loads((STATE / "episodes.json").read_text())
lineup = build_lineup(episodes, short, long, filler["id"])
api(f"/channels/{CHANNEL}/programming", {"type": "manual", "append": False, "lineup": lineup})
configured = json.loads((STATE / "channels.json").read_text())
for channel_id, name in configured.items():
applied = STATE / f"{channel_id}-applied.json"
if applied.exists() and signature == json.loads(applied.read_text()):
continue
if not apply_active and api(f"/channels/{channel_id}")["sessions"]:
continue
apply_lineup(channel_id, name, short, long, filler["id"], apply_active)
save_json(applied, signature)
def apply_lineup(channel_id, name, short, long, filler_id, apply_active):
episodes = json.loads((STATE / f"{channel_id}-episodes.json").read_text())
lineup = build_lineup(episodes, short, long, filler_id)
api(f"/channels/{channel_id}/programming", {"type": "manual", "append": False, "lineup": lineup})
expected_items = [
{"type": "content", "id": entry["id"], "durationMs": entry["duration"],
**({"startOffsetMs": entry["startOffsetMs"]} if entry["type"] == "content"
else {"fillerListId": filler["id"], "fillerType": entry["fillerType"]})}
else {"fillerListId": filler_id, "fillerType": entry["fillerType"]})}
for entry in lineup
]
assert stored_items() == expected_items, "Saved lineup differs from requested lineup"
save_json(applied, signature)
assert stored_items(channel_id) == expected_items, "Saved lineup differs from requested lineup"
if apply_active:
try:
api(f"/channels/{CHANNEL}/sessions", method="DELETE")
api(f"/channels/{channel_id}/sessions", method="DELETE")
except urllib.error.HTTPError as error:
if error.code != 404:
raise
counts = collections.Counter(item["id"] for item in lineup if item["type"] == "filler")
print(f"Verified {len(episodes)} episodes and {sum(counts.values())} ads. Plays by clip: {dict(counts)}")
print(f"{name}: verified {len(episodes)} episodes and {sum(counts.values())} ads. Plays by clip: {dict(counts)}")
if __name__ == "__main__":