// A PERSON CORRECTS A FRAME READING, with no model (release 32, lane R3): the // video page's Frame scan panel opens the reading at a second, shows what the // model read beside what the derivation now uses, and saves the person's // values (or "misread") into the sidecar's `corrections` // (lib/frames/corrections.ts) — then works `derived` out again at once, as // `frame-scan {rederive: true}` does. Never while a scan of the video is // queued or running (it writes the same sidecar). // // Only what differs from the model's reading is stored, so a form may send // every field it shows; a save that differs in nothing (and is not a misread) // removes the correction. import path from "node:path"; import type { Paths } from "../lib/paths"; import { frameScanSidecar, type FrameScanRecord } from "../lib/frameScan-server"; import { isFrameProfile } from "../lib/frames/profiles"; import { rederiveRecord } from "../lib/frames/scan"; import { CorrectionInputError, checkCorrectionSet, correctableFields, correctedReading, readField, upsertCorrection, type CorrectableField, type CorrectionValue, type ReadingCorrection, } from "../lib/frames/corrections"; import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; import { frameScanBusy, loadCues, rederivedSummary, type FrameScanRederived } from "./frameScan"; type Reading = FrameScanRecord["readings"][number]; export type FrameReadingField = CorrectableField & { // What the model read (undefined: not shown), and what the derivation uses. read: CorrectionValue; value: CorrectionValue; corrected: boolean; }; export type FrameReadingView = { profile: string; t: number; // A duplicate frame: the read frame it copies. copyOf: number | null; correction: ReadingCorrection | null; misread: boolean; fields: FrameReadingField[]; // The grid seconds before and after, for stepping. prev: number | null; next: number | null; }; const norm = (v: unknown): CorrectionValue => (v === undefined || v === "" ? null : (v as CorrectionValue)); const same = (a: unknown, b: unknown) => JSON.stringify(norm(a)) === JSON.stringify(norm(b)); function gridOf(rec: FrameScanRecord): number[] { const ts = new Set(rec.readings.map((r) => r.t)); for (const [t] of rec.duplicates ?? []) ts.add(t); return [...ts].sort((a, b) => a - b); } // The model's reading at `t` (a duplicate's is its source's, at `t`). function modelReadingAt(rec: FrameScanRecord, t: number): { reading: Reading; copyOf: number | null } | null { const byT = new Map(rec.readings.map((r) => [r.t, r])); const own = byT.get(t); if (own) return { reading: own, copyOf: null }; const dup = (rec.duplicates ?? []).find(([d]) => d === t); const src = dup ? byT.get(dup[1]) : undefined; return src ? { reading: { ...src, t }, copyOf: dup![1] } : null; } function videoDirOf(paths: Paths, slug: string, id: string): string { return path.join(paths.channelsDir, slug, "data", id); } function checkRef(o: { slug: unknown; id: unknown; profile?: unknown }): { slug: string; id: string; profile: string } { if (typeof o.slug !== "string" || !isSafeChannelSegment(o.slug)) throw new CorrectionInputError(`"slug" must be a channel slug`); if (typeof o.id !== "string" || !isSafeIdSegment(o.id)) throw new CorrectionInputError(`"id" must be a video id`); const profile = o.profile ?? "poker"; if (!isFrameProfile(profile)) throw new CorrectionInputError(`"${String(profile)}" is not a frame-scan profile`); return { slug: o.slug, id: o.id, profile }; } function viewOf(rec: FrameScanRecord, t: number): FrameReadingView | null { const model = modelReadingAt(rec, t); if (!model) return null; // The derivation lays a correction made at a copy's second, or at its // source's, over the copy (deriveOf); the panel shows the same. const corrections = rec.corrections ?? []; const own = corrections.find((c) => c.t === t) ?? null; const fromSource = model.copyOf !== null ? (corrections.find((c) => c.t === model.copyOf) ?? null) : null; let effective: Reading | null = model.reading; if (fromSource) effective = effective && correctedReading(effective, fromSource); if (own) effective = effective && correctedReading(effective, own); const grid = gridOf(rec); const i = grid.indexOf(t); return { profile: rec.profile, t, copyOf: model.copyOf, correction: own, misread: effective === null, fields: correctableFields(rec.profile).map((f) => { const read = norm(readField(model.reading, f.path)); const value = effective ? norm(readField(effective, f.path)) : read; return { ...f, read, value, corrected: !same(read, value) }; }), prev: i > 0 ? grid[i - 1]! : null, next: i >= 0 && i < grid.length - 1 ? grid[i + 1]! : null, }; } /** The reading nearest `t` (a read frame or a duplicate), as the panel shows it. */ export async function frameReadingAt( paths: Paths, raw: { slug: unknown; id: unknown; profile?: unknown; t: unknown }, ): Promise<{ ok: true; view: FrameReadingView } | { ok: false; error: string }> { let ref; try { ref = checkRef(raw); } catch (e) { return { ok: false, error: (e as Error).message }; } const t = typeof raw.t === "number" ? raw.t : Number(raw.t); if (!Number.isFinite(t) || t < 0) return { ok: false, error: "give a time, in seconds or h:mm:ss" }; const sidecar = frameScanSidecar(ref.profile); const rec = await sidecar.load(videoDirOf(paths, ref.slug, ref.id)); if (!rec) return { ok: false, error: `${ref.slug}/${ref.id} has no ${sidecar.filename}` }; const grid = gridOf(rec); if (grid.length === 0) return { ok: false, error: "the scan holds no readings" }; const nearest = grid.reduce((best, x) => (Math.abs(x - t) < Math.abs(best - t) ? x : best), grid[0]!); return { ok: true, view: viewOf(rec, nearest)! }; } export type CorrectFrameReadingResult = | { ok: true; correction: ReadingCorrection | null; view: FrameReadingView; rederived: FrameScanRederived } | { ok: false; error: string }; /** * Save a person's correction of the reading at `t` and re-derive. * set field → value (every field a form shows may be sent; only the * ones that differ from the model's reading are kept) * misread the whole reading set aside * clear the correction at `t` removed */ export async function correctFrameReading( paths: Paths, raw: { slug: unknown; id: unknown; profile?: unknown; t: unknown; set?: unknown; misread?: unknown; clear?: unknown; note?: unknown }, o: { now?: () => Date } = {}, ): Promise { let ref; let set: Record | undefined; try { ref = checkRef(raw); set = checkCorrectionSet(ref.profile, raw.set); if (raw.misread !== undefined && typeof raw.misread !== "boolean") throw new CorrectionInputError(`"misread" is true or false`); if (raw.clear !== undefined && typeof raw.clear !== "boolean") throw new CorrectionInputError(`"clear" is true or false`); if (raw.note !== undefined && typeof raw.note !== "string") throw new CorrectionInputError(`"note" is text`); } catch (e) { return { ok: false, error: (e as Error).message }; } const t = typeof raw.t === "number" ? raw.t : NaN; if (!Number.isFinite(t)) return { ok: false, error: `"t" is the reading's second` }; if (frameScanBusy(ref.slug, ref.id)) { return { ok: false, error: `a frame scan of ${ref.slug}/${ref.id} is queued or running — correct it when the scan is done (it writes the sidecar)` }; } const videoDir = videoDirOf(paths, ref.slug, ref.id); const sidecar = frameScanSidecar(ref.profile); const rec = await sidecar.load(videoDir); if (!rec) return { ok: false, error: `${ref.slug}/${ref.id} has no ${sidecar.filename} — scan it first` }; const model = modelReadingAt(rec, t); if (!model) return { ok: false, error: `no frame was read at ${t} s` }; let correction: ReadingCorrection | null = null; if (raw.clear !== true) { const diff: Record = {}; for (const [p, v] of Object.entries(set ?? {})) if (!same(readField(model.reading, p), v)) diff[p] = v; const note = typeof raw.note === "string" ? raw.note.replace(/\s+/g, " ").trim().slice(0, 300) : ""; if (raw.misread === true || Object.keys(diff).length > 0) { correction = { t, at: (o.now ?? (() => new Date()))().toISOString(), by: "person", ...(raw.misread === true ? { misread: true as const } : {}), ...(Object.keys(diff).length ? { set: diff } : {}), ...(note ? { note } : {}), }; } } const corrections = upsertCorrection(rec.corrections, t, correction); const withCorrections: FrameScanRecord = { ...rec, corrections }; if (!corrections.length) delete withCorrections.corrections; const cues = await loadCues(videoDir); const out = rederiveRecord(withCorrections, { ...(cues ? { cues } : {}), ...(o.now ? { now: o.now } : {}) }); await sidecar.write(videoDir, out); return { ok: true, correction, view: viewOf(out, t)!, rederived: rederivedSummary(rec, out, sidecar.filename) }; }