From 16901c50cef111dad6463700e24ed455937cf6a3 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Thu, 5 Nov 2026 15:34:47 +0000 Subject: [PATCH] Director's Chair: other channels in a drop-down, and learning from your decisions The pop-up keeps its suggestion (or an ask's two channels) up front and puts every other channel in an 'Other channels' drop-down: scored fits first, then the rest of the title's kind with why each is outside its usual brief. Never the wrong kind, a children's channel for an adult rating, animation for live action, or Premiere. Learning (ChairLearning.kt): the decisions the Chair keeps become lessons when two or more go the same way: a redirect (you keep putting a genre on another channel) or a hold-back (you keep dropping a genre for a channel), each explained by its own decisions. Shown always; used only while your Learning switch on the Chair is on (off by default). Off undoes every effect at once. Nothing is booked, placed or approved by it. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../java/tv/orbit/classic/ChairLearning.kt | 57 +++++++++++ .../java/tv/orbit/classic/DirectorChair.kt | 94 +++++++++++++++---- .../tv/orbit/classic/EmbyConnectionScreen.kt | 10 +- .../java/tv/orbit/classic/ScheduleStore.kt | 2 + .../tv/orbit/classic/ChairLearningTest.kt | 45 +++++++++ .../tv/orbit/classic/DirectorChairTest.kt | 4 +- 6 files changed, 190 insertions(+), 22 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/ChairLearning.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ChairLearningTest.kt diff --git a/android/app/src/main/java/tv/orbit/classic/ChairLearning.kt b/android/app/src/main/java/tv/orbit/classic/ChairLearning.kt new file mode 100644 index 00000000..fb2916b1 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ChairLearning.kt @@ -0,0 +1,57 @@ +package tv.orbit.classic + +import org.json.JSONObject +import java.io.File + +/** + * The Director's Chair learning from your decisions (Paul, 5 November 2026): local, explainable and reversible. It reads the + * decisions the Chair has kept and finds the patterns in them, each a lesson in plain words with the decisions behind it: + * - a redirect: you put titles of a genre on another channel than the one suggested, at least [LESSON_MIN] times; + * - a hold-back: you dropped titles of a genre suggested for a channel, at least [LESSON_MIN] times; + * - agreement: how often you placed a title where the Chair suggested. + * Lessons only change suggestions while learning is switched on ([ChairLearning.on], your switch on the Chair). Off, the Chair + * suggests from the briefs alone and the lessons are just shown. Switching off undoes every effect at once; no decision is lost. + * Learning never books, places or approves anything. + */ +internal const val LESSON_MIN = 2 + +internal class ChairLesson(val kind: Kind, val genre: String, val from: Int, val to: Int?, val count: Int, val titles: List) { + enum class Kind { Redirect, HoldBack } + fun text(): String { + val fromName = Briefs.firstOrNull { it.number == from }?.name ?: "$from" + return when (kind) { + Kind.Redirect -> "$genre titles suggested for $fromName go on ${Briefs.firstOrNull { it.number == to }?.name ?: "$to"} ($count times: ${titles.take(3).joinToString(", ")})" + Kind.HoldBack -> "Fewer $genre titles for $fromName: you dropped $count (${titles.take(3).joinToString(", ")})" + } + } +} + +internal class ChairLessons(val lessons: List, val decisions: Int, val agreed: Int, val changed: Int, val dropped: Int) { + /** The lesson that applies to a title suggested for [channel] with [genres], redirects first. */ + fun redirectFor(channel: Int, genres: Set) = lessons.firstOrNull { it.kind == ChairLesson.Kind.Redirect && it.from == channel && it.genre in genres } + fun holdBackFor(channel: Int, genres: Set) = lessons.firstOrNull { it.kind == ChairLesson.Kind.HoldBack && it.from == channel && it.genre in genres } + fun summary(): String = if (decisions == 0) "No decisions yet." else + "$decisions decisions: $agreed placed where suggested, $changed placed elsewhere, $dropped dropped." +} + +/** The lessons in [decisions], judged by each decided title's genres in [evidence]. Titles without evidence teach nothing. */ +internal fun chairLessons(decisions: List, evidence: Map): ChairLessons { + val judged = decisions.filter { !it.premiere && it.suggested != null } + val redirects = HashMap, MutableList>(); val drops = HashMap, MutableList>() + for (d in judged) { + val genres = evidence[d.id]?.genreSet.orEmpty() + val suggested = d.suggested ?: continue + if (d.placed && d.channel != null && d.channel != suggested) genres.forEach { redirects.getOrPut(Triple(it, suggested, d.channel)) { mutableListOf() } += d.title } + if (!d.placed) genres.forEach { drops.getOrPut(it to suggested) { mutableListOf() } += d.title } + } + val lessons = redirects.filterValues { it.size >= LESSON_MIN }.map { (k, t) -> ChairLesson(ChairLesson.Kind.Redirect, k.first, k.second, k.third, t.size, t) } + + drops.filterValues { it.size >= LESSON_MIN }.map { (k, t) -> ChairLesson(ChairLesson.Kind.HoldBack, k.first, k.second, null, t.size, t) } + return ChairLessons(lessons.sortedByDescending { it.count }, judged.size, judged.count { it.placed && it.channel == it.suggested }, + judged.count { it.placed && it.channel != it.suggested }, judged.count { !it.placed }) +} + +/** Your learning switch on the Chair, kept on the box. Off unless you turn it on. */ +internal object ChairLearning { + fun on(file: File): Boolean = runCatching { JSONObject(file.readText()).optBoolean("on") }.getOrDefault(false) + fun set(file: File, on: Boolean) = runCatching { file.writeText(JSONObject().put("on", on).toString()) } +} diff --git a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt index ef98affa..2924ce3d 100644 --- a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt +++ b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt @@ -81,13 +81,16 @@ internal class DeskReport(val newlyReleased: Int, val newToLibrary: Int, val sca /** Recent major films whose evidence is still to be read before they can be judged. */ val premiereQueued: Int = 0, /** Premiere debuts you've approved, waiting for the booking workflow. */ - val premiereApproved: List = emptyList()) { + val premiereApproved: List = emptyList(), + /** What the Chair has learned from your decisions, in plain words, and whether it's allowed to use it. */ + val learnedSummary: String = "", val lessons: List = emptyList(), val learningOn: Boolean = false) { fun toJson(): JSONObject = JSONObject().put("newlyReleased", newlyReleased).put("newToLibrary", newToLibrary).put("scanned", scanned).put("unread", unread) .put("strong", strong).put("strongByChannel", JSONArray(strongByChannel.map { JSONObject().put("c", it.first).put("n", it.second) })) .put("picks", JSONArray(picks.map { JSONObject().put("t", it.title).put("c", it.channel).put("g", it.tag).put("l", it.line).item(it.id, it.type, it.year, it.options, it.firstRun) })) .put("asks", JSONArray(asks.map { JSONObject().put("t", it.title).put("a", it.first).put("b", it.second).put("l", it.line).item(it.id, it.type, it.year, it.options, it.firstRun) })) .put("collections", collections).put("franchises", franchises).put("catalogueComplete", catalogueComplete).put("computedMs", computedMs).put("tookMs", tookMs) .put("decided", decided).put("premieres", JSONArray(premieres.map { it.toJson() })).put("premiereQueued", premiereQueued).put("premiereApproved", JSONArray(premiereApproved)) + .put("learnedSummary", learnedSummary).put("lessons", JSONArray(lessons)).put("learningOn", learningOn) companion object { fun of(o: JSONObject): DeskReport { fun list(key: String) = o.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.getJSONObject(it) } }.orEmpty() @@ -97,7 +100,8 @@ internal class DeskReport(val newlyReleased: Int, val newToLibrary: Int, val sca list("asks").map { DeskAsk(it.optString("t"), it.optString("a"), it.optString("b"), it.optString("i"), it.optString("k"), it.year(), it.options(), it.optString("l"), it.firstRun()) }, o.optInt("collections"), o.optBoolean("catalogueComplete"), o.optInt("franchises"), o.optLong("computedMs"), o.optLong("tookMs"), o.optInt("decided"), list("premieres").map(DeskPremiere::of), o.optInt("premiereQueued"), - o.optJSONArray("premiereApproved")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty()) + o.optJSONArray("premiereApproved")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty(), + o.optString("learnedSummary"), o.optJSONArray("lessons")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty(), o.optBoolean("learningOn")) } } } @@ -140,6 +144,22 @@ internal fun homeOf(p: Placement): Placement { /** Where a placed title can go: the scored channels, best first, three at most, never one the scoring ruled out. */ private fun optionsOf(p: Placement, max: Int = 3): List = p.ranked.take(max).map { (b, _, why) -> DeskOption(b.number, b.name, reasonLine(why)) } +/** Hard limits a drop-down never crosses: the wrong kind (a series on a film channel), a children's channel for an adult rating, or animation and live action swapped. */ +private fun neverOffered(why: List) = why.firstOrNull()?.let { it == "wrong kind" || it.startsWith("rated ") || it.endsWith("not for this channel") && ("animation" in it || "live action" in it) } == true + +/** + * Every channel a title could be placed on, for the pop-up's drop-down: the scored fits best first, then the rest of its kind, + * each with the reason it's outside its usual brief. Premiere is never a home. + */ +internal fun channelChoices(p: Placement, text: ChannelText, links: FranchiseLinks): List { + val fits = p.ranked.filter { it.first.number != PREMIERE_NUMBER }.map { (b, _, why) -> DeskOption(b.number, b.name, reasonLine(why)) } + val rest = Briefs.filter { b -> b.number != PREMIERE_NUMBER && fits.none { it.number == b.number } }.mapNotNull { b -> + val why = channelScore(p.evidence, b, text, links).second + if (neverOffered(why)) null else DeskOption(b.number, b.name, "outside its usual brief: " + (why.firstOrNull() ?: "no fit")) + } + return fits + rest +} + /** Paul's standing editorial calls so far, shown so the director's reasoning is visible. */ internal val DirectorRules = listOf("Made-for-TV romances: not for Orbit", "Tales from the Crypt: After Dark strand", "Black Mirror: Paradox from 21:00") @@ -174,8 +194,8 @@ internal fun franchiseLinks(file: File, pools: Map>): Triple>, released: List, carriedWorks: Set, originals: Map, newToLibrary: Int, catalogueComplete: Boolean, mode: DirectorMode, nowMs: Long, zone: ZoneId = ZoneId.systemDefault(), - decided: Set = emptySet(), premiere: PremiereInputs = PremiereInputs()): DeskReport = - buildDeskReports(evidenceFile, collectionsFile, pools, released, carriedWorks, originals, newToLibrary, catalogueComplete, nowMs, zone, decided, premiere).getValue(mode) + decided: Set = emptySet(), premiere: PremiereInputs = PremiereInputs(), history: List = emptyList(), learning: Boolean = false): DeskReport = + buildDeskReports(evidenceFile, collectionsFile, pools, released, carriedWorks, originals, newToLibrary, catalogueComplete, nowMs, zone, decided, premiere, history, learning).getValue(mode) /** What Orbit Premiere's proposals are judged from: the catalogue's recent films, each film's Orbit status and this week's premiere decisions. */ internal class PremiereInputs(val films: List = emptyList(), val status: (String) -> OrbitStatus = { OrbitStatus.Never }, val decidedThisWeek: Int = 0) @@ -189,7 +209,9 @@ internal fun listMembers(file: File, names: Set): Set = if (!fil internal fun buildDeskReports(evidenceFile: File, collectionsFile: File, pools: Map>, released: List, carriedWorks: Set, originals: Map, newToLibrary: Int, catalogueComplete: Boolean, nowMs: Long, zone: ZoneId = ZoneId.systemDefault(), /** Titles you've placed or dropped on the Chair: never shown again, so the next ones take their place. */ - decided: Set = emptySet(), premiere: PremiereInputs = PremiereInputs()): Map { + decided: Set = emptySet(), premiere: PremiereInputs = PremiereInputs(), + /** Your decisions, for what the Chair has learned ([chairLessons]); [learning] is your switch for letting it change suggestions. */ + history: List = emptyList(), learning: Boolean = false): Map { val started = System.nanoTime() val evidence = if (evidenceFile.exists()) evidenceFile.readLines().mapNotNull { runCatching { JSONObject(it) }.getOrNull() } .associate { it.optString("id") to TitleEvidence.of(it, originals[it.optString("id")]) } else emptyMap() @@ -221,20 +243,30 @@ internal fun buildDeskReports(evidenceFile: File, collectionsFile: File, pools: val byChannel = strong.groupingBy { it.top.name }.eachCount().entries.sortedByDescending { it.value }.map { it.key to it.value } val premiered = released.associate { it.id to it.premiere } fun recent(id: String) = premiered[id]?.takeIf { it.length == 10 }?.let { runCatching { LocalDate.parse(it) }.getOrNull() }?.let { !it.isBefore(today.minusDays(14)) } == true - val undecided = placed.filter { it.evidence.id !in decided && it.evidence.id !in proposed } + val lessons = chairLessons(history, evidence) + // Learning on: titles like ones you keep dropping are held back, and a redirect you keep making becomes the suggestion. + val heldBack = if (learning) placed.filter { lessons.holdBackFor(it.top.number, it.evidence.genreSet) != null }.map { it.evidence.id }.toSet() else emptySet() + fun learned(p: Placement): ChairLesson? = if (learning) lessons.redirectFor(p.top.number, p.evidence.genreSet) else null + fun choicesFor(p: Placement): List { + val all = channelChoices(p, text, links) + val lesson = learned(p) ?: return all + val to = all.firstOrNull { it.number == lesson.to } ?: return all + return listOf(DeskOption(to.number, to.name, "learned from you: " + lesson.text())) + all.filter { it.number != to.number } + } + val undecided = placed.filter { it.evidence.id !in decided && it.evidence.id !in proposed && it.evidence.id !in heldBack } val asks = undecided.filter { it.tier == FitTier.NeedsEye }.sortedByDescending { it.s1 }.take(3).map { - DeskAsk(it.evidence.name, it.top.name, it.second.name, it.evidence.id, it.evidence.type, it.evidence.year, optionsOf(it, 2), it.evidence.overview?.let { o -> sentence(o) } ?: "No description in the library yet") } + DeskAsk(it.evidence.name, it.top.name, it.second.name, it.evidence.id, it.evidence.type, it.evidence.year, choicesFor(it), it.evidence.overview?.let { o -> sentence(o) } ?: "No description in the library yet") } val tookMs = (System.nanoTime() - started) / 1_000_000 return DirectorMode.values().associateWith { mode -> // Discoveries: the strongest strong matches, one per channel; Surprise Me reaches into the possibles for channels the strong list missed. val pool = undecided.filter { it.tier == FitTier.Strong }.sortedByDescending { it.s1 }.distinctBy { it.top.number }.toMutableList() if (mode == DirectorMode.Surprise) pool += undecided.filter { it.tier == FitTier.Possible && pool.none { p -> p.top.number == it.top.number } }.sortedByDescending { it.s1 }.take(2) val picks = pool.take(mode.picks).map { p -> - DeskPick(p.evidence.name, p.top.name, when { p.tier == FitTier.Possible -> "SOMETHING DIFFERENT"; recent(p.evidence.id) -> "JUST RELEASED"; else -> "STRONG MATCH" }, - p.evidence.overview?.let { sentence(it) } ?: "No description in the library yet", p.evidence.id, p.evidence.type, p.evidence.year, optionsOf(p)) + DeskPick(p.evidence.name, learned(p)?.to?.let { n -> Briefs.firstOrNull { it.number == n }?.name } ?: p.top.name, when { learned(p) != null -> "LEARNED FROM YOU"; p.tier == FitTier.Possible -> "SOMETHING DIFFERENT"; recent(p.evidence.id) -> "JUST RELEASED"; else -> "STRONG MATCH" }, + p.evidence.overview?.let { sentence(it) } ?: "No description in the library yet", p.evidence.id, p.evidence.type, p.evidence.year, choicesFor(p)) } DeskReport(candidates.size, newToLibrary, read.size, candidates.size - read.size, byChannel, strong.size, picks, asks, collections, catalogueComplete, franchises, nowMs, tookMs, placed.count { it.evidence.id in decided }, premieres, premiereQueued, - PremiereCalls.filter { it.premiere }.map { it.title }) + PremiereCalls.filter { it.premiere }.map { it.title }, lessons.summary(), lessons.lessons.map { it.text() }, learning) } } @@ -247,7 +279,8 @@ private val DirectorLock = Any() */ internal fun directorReports(store: ScheduleStore, catalogue: CatalogueStore, userId: String, nowMs: Long = System.currentTimeMillis()): Map? = synchronized(DirectorLock) { val evidence = store.evidenceFile(); val collections = store.collectionsFile(); val cache = store.directorFile(); val decisions = store.decisionsFile() - val key = listOf(evidence.lastModified(), collections.lastModified(), store.poolsStamp(), catalogue.summary().total ?: 0L, decisions.lastModified()).joinToString(":") + val key = listOf(evidence.lastModified(), collections.lastModified(), store.poolsStamp(), catalogue.summary().total ?: 0L, decisions.lastModified(), + store.learningFile().lastModified()).joinToString(":") runCatching { JSONObject(cache.readText()) }.getOrNull()?.takeIf { it.optString("key") == key && nowMs - it.optLong("savedMs") < 24 * 60 * 60_000L }?.let { saved -> val reports = saved.optJSONObject("reports") if (reports != null) return@synchronized DirectorMode.values().associateWith { DeskReport.of(reports.getJSONObject(it.name)) } @@ -259,7 +292,8 @@ internal fun directorReports(store: ScheduleStore, catalogue: CatalogueStore, us val (arrivals, _) = store.loadArrivals(userId) val newToLibrary = arrivals.count { nowMs - it.firstSeenMs < NEW_TO_LIBRARY_DAYS * 24 * 60 * 60_000L } val reports = buildDeskReports(evidence, collections, ids, released, carriedWorks, catalogue.originalTitles(released.map { it.id }), newToLibrary, catalogue.complete(), nowMs, - decided = loadDecisions(decisions).map { it.id }.toSet(), premiere = premiereInputs(store, catalogue, userId, nowMs)) + decided = loadDecisions(decisions).map { it.id }.toSet(), premiere = premiereInputs(store, catalogue, userId, nowMs), + history = loadDecisions(decisions), learning = ChairLearning.on(store.learningFile())) runCatching { cache.writeText(JSONObject().put("key", key).put("savedMs", nowMs).put("reports", JSONObject().apply { reports.forEach { (m, r) -> put(m.name, r.toJson()) } }).toString()) } val b = reports.getValue(DirectorMode.Balanced) android.util.Log.i("OrbitSchedule", "director newlyReleased=${b.newlyReleased} read=${b.scanned} strong=${b.strong} asks=${b.asks.size} collections=${b.collections} tookMs=${b.tookMs}") @@ -316,7 +350,9 @@ private val ChairSky = Color(0xFF78BEFF) internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequester, modifier: Modifier, place: (ChairChoice, DeskOption) -> Unit = { _, _ -> }, drop: (ChairChoice) -> Unit = {}, /** Premiere first, then [DeskOption] as its home; returns what to tell you (the debut, or why there's none). */ - premiere: suspend (ChairChoice, DeskOption) -> String = { _, _ -> "" }) { + premiere: suspend (ChairChoice, DeskOption) -> String = { _, _ -> "" }, + /** Your learning switch: saved, then the report is worked out again. */ + setLearning: suspend (Boolean) -> Unit = {}) { var mode by remember { mutableStateOf(DirectorMode.Balanced) } var version by remember { mutableIntStateOf(0) } var report by remember { mutableStateOf(null) } @@ -339,6 +375,13 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ } Spacer(Modifier.width(8.dp)) Text("Auto-approval: OFF", color = ChairMint, fontSize = 11.sp, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.width(8.dp)) + val learningOn = report?.learningOn == true + var learnFocused by remember { mutableStateOf(false) } + Text("Learning: " + if (learningOn) "ON" else "OFF", Modifier.onFocusChanged { learnFocused = it.isFocused } + .clickable { scope.launch { setLearning(!learningOn); said = if (learningOn) "Learning off: suggestions come from the channel briefs alone." else "Learning on: what it's learned from your decisions now shapes the suggestions."; version++ } } + .background(if (learningOn) ChairMint else ChairPanel, RoundedCornerShape(12.dp)).border(if (learnFocused) 2.dp else 0.dp, Color.White, RoundedCornerShape(12.dp)) + .padding(horizontal = 10.dp, vertical = 3.dp), color = if (learningOn) ChairNavy else Color.White, fontSize = 11.sp, fontWeight = FontWeight.SemiBold) } val r = report if (r == null) { Text("Working out this week's report. The first time takes a little while; after that the Chair opens straight away.", color = Muted, fontSize = 12.sp); return@Column } @@ -384,6 +427,11 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ Spacer(Modifier.height(4.dp)) Text("RULES IN FORCE", color = Color.White, fontFamily = Anton, fontSize = 13.sp) DirectorRules.forEach { Text("· $it", color = Muted, fontSize = 10.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) } + Spacer(Modifier.height(4.dp)) + Text("WHAT IT'S LEARNED", color = Color.White, fontFamily = Anton, fontSize = 13.sp) + Text(r.learnedSummary.ifEmpty { "No decisions yet." }, color = Muted, fontSize = 10.sp) + if (r.lessons.isEmpty()) Text("Nothing to change yet: a pattern needs two decisions that go the same way.", color = Muted, fontSize = 10.sp) + r.lessons.take(3).forEach { Text("· $it", color = if (r.learningOn) ChairMint else Muted, fontSize = 10.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) } } } Text(said ?: "Press a title to place it or drop it. A placed title joins that channel's list at its next top-up; nothing already booked changes. Worked out in ${r.tookMs} ms.", @@ -427,22 +475,28 @@ private fun ChairPopup(choice: ChairChoice, onPlace: (DeskOption) -> Unit, onDro if (PREMIERE_BOOKING_ACTIVE && home != null) OrbitButton("Premiere, then ${home.name.removePrefix("Orbit ")}", Modifier.focusRequester(firstButton), onClick = { onPremiere(home) }) else Text("Premiere booking switches on once you approve it", color = ChairGold, fontSize = 10.sp) } - // Asks show both channels from the start; a pick shows its suggestion, and the other fits on Change channel. + // A pick shows its suggestion, an ask the two channels it's torn between; every other channel is in the drop-down. // A Premiere proposal is view-only while booking is off: no placing, no dropping, nothing written. val viewOnly = choice.firstRun != null && !PREMIERE_BOOKING_ACTIVE - val shown = when { viewOnly -> emptyList(); choice.ask || others -> choice.options; else -> choice.options.take(1) } - shown.forEachIndexed { i, option -> - Row(Modifier.fillMaxWidth().background(ChairPanel, RoundedCornerShape(6.dp)).padding(10.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, + val lead = if (viewOnly) 0 else if (choice.ask) 2 else 1 + @Composable fun OptionRow(option: DeskOption, label: String, focusFirst: Boolean) = + Row(Modifier.fillMaxWidth().background(ChairPanel, RoundedCornerShape(6.dp)).padding(horizontal = 10.dp, vertical = 6.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { Column(Modifier.weight(1f)) { - Text(option.name.uppercase(java.util.Locale.UK) + if (i == 0 && !choice.ask) " · SUGGESTED" else "", color = ChairSky, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) + Text(option.name.uppercase(java.util.Locale.UK) + label, color = ChairSky, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) Text(option.reason, color = Muted, fontSize = 11.sp, maxLines = 2, overflow = TextOverflow.Ellipsis) } - OrbitButton("Place on ${option.name}", if (i == 0 && (choice.firstRun == null || !PREMIERE_BOOKING_ACTIVE)) Modifier.focusRequester(firstButton) else Modifier, onClick = { onPlace(option) }) + OrbitButton("Place on ${option.name}", if (focusFirst) Modifier.focusRequester(firstButton) else Modifier, onClick = { onPlace(option) }) } + choice.options.take(lead).forEachIndexed { i, option -> + OptionRow(option, if (i == 0 && !choice.ask) " · SUGGESTED" else "", i == 0 && (choice.firstRun == null || !PREMIERE_BOOKING_ACTIVE) && !others) + } + val rest = choice.options.drop(lead) + if (others && rest.isNotEmpty()) Column(Modifier.fillMaxWidth().heightIn(max = 220.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp)) { + rest.forEachIndexed { i, option -> OptionRow(option, "", i == 0) } } Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { - if (!viewOnly && !choice.ask && !others && choice.options.size > 1) OrbitButton("Change channel", onClick = { others = true }) + if (!viewOnly && rest.isNotEmpty()) OrbitButton(if (others) "Other channels ▴" else "Other channels ▾ (${rest.size})", onClick = { others = !others }) if (!viewOnly) OrbitButton("Drop", if (choice.options.isEmpty()) Modifier.focusRequester(firstButton) else Modifier, onClick = onDrop) OrbitButton(if (viewOnly) "Close" else "Not now", if (viewOnly) Modifier.focusRequester(firstButton) else Modifier, onClick = onClose) } diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index 4b6d96cc..5a3ed353 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -516,7 +516,15 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea }.onFailure { android.util.Log.w("OrbitSchedule", "director placeFailed=${it.javaClass.simpleName}") } } } }, drop = { choice -> scope.launch(Dispatchers.IO) { runCatching { dropFromChair(scheduleStore, choice.id, choice.title, choice.type, choice.options.firstOrNull()?.number, premiere = choice.firstRun != null) } .onFailure { android.util.Log.w("OrbitSchedule", "director dropFailed=${it.javaClass.simpleName}") }; android.util.Log.i("OrbitSchedule", "director dropped") } }, - premiere = { _, _ -> "Premiere booking is off until you approve it." }) }, isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) }, + premiere = { choice, home -> val active = session + if (active == null) "Not connected, so nothing was placed." else withContext(Dispatchers.IO) { runCatching { + placePremiereFromChair(scheduleStore, active.accountId, choice.id, choice.title, choice.year, home.number) + }.getOrNull() }.let { debut -> + android.util.Log.i("OrbitSchedule", "director premiere home=${home.number} debut=${debut != null}") + if (debut == null) "${choice.title} wasn't placed: it has been booked on Orbit already, or there was no free Friday or Saturday night in the next three weeks." + else "${choice.title} premieres on Orbit Premiere ${java.time.Instant.ofEpochMilli(debut).atZone(java.time.ZoneId.systemDefault()).let { "%s %d %s at %02d:%02d".format(it.dayOfWeek.getDisplayName(java.time.format.TextStyle.FULL, java.util.Locale.UK), it.dayOfMonth, it.month.getDisplayName(java.time.format.TextStyle.FULL, java.util.Locale.UK), it.hour, it.minute) }}, then joins ${home.name}." + } }, + setLearning = { on -> withContext(Dispatchers.IO) { ChairLearning.set(scheduleStore.learningFile(), on) }; android.util.Log.i("OrbitSchedule", "director learning=$on") }) }, isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) }, onSignOut = { job?.cancel(); closeSession(forget = true) }, windingDown = windingDown, onWindDown = { on -> val tots = scheduledChannels[TOTS_NUMBER] val active = session diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 98b8643b..b4d61ade 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -58,6 +58,8 @@ internal class ScheduleStore(private val directory: File) { fun decisionsFile() = File(directory, "director-decisions-0.json") /** Films on their premiere run ([PremiereRun]): debut, window and home. */ fun premiereRunsFile() = File(directory, "premiere-runs-0.json") + /** Your Director's Chair learning switch ([ChairLearning]). */ + fun learningFile() = File(directory, "director-learning-0.json") /** When the channels' pools last changed, without reading them: their files' times together. */ fun poolsStamp(): Long = directory.listFiles { f -> f.name.startsWith("episodes-") && f.name.endsWith(".json") }?.sumOf { it.lastModified() } ?: 0L diff --git a/android/app/src/test/java/tv/orbit/classic/ChairLearningTest.kt b/android/app/src/test/java/tv/orbit/classic/ChairLearningTest.kt new file mode 100644 index 00000000..f6b9644e --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ChairLearningTest.kt @@ -0,0 +1,45 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import java.io.File + +/** The Chair learning from your decisions: patterns of two or more, explained, used only while learning is on. */ +class ChairLearningTest { + private fun ev(id: String, title: String, genres: List) = TitleEvidence(id, "Movie", title, 2026, "A story.", genres, null, null, null, null) + private fun placed(id: String, title: String, channel: Int, suggested: Int) = ChairDecision(id, title, "Movie", true, channel, suggested, 1) + private fun dropped(id: String, title: String, suggested: Int) = ChairDecision(id, title, "Movie", false, null, suggested, 1) + + @Test fun twoMatchingDecisionsMakeALessonOneDoesNot() { + val evidence = mapOf("1" to ev("1", "Gore Night", listOf("Horror")), "2" to ev("2", "Splatter Party", listOf("Horror")), "3" to ev("3", "Wedding", listOf("Romance")), + "4" to ev("4", "Big Day", listOf("Romance")), "5" to ev("5", "Lone Shark", listOf("Horror"))) + val lessons = chairLessons(listOf(placed("1", "Gore Night", 305, 304), placed("2", "Splatter Party", 305, 304), dropped("3", "Wedding", 307), dropped("4", "Big Day", 307), + placed("5", "Lone Shark", 304, 304)), evidence) + assertEquals(5, lessons.decisions); assertEquals(1, lessons.agreed); assertEquals(2, lessons.changed); assertEquals(2, lessons.dropped) + assertEquals(305, lessons.redirectFor(304, setOf("Horror"))!!.to) + assertNotNull(lessons.holdBackFor(307, setOf("Romance"))) + assertNull(lessons.redirectFor(304, setOf("Comedy"))) + assertTrue(lessons.lessons.first { it.kind == ChairLesson.Kind.Redirect }.text().contains("Gore Night")) // explained by its own decisions + // One decision alone is no pattern. + assertTrue(chairLessons(listOf(placed("1", "Gore Night", 305, 304)), evidence).lessons.isEmpty()) + } + + @Test fun lessonsChangeSuggestionsOnlyWhileLearningIsOn() { + val horror = { id: String, name: String -> JSONObject().put("id", id).put("type", "Movie").put("name", name).put("year", 2026) + .put("overview", "A haunted house, a demon and a curse: terror for a family in the night.").put("genres", JSONArray(listOf("Horror"))).put("studios", JSONObject.NULL) + .put("rating", JSONObject.NULL).put("countries", JSONArray(listOf("United States"))).put("taglines", JSONObject.NULL) } + val evidence = File.createTempFile("evidence", ".jsonl").apply { deleteOnExit(); writeText(listOf(horror("1", "Gore Night"), horror("2", "Splatter Party"), horror("9", "The Haunting"), horror("10", "The Curse")).joinToString("") { "$it\n" }) } + val sets = File.createTempFile("collections", ".jsonl").apply { delete(); deleteOnExit() } + val history = listOf(placed("1", "Gore Night", 305, 304), placed("2", "Splatter Party", 305, 304)) + fun report(learning: Boolean) = buildDeskReport(evidence, sets, emptyMap(), listOf(Arrival("9", "Movie", "The Haunting", 2026, "2026-10-30", "tmdb:9", 0)), + emptySet(), emptyMap(), 1, true, DirectorMode.Balanced, 1_793_800_000_000, decided = setOf("1", "2"), history = history, learning = learning) + val off = report(false); val on = report(true) + assertEquals(1, off.lessons.size); assertFalse(off.learningOn) + val offFirst = (off.picks.map { it.options } + off.asks.map { it.options }).single().first() + val onFirst = (on.picks.map { it.options } + on.asks.map { it.options }).single().first() + assertEquals(304, offFirst.number) // off: the brief's own suggestion + assertEquals(305, onFirst.number); assertTrue(onFirst.reason.startsWith("learned from you")) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/DirectorChairTest.kt b/android/app/src/test/java/tv/orbit/classic/DirectorChairTest.kt index 3550acad..c6ba2c26 100644 --- a/android/app/src/test/java/tv/orbit/classic/DirectorChairTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/DirectorChairTest.kt @@ -105,7 +105,9 @@ class DirectorChairTest { val pick = before.picks.first() assertEquals(1, before.picks.size); assertEquals("Series", pick.type) // one pick per channel: both are Terra's assertEquals(201, pick.options.first().number) // the suggested channel first - assertTrue(pick.options.size <= 3); assertTrue(pick.options.none { it.number == 107 }) // never a channel the scoring ruled out (Evidence takes no documentaries) + // The drop-down offers the other channels too: a channel the scoring ruled out says why, and the wrong kind never appears. + assertTrue(pick.options.first { it.number == 107 }.reason.startsWith("outside its usual brief")) + assertTrue(pick.options.none { it.number == 303 || it.number == PREMIERE_NUMBER }) // a film channel for a series, and Premiere, never assertTrue(pick.options.first().reason.isNotBlank()) // Once decided, a title isn't shown again; the counts stay as they were. val after = buildDeskReport(ev, sets, pools, released, emptySet(), emptyMap(), 2, true, DirectorMode.Balanced, 1_793_800_000_000, decided = setOf(pick.id))