Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 3fea701c80dbf8c8c35890ba4b9e971519bc6e68
parent ee840110e67c29ee010f75f94972136ef72d546d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 14:35:04 -0500

copies: date a re-upload by its stream day, search by runtime where a channel has no date, say when dates never meet

The scan dated every video by its channel's recorded-date rule, else its upload day, so a channel of
re-uploads never came within a day of the live recordings it copies and the scan answered 0 candidates.
A video is now dated by the channel's rule, else a live stream's own day, else (with no rule) a date read
from the title when one shape reads at least half the channel's non-live videos, else the upload day.
Videos of a channel with no rule that still have no date candidate are searched by runtime and words,
bounded (8 nearest runtimes, 2,000 pairs a scan); a group whose channels all have rules scans as before.
The scan's result carries `dating` and `advice`, with a warning when the members' dates never overlap.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/copies.test.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/copiesScan.ts | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Acommon/lib/copies/dating.test.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/copies/dating.ts | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/copies/file.ts | 21++++++++++++++++++++-
Mcommon/lib/copies/match.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/copies/match.ts | 126++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/CHANGELOG.md | 15+++++++++++++++
Mscripts/archilyzer-ops.mjs | 16+++++++++++++---
10 files changed, 726 insertions(+), 21 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -236,7 +236,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a claim repeating an earlier one, the same text over the same cited spans, is asked once; default: every claim is asked)} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | | `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` | | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/&lt;slug&gt;.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | -| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -&gt; {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their recorded dates are at most dateWindowDays apart. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/&lt;group&gt;.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals}. | | +| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -&gt; {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their dates are at most dateWindowDays apart. A video is dated by the best evidence it has: its channel's recordedDate rule, else a live stream's own day, else (no rule set) a date the channel's titles carry in a shape the scan recognises, else its upload day. On a channel with no rule, a video with only an upload day (on a re-upload channel, the copy's day) or none, and no candidate by date, is looked for by runtime instead: its 8 nearest agreeing runtimes on the other channels, at most 2,000 such pairs a scan, decided by their words only (no words, no pair). The result's advice says what the scan could not date well, with the exact channel-config patch that sets a channel's rule. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/&lt;group&gt;.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals, dating, advice?}. | | | `copies-release` | copies-release releases copies to their lanes: {"group", "video": "&lt;channel&gt;/&lt;dir&gt;" \| "videos": \[...\], "undo"?, "note"?, "by"?} -&gt; {group, action, undo, applied, unknown, skipped, now}. A released video is queued by its lanes as if it had no source group, whether it was held or skipped; undo takes the release back. A video may be named by its dir or its id (a Rumble video's differ); one the scan does not list is reported in unknown and not stored. by is "operator" or "agent" (the default), the caller's word, recorded with the time and the note in transcripts/copies/&lt;group&gt;.decisions.json, which the scan never touches. | | | `copies-confirm` | copies-confirm confirms metadata-only pairs as the same recording: {"group", "pair": "&lt;channel&gt;/&lt;dir&gt;\|&lt;channel&gt;/&lt;dir&gt;" \| "pairs": \[...\], "undo"?, "note"?, "by"?} -&gt; {group, action, undo, applied, unknown, skipped, now}. A confirmed pair acts as one confirmed by text: the copy is skipped once the other copy's work is done. Only a metadata-only pair takes it; a part-of or overlapping one is skipped with the reason. get copies lists the metadata pairs in their wait, with titles, dates and runtimes, for confirming in bulk. Recorded with who and when, as copies-release. | | | `copies-reject` | copies-reject rejects pairs: the same body as copies-confirm. A rejected pair never holds or skips again, whatever its link; undo takes it back, and a later confirm replaces it. | | diff --git a/common/controller/copies.test.ts b/common/controller/copies.test.ts @@ -103,21 +103,40 @@ function vtt(lines: number, text: (i: number) => string, asr = false): string { return out; } -function channel(p: Paths, slug: string): void { +function channel(p: Paths, slug: string, extra: Record<string, unknown> = {}): void { mkdirSync(path.join(p.channelsDir, slug, "data"), { recursive: true }); - writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe" })); + writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe", ...extra })); } function video( p: Paths, slug: string, dir: string, - o: { date: string; duration: number; cues?: ReturnType<typeof cues>; transcript?: boolean | number; audio?: boolean; id?: string }, + o: { + date: string; + duration: number; + cues?: ReturnType<typeof cues>; + transcript?: boolean | number; + audio?: boolean; + id?: string; + title?: string; + // A finished live stream (yt-dlp's live_status "was_live"). + live?: boolean; + }, ): void { const d = path.join(p.channelsDir, slug, "data", dir); mkdirSync(d, { recursive: true }); const id = o.id ?? dir; - writeFileSync(path.join(d, "metadata.info.json"), JSON.stringify({ id, title: `Stream ${id}`, duration: o.duration, upload_date: o.date })); + writeFileSync( + path.join(d, "metadata.info.json"), + JSON.stringify({ + id, + title: o.title ?? `Stream ${id}`, + duration: o.duration, + upload_date: o.date, + ...(o.live ? { live_status: "was_live", was_live: true } : {}), + }), + ); if (o.cues) writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id, cues: o.cues })); // A real-length transcript by default: 20 words a minute of runtime. if (o.transcript) writeFileSync(path.join(d, "transcript.json"), whisperJson(typeof o.transcript === "number" ? o.transcript : Math.ceil((o.duration / 60) * 20))); @@ -262,6 +281,90 @@ test("a cancelled scan stops between pairs and writes nothing", async () => { assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"], "no copies file"); }); +// A RE-UPLOAD channel and a LIVE mirror of the same streams (the shape of the +// first real scan's fault): the re-uploads went up months after the streams and +// carry the stream's day only in their titles; the mirror's videos are the live +// streams themselves, dated by their own day. No recordedDate rule is set. +function reuploads(p: Paths, prefConfig: Record<string, unknown> = {}): void { + channel(p, "pref-chan", prefConfig); + channel(p, "mirror-chan"); + video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "2023-04-05 the long stream", cues: cues(1) }); + video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "2023 04 08 another stream" }); + video(p, "pref-chan", "p3", { date: "20260312", duration: 3000, title: "2023 Apr 20 a short one" }); + video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, title: "[Copy] stream", cues: cues(1, 45), audio: true }); + video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, title: "[Copy] stream", cues: cues(2), audio: true }); +} + +test("a re-upload channel dated only in its titles is paired with the live copies (fails against upload-date dating)", async () => { + const p = corpus(); + reuploads(p); + const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true }); + const f = out.file; + assert.deepEqual( + f.pairs.map((x) => [x.key, x.link, x.a.dateFrom, x.b.dateFrom]), + [ + ["pref-chan/p1|mirror-chan/m1", "confirmed", "title", "live"], + ["pref-chan/p2|mirror-chan/m2", "metadata", "title", "live"], + ], + ); + assert.deepEqual(f.pairs[0].a.date, "20230405", "the stream's day, not the upload's"); + assert.equal(f.dating?.["pref-chan"].detectedPattern !== undefined, true); + assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 0, live: 0, title: 3, upload: 0, none: 0 }); + assert.deepEqual(f.dating?.["mirror-chan"].byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 }); + // The scan SAYS the channel lacks its rule, with the exact patch to set it. + const advice = (f.advice ?? []).join("\n"); + assert.match(advice, /pref-chan: 3 of 3 videos are dated by a date their titles carry/); + const patch = /pnpm ops channel-config --json '(.*?)'/.exec(advice)?.[1]; + assert.ok(patch, advice); + const body = JSON.parse(patch!); + assert.equal(body.slug, "pref-chan"); + assert.equal(new RegExp(body.patch.recordedDateTitlePattern, "i").test("2023-04-05 the long stream"), true); + assert.doesNotMatch(advice, /mirror-chan/, "a live channel is dated by its streams: nothing to set"); +}); + +test("the channel's own recordedDate rule dates its videos first, and no advice asks for one", async () => { + const p = corpus(); + reuploads(p, { recordedDate: { titlePattern: "^(?<year>\\d{4})[- ](?<month>\\d{2})[- ](?<day>\\d{2})" } }); + const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file; + assert.deepEqual( + f.pairs.map((x) => [x.key, x.link, x.a.dateFrom]), + [ + ["pref-chan/p1|mirror-chan/m1", "confirmed", "rule"], + ["pref-chan/p2|mirror-chan/m2", "metadata", "rule"], + ], + ); + // p3's "2023 Apr 20" is not the rule's shape: the rule is the operator's word, + // so the scan does not guess past it — p3 keeps its upload date. + assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 2, live: 0, title: 0, upload: 1, none: 0 }); + assert.equal(f.dating?.["pref-chan"].detectedPattern, undefined); + assert.doesNotMatch((f.advice ?? []).join("\n"), /recordedDateTitlePattern/); + // A ruled channel is never searched by runtime: the scan is main's. + assert.equal(f.totals.runtime, undefined); +}); + +test("with no date to go by, a copy is found by runtime and words, never held on runtime alone, and the search is bounded", async () => { + const p = corpus(); + channel(p, "pref-chan"); + channel(p, "mirror-chan"); + // Re-uploads whose titles carry no date: their upload day is the copy's. + video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "Stream highlights", cues: cues(1) }); + video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "Another stream" }); + video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, cues: cues(1, 45), audio: true }); + video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, cues: cues(2), audio: true }); + video(p, "mirror-chan", "m3", { date: "20230409", duration: 7190, live: true, cues: cues(3), audio: true }); + const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file; + assert.deepEqual( + f.pairs.map((x) => [x.key, x.link, x.evidence.via]), + [["pref-chan/p1|mirror-chan/m1", "confirmed", "runtime"]], + "p2 has no words: a runtime alone is no evidence, so no pair (and no hold)", + ); + assert.equal(f.totals.candidates, 0, "nothing was dated near anything"); + assert.deepEqual(f.totals.runtime, { searched: 1, candidates: 3, rejected: 2, capped: 0 }); + const advice = (f.advice ?? []).join("\n"); + assert.match(advice, /pref-chan: 2 of 2 videos have only an upload date/); + assert.match(advice, /no two members' videos are dated within 1 day/); +}); + async function lane(p: Paths, kind: "transcription" | "backfill" = "transcription") { resetCopiesLaneCacheForTest(); return computeLeafPending(kind, p, { state: emptyAutoQueueState() }); diff --git a/common/controller/copiesScan.ts b/common/controller/copiesScan.ts @@ -26,16 +26,18 @@ import { CUES_JSON_FILENAME } from "../lib/videoStatus"; import { isRealAudioFile } from "../lib/mediaFiles"; import { inspectChannelMedia } from "../lib/channelMedia"; import { isMediaHeld } from "../lib/channelMediaHold"; -import { contentDate } from "../lib/mirrors/match"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { readChannelConfig } from "./channels"; import { readChannelRecords } from "./mirrorScan"; import { classifyCandidate, copyCandidates, + COPY_RUNTIME_PER_VIDEO, cuesToWords, prepareCopyText, + runtimeCandidates, textEvidence, + wantsRuntimeSearch, type CopyRecord, type CopyText, type TextEvidence, @@ -55,6 +57,7 @@ import { } from "../lib/copies/file"; import { readCopiesDecisions, readCopiesFile, updateCopiesDecisions, writeCopiesFile } from "../lib/copies/file-server"; import { SOURCE_GROUP_ID_RE, type SourceGroup } from "../lib/copies/settings"; +import { dateChannel, datingAdvice, noCandidatesAdvice, type ChannelDating, type DatedChannel } from "../lib/copies/dating"; export const COPIES_SCAN_JOB_KIND = "copies-scan"; // One scan at a time, machine-wide: each reads thousands of cue files. @@ -117,7 +120,22 @@ export class CopiesScanCancelled extends Error { } function member(r: CopyRecord): CopyMember { - return { channel: r.channel, dir: r.dir, id: r.id, title: r.title, duration: r.duration, date: r.date }; + return { + channel: r.channel, + dir: r.dir, + id: r.id, + title: r.title, + duration: r.duration, + date: r.date, + ...(r.dateFrom !== undefined ? { dateFrom: r.dateFrom } : {}), + }; +} + +async function hasCuesFile(paths: Paths, r: CopyRecord): Promise<boolean> { + return stat(path.join(paths.channelsDir, r.channel, "data", r.dir, CUES_JSON_FILENAME)).then( + (s) => s.isFile() && s.size > 0, + () => false, + ); } export type CopiesScanOptions = { @@ -138,7 +156,7 @@ export type CopiesScanOutcome = { // The file's content without the per-run stamps, for "did anything change". function contentOf(f: CopiesFile): string { - return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals]); + return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals, f.dating ?? {}, f.advice ?? []]); } export async function runCopiesScan( @@ -169,27 +187,78 @@ export async function runCopiesScan( const missing: string[] = []; const records: CopyRecord[] = []; const videos: Record<string, number> = {}; + const datings = new Map<string, DatedChannel<{ title: string; uploadDate: string; recordedDate?: string; wasLive: boolean }>>(); let undated = 0; for (const slug of group.channels) { checkCancel(); - if (!(await readChannelConfig(paths, slug))) { + const config = await readChannelConfig(paths, slug); + if (!config) { missing.push(slug); continue; } const c = await readChannelRecords(paths, slug); videos[slug] = c.records.length; - for (const r of c.records) { - const date = contentDate(r); + // DATED BY THE BEST EVIDENCE EACH VIDEO HAS (lib/copies/dating.ts): the + // channel's rule, a live stream's own day, a date its titles carry, its upload. + const d = dateChannel(c.records, !!config.recordedDate); + datings.set(slug, d); + for (const { record: r, date, from } of d.dated) { if (!date) undated++; - records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date }); + records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date, dateFrom: from }); } - log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk)`); + const by = Object.entries(d.dating.byFrom) + .filter(([, n]) => n > 0) + .map(([k, n]) => `${n} by ${k === "none" ? "nothing (undated)" : k}`) + .join(", "); + log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk); dated ${by || "none"}`); } if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`); const candidates = copyCandidates(group, records); log(`${candidates.length} candidate pairs dated within ${group.dateWindowDays} day(s)`); + // THE RUNTIME SEARCH for videos whose date cannot pair them (only an upload + // day, or none) and that found no candidate by date: bounded, and decided by + // the words only (lib/copies/match.ts runtimeCandidates). + const pairedByDate = new Set<string>(); + for (const c of candidates) { + if (c.a.channel === c.b.channel) continue; + pairedByDate.add(`${c.a.channel}/${c.a.dir}`); + pairedByDate.add(`${c.b.channel}/${c.b.dir}`); + } + const ruled = new Set([...datings].filter(([, d]) => d.dating.ruleSet).map(([slug]) => slug)); + const textKnown = new Set<string>(); + if (wantsRuntimeSearch(records, ruled)) { + for (const r of records) { + await breathe(); + if (r.duration > 0 && (await hasCuesFile(paths, r))) textKnown.add(`${r.channel}/${r.dir}`); + } + } + const search = await runtimeCandidates(group, records, { + hasText: (r) => textKnown.has(`${r.channel}/${r.dir}`), + dated: pairedByDate, + ruled, + breathe, + }); + if (search.searched > 0 || search.capped > 0) { + log( + `${search.candidates.length} candidate pairs by runtime for ${search.searched} video(s) with no date to pair by` + + `${search.capped ? ` (${search.capped} more left unsearched: the scan's cap)` : ""}`, + ); + } + const runtimeSentence = + search.searched > 0 || search.capped > 0 + ? `Those with words were looked for by runtime instead (at most ${COPY_RUNTIME_PER_VIDEO} nearest each): ${search.searched} searched, ` + + `${search.candidates.length} compared${search.capped ? `, ${search.capped} left unsearched by the cap` : ""}.` + : null; + const advice: string[] = []; + for (const [slug, d] of datings) advice.push(...datingAdvice(slug, d, d.dating.byFrom.upload + d.dating.byFrom.none > 0 ? runtimeSentence : null)); + const crossDated = candidates.some((c) => c.a.channel !== c.b.channel); + if (!crossDated && datings.size >= 2 && records.length > 0) { + advice.push(noCandidatesAdvice(group.dateWindowDays, [...datings].map(([slug, d]) => ({ slug, span: d.dating.span })))); + } + for (const a of advice) log(`note: ${a}`); + // A small cache of words and their phrase index: candidates come grouped // by their `a` side, so each is built once per run of its candidates. const cache = new Map<string, CopyText | null>(); @@ -219,16 +288,22 @@ export async function runCopiesScan( overlaps: 0, rejected: 0, withinChannel: 0, + ...(search.searched > 0 || search.capped > 0 + ? { runtime: { searched: search.searched, candidates: search.candidates.length, rejected: 0, capped: search.capped } } + : {}), }; const pairs: CopyPairRecord[] = []; - for (const c of candidates) { + for (const c of [...candidates, ...search.candidates]) { await breathe(); const [wa, wb] = [await wordsOf(c.a), await wordsOf(c.b)]; const text: TextEvidence | null = wa && wb ? textEvidence(wa, wb) : null; const usable = text && text.verdict !== "no-text" ? text : null; const cls = classifyCandidate(c, usable); if (!cls) { - if (usable) totals.rejected++; + if (usable) { + if (c.via === "runtime") totals.runtime!.rejected++; + else totals.rejected++; + } continue; } const { link } = cls; @@ -246,6 +321,7 @@ export async function runCopiesScan( withinChannel, evidence: { kind: usable ? "text" : "metadata", + via: c.via ?? "date", dateDeltaDays: c.dateDeltaDays, durationOk: c.durationOk, ...(usable ? { text: usable } : {}), @@ -269,6 +345,8 @@ export async function runCopiesScan( }, pairs, totals, + dating: Object.fromEntries([...datings].map(([slug, d]) => [slug, d.dating])) as Record<string, ChannelDating>, + ...(advice.length > 0 ? { advice } : {}), }; log( `${totals.confirmed} confirmed by text and runtime, ${totals.metadata} metadata only, ${totals.partOf} part of ` + @@ -293,6 +371,8 @@ export function copiesScanSummary(out: CopiesScanOutcome, dryRun: boolean) { channels: f.channels, ...(f.missing ? { missing: f.missing } : {}), totals: f.totals, + ...(f.dating ? { dating: f.dating } : {}), + ...(f.advice ? { advice: f.advice } : {}), }; } @@ -544,6 +624,8 @@ export type CopiesGroupReport = { jobId?: string; totals: CopiesTotals; missing?: string[]; + // What the scan said about its own inputs (CopiesFile.advice). + advice?: string[]; }; // Cross-channel pairs by link (a metadata pair a person confirmed counts as // confirmed; a rejected pair counts nowhere but `rejected`); the pairs @@ -631,7 +713,7 @@ export async function copiesReport( key: p.key, a: p.a, b: p.b, - dateDeltaDays: p.evidence.dateDeltaDays, + dateDeltaDays: p.evidence.dateDeltaDays ?? 0, durationDifferenceSeconds: Math.round(Math.abs(p.a.duration - p.b.duration)), firstSeenAt: p.firstSeenAt, waitEnds: new Date(ends).toISOString(), @@ -676,6 +758,7 @@ export async function copiesReport( ...(file.jobId ? { jobId: file.jobId } : {}), totals: file.totals, ...(file.missing ? { missing: file.missing } : {}), + ...(file.advice ? { advice: file.advice } : {}), } : null, pairs, diff --git a/common/lib/copies/dating.test.ts b/common/lib/copies/dating.test.ts @@ -0,0 +1,93 @@ +// lib/copies/dating.ts: the date a copies scan pairs a video by. Every title, +// channel and date here is synthetic. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { recordedDatePatternProblem } from "../recordedDate"; +import { + dateChannel, + dateEvidence, + datingAdvice, + detectTitleDate, + noCandidatesAdvice, + recordedDatePatchCommand, + TITLE_DATE_SHAPES, + type DatingRecord, +} from "./dating"; + +const upload = (title: string, uploadDate = "20260310"): DatingRecord => ({ title, uploadDate, wasLive: false }); +const live = (title: string, uploadDate: string): DatingRecord => ({ title, uploadDate, wasLive: true }); + +test("every built-in title shape is a valid recordedDate rule, so the one detected can be proposed verbatim", () => { + for (const s of TITLE_DATE_SHAPES) assert.equal(recordedDatePatternProblem(s.pattern), null, s.id); +}); + +test("the order: the channel's rule, else a live stream's day, else a title date, else the upload", () => { + const re = new RegExp(TITLE_DATE_SHAPES[0].pattern, "i"); + assert.deepEqual(dateEvidence({ ...upload("2023-01-02 x"), recordedDate: "20230101" }, re), { date: "20230101", from: "rule" }); + assert.deepEqual(dateEvidence(live("2023-01-02 x", "20230103"), re), { date: "20230103", from: "live" }); + assert.deepEqual(dateEvidence(upload("2023-01-02 x"), re), { date: "20230102", from: "title" }); + assert.deepEqual(dateEvidence(upload("2023-01-02 x"), null), { date: "20260310", from: "upload" }); + // A title date after the upload is a date the title mentions, not the stream's. + assert.deepEqual(dateEvidence(upload("2027-01-02 preview"), re), { date: "20260310", from: "upload" }); + assert.equal(dateEvidence({ title: "x", uploadDate: "", wasLive: false }, re), null); +}); + +test("a re-upload channel's leading title dates are detected in their mixed spellings (fails against upload-date dating)", () => { + const d = dateChannel( + [upload("2023 01 04 a stream"), upload("2023-01-05 the stream"), upload("2023 Jan 06 more"), upload("2012 a stream part 2")], + false, + ); + assert.deepEqual( + d.dated.map((x) => [x.date, x.from]), + [ + ["20230104", "title"], + ["20230105", "title"], + ["20230106", "title"], + ["20260310", "upload"], + ], + ); + assert.equal(d.dating.detectedPattern, TITLE_DATE_SHAPES[0].pattern); + assert.deepEqual(d.dating.span, { from: "20230104", to: "20260310" }); + const advice = datingAdvice("pref-chan", d, null).join("\n"); + assert.match(advice, /pref-chan: 3 of 4 videos are dated by a date their titles carry/); + assert.ok(advice.includes(recordedDatePatchCommand("pref-chan", TITLE_DATE_SHAPES[0].pattern))); + assert.match(advice, /pref-chan: 1 of 4 videos have only an upload date/); +}); + +test("a mirror's tagged titles are detected; a live channel is dated by its streams whatever its titles say", () => { + const tagged = dateChannel([upload("[Copy] 2023-01-04"), upload("[Copy] 2023-01-05 Part 2/2"), upload("[Copy] 2023-01-07")], false); + assert.equal(tagged.dating.byFrom.title, 3); + const lives = dateChannel([live("[Copy] 2023-01-04", "20230105"), live("A stream", "20230106")], false); + assert.deepEqual(lives.dating.byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 }); + assert.equal(lives.dating.detectedPattern, undefined); + assert.deepEqual(datingAdvice("mirror-chan", lives, null), [], "nothing to set on a live channel"); +}); + +test("a shape that reads only a few titles does not stand for the channel; the advice names it with what it reads", () => { + const recs = [upload("Episode 1"), upload("Episode 2"), upload("Recap of 2023-01-04"), upload("Episode 3"), upload("Episode 4")]; + assert.equal(detectTitleDate(recs), null); + const d = dateChannel(recs, false); + assert.equal(d.dating.byFrom.upload, 5); + const advice = datingAdvice("pref-chan", d, "searched by runtime.").join("\n"); + assert.match(advice, /closest title shape reads 1 of 5/); + assert.match(advice, /searched by runtime\./); +}); + +test("with the channel's rule set, no shape is guessed past it", () => { + const d = dateChannel([{ ...upload("2023-01-04 x"), recordedDate: "20230104" }, upload("2023 Jan 05 y")], true); + assert.deepEqual(d.dating.byFrom, { rule: 1, live: 0, title: 0, upload: 1, none: 0 }); + assert.doesNotMatch(datingAdvice("pref-chan", d, null).join("\n"), /recordedDateTitlePattern/); +}); + +test("the patch command is one valid JSON body, and a scan with no dated pair names each member's span", () => { + const cmd = recordedDatePatchCommand("pref-chan", TITLE_DATE_SHAPES[0].pattern); + const body = JSON.parse(/--json '(.*)'$/.exec(cmd)![1]); + assert.deepEqual(body, { slug: "pref-chan", patch: { recordedDateTitlePattern: TITLE_DATE_SHAPES[0].pattern } }); + assert.equal( + noCandidatesAdvice(1, [ + { slug: "pref-chan", span: { from: "20260303", to: "20261118" } }, + { slug: "mirror-chan", span: { from: "20230104", to: "20260225" } }, + ]), + "no two members' videos are dated within 1 day(s) of each other (pref-chan 2026-03-03…2026-11-18; mirror-chan 2023-01-04…2026-02-25): check the dates above before reading 0 as \"no copies\".", + ); +}); diff --git a/common/lib/copies/dating.ts b/common/lib/copies/dating.ts @@ -0,0 +1,212 @@ +// THE DATE A COPIES SCAN PAIRS A VIDEO BY (lane copies-dates). Pure. +// +// The copies scan (controller/copiesScan.ts) pairs two members' videos when +// their dates are at most `dateWindowDays` apart, so the date it reads is the +// whole of its first stage. A video's `upload_date` is the day THAT COPY went +// up: right for a live stream (the video is the stream) and for a creator's +// own upload, wrong for a re-upload channel, whose copies go up weeks or years +// after the streams. The first real scan answered 0 candidates for exactly +// that: a re-upload channel dated by its uploads (all of them months after the +// last stream its live mirror held) against the mirror dated by its streams. +// +// THE ORDER, best evidence first; a video is dated by the first that gives one: +// rule the channel's `recordedDate.titlePattern` (lib/recordedDate.ts): +// the operator's word, as the index derived it or applied here. With +// a rule set nothing else is read off a title: a title the rule does +// not read is not guessed past it. +// live a finished live stream's own day: its `upload_date`, which yt-dlp +// sets from the stream (equal to the UTC day of `release_timestamp` +// on 822 of 832 live videos measured, a day apart on the rest — the +// date window absorbs it). +// title with NO rule set, a date the channel's titles carry in one of the +// shapes below, when that shape reads at least TITLE_DATE_MIN_SHARE +// of the channel's videos that are not live streams (and at least +// TITLE_DATE_MIN_VIDEOS of them). The one shape is applied to the +// whole channel, as a rule would be, and the same guards hold: a real +// day, no later than the upload. The scan then SAYS the rule is not +// set and gives the exact patch that sets it, so every other reader +// (coverage, the index) dates the channel the same way. +// upload anything else: a not-live video's upload day. On a re-upload +// channel that is the copy's day, so such a video is also looked for +// by runtime and words (lib/copies/match.ts, runtimeCandidates). +// +// A date only proposes candidates. What a pair IS stays the matcher's: words +// both ways and agreeing runtimes to confirm; a metadata-only pair (one side +// without words) is held for a bounded wait, never skipped. + +import { deriveRecordedDate, recordedDatePatternProblem } from "../recordedDate"; + +export type DateFrom = "rule" | "live" | "title" | "upload"; + +export const DATE_FROM_ORDER: readonly DateFrom[] = ["rule", "live", "title", "upload"]; + +// The title shapes the scan recognises without a rule. Each is a valid +// recordedDate.titlePattern (the dating test proves it), so the one detected +// is proposed to the operator verbatim. +export const TITLE_DATE_SHAPES: readonly { id: string; pattern: string }[] = [ + // "2023-01-04 …", "2023 01 04 …", "2023 Jan 04 …", "(2023.01.04) …" + { id: "leading", pattern: "^\\W{0,3}(?<year>\\d{4})[-\\s._/](?<month>\\d{1,2}|[a-z]{3,9})[-\\s._/](?<day>\\d{1,2})\\b" }, + // "[Mirror] 2023-01-04 …", "[VOD] 2023.01.04 …" + { id: "tagged", pattern: "^\\s*\\[[^\\]]{1,40}\\]\\s*(?<year>\\d{4})[-._/](?<month>\\d{1,2})[-._/](?<day>\\d{1,2})\\b" }, + // "… stream 2023-01-04 …" + { id: "iso", pattern: "\\b(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})\\b" }, + // "… January 4, 2023 …", "… Jan 4th 2023 …" + { id: "month-name", pattern: "\\b(?<month>[a-z]{3,9})\\.? (?<day>\\d{1,2})(?:st|nd|rd|th)?,? (?<year>\\d{4})\\b" }, +]; + +export const TITLE_DATE_MIN_SHARE = 0.5; +export const TITLE_DATE_MIN_VIDEOS = 3; + +export type DatingRecord = { + title: string; + // YYYYMMDD, or "" when unknown. + uploadDate: string; + // The channel rule's date (the index's, or applied by the reader). + recordedDate?: string; + wasLive: boolean; +}; + +export type DetectedTitleDate = { + pattern: string; + // Not-live videos the shape reads, of how many. + reads: number; + of: number; +}; + +const YMD = /^\d{8}$/; + +/** + * The title shape that dates most of a channel's not-live videos, when it + * reads enough of them to stand for the channel; with `best`, the best shape + * whatever it reads (for advice), null when none reads one. + */ +export function detectTitleDate( + records: readonly DatingRecord[], + opts: { best?: boolean } = {}, +): DetectedTitleDate | null { + const notLive = records.filter((r) => !r.wasLive); + if (notLive.length === 0) return null; + let top: DetectedTitleDate | null = null; + for (const shape of TITLE_DATE_SHAPES) { + if (recordedDatePatternProblem(shape.pattern)) continue; + const re = new RegExp(shape.pattern, "i"); + let reads = 0; + for (const r of notLive) if (deriveRecordedDate(re, r.title, r.uploadDate || undefined)) reads++; + if (reads > 0 && (!top || reads > top.reads)) top = { pattern: shape.pattern, reads, of: notLive.length }; + } + if (!top || opts.best) return top; + return top.reads >= TITLE_DATE_MIN_VIDEOS && top.reads >= TITLE_DATE_MIN_SHARE * top.of ? top : null; +} + +/** A video's date and where it came from, by the order above; null: undated. */ +export function dateEvidence( + r: DatingRecord, + detected: RegExp | null, +): { date: string; from: DateFrom } | null { + if (r.recordedDate && YMD.test(r.recordedDate)) return { date: r.recordedDate, from: "rule" }; + const upload = YMD.test(r.uploadDate) ? r.uploadDate : null; + if (r.wasLive && upload) return { date: upload, from: "live" }; + if (!r.wasLive && detected) { + const d = deriveRecordedDate(detected, r.title, upload ?? undefined); + if (d) return { date: d, from: "title" }; + } + return upload ? { date: upload, from: "upload" } : null; +} + +export type ChannelDating = { + videos: number; + byFrom: Record<DateFrom | "none", number>; + // The span of the dates the scan pairs by (YYYYMMDD), null: none dated. + span: { from: string; to: string } | null; + // Whether the channel's config sets a recordedDate rule. + ruleSet: boolean; + // The title shape the scan dated the channel by (no rule set). + detectedPattern?: string; +}; + +export type DatedChannel<T extends DatingRecord> = { + dating: ChannelDating; + dated: { record: T; date: string | null; from: DateFrom | null }[]; + // With no rule set and no shape detected: the best shape and what it reads, + // for the advice (null when no shape reads any title). + bestShape: DetectedTitleDate | null; +}; + +/** One channel's videos, each dated by the order above, with the tally. */ +export function dateChannel<T extends DatingRecord>(records: readonly T[], ruleSet: boolean): DatedChannel<T> { + const detected = ruleSet ? null : detectTitleDate(records); + const re = detected ? new RegExp(detected.pattern, "i") : null; + const byFrom: Record<DateFrom | "none", number> = { rule: 0, live: 0, title: 0, upload: 0, none: 0 }; + let from: string | null = null; + let to: string | null = null; + const dated = records.map((record) => { + const e = dateEvidence(record, re); + byFrom[e?.from ?? "none"]++; + if (e) { + if (!from || e.date < from) from = e.date; + if (!to || e.date > to) to = e.date; + } + return { record, date: e?.date ?? null, from: e?.from ?? null }; + }); + return { + dating: { + videos: records.length, + byFrom, + span: from && to ? { from, to } : null, + ruleSet, + ...(detected ? { detectedPattern: detected.pattern } : {}), + }, + dated, + bestShape: ruleSet || detected ? null : detectTitleDate(records, { best: true }), + }; +} + +/** The ops call that sets a channel's recorded-date rule to `pattern`. */ +export function recordedDatePatchCommand(slug: string, pattern: string): string { + return `pnpm ops channel-config --json '${JSON.stringify({ slug, patch: { recordedDateTitlePattern: pattern } })}'`; +} + +const ymdShow = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`; + +/** + * What the scan says about a channel's dates, as sentences: the rule it lacks + * (with the exact patch), the videos it could date only by their upload. + */ +export function datingAdvice(slug: string, d: DatedChannel<DatingRecord>, runtimeSearch: string | null): string[] { + const out: string[] = []; + const { dating } = d; + if (dating.detectedPattern) { + out.push( + `${slug}: ${dating.byFrom.title} of ${dating.videos} videos are dated by a date their titles carry; the channel ` + + `sets no recordedDate rule, so the scan read the shape itself. Set it, so the index and coverage date them the ` + + `same way: ${recordedDatePatchCommand(slug, dating.detectedPattern)}`, + ); + } + if (dating.byFrom.upload > 0) { + let s = + `${slug}: ${dating.byFrom.upload} of ${dating.videos} videos have only an upload date (not a live stream, no ` + + `date in the title${dating.ruleSet ? " the channel's rule reads" : ""}); on a channel of re-uploads that is the ` + + `day of the copy, not of the stream.`; + if (runtimeSearch) s += ` ${runtimeSearch}`; + // With a rule set, or one proposed above, that is the channel's shape: + // these titles simply carry none, and nothing more is proposed. + if (!dating.ruleSet && !dating.detectedPattern) { + s += d.bestShape + ? ` The closest title shape reads ${d.bestShape.reads} of ${d.bestShape.of}; if the titles carry the ` + + `stream's day, set a rule: ${recordedDatePatchCommand(slug, d.bestShape.pattern)}` + : ` If the titles carry the stream's day, set a rule: ${recordedDatePatchCommand(slug, "<regex with groups year, month, day>")}`; + } + out.push(s); + } + if (dating.byFrom.none > 0) out.push(`${slug}: ${dating.byFrom.none} of ${dating.videos} videos have no date at all.`); + return out; +} + +/** The sentence for a scan with no date candidate at all, naming each member's span. */ +export function noCandidatesAdvice( + windowDays: number, + spans: readonly { slug: string; span: ChannelDating["span"] }[], +): string { + const parts = spans.map((s) => `${s.slug} ${s.span ? `${ymdShow(s.span.from)}…${ymdShow(s.span.to)}` : "undated"}`); + return `no two members' videos are dated within ${windowDays} day(s) of each other (${parts.join("; ")}): check the dates above before reading 0 as "no copies".`; +} diff --git a/common/lib/copies/file.ts b/common/lib/copies/file.ts @@ -15,6 +15,7 @@ // the decisions only ever act on pairs the scan lists. import type { CopyLink, TextEvidence } from "./match"; +import type { ChannelDating, DateFrom } from "./dating"; export const COPIES_DIRNAME = "copies"; export const COPIES_FORMAT = "archilyzer-copies"; @@ -28,6 +29,9 @@ export type CopyMember = { title: string; duration: number; date: string | null; + // Where `date` came from: the channel's rule, the live stream's own day, a + // date the titles carry, or the upload (lib/copies/dating.ts). + dateFrom?: DateFrom | null; }; export type CopyPairRecord = { @@ -43,7 +47,11 @@ export type CopyPairRecord = { evidence: { // What decided the link: the words, or (no text on one side) metadata. kind: "text" | "metadata"; - dateDeltaDays: number; + // How the pair was proposed: dated within the window, or by runtime (one + // side had no date to go by; such a pair is always decided by its words). + via?: "date" | "runtime"; + // null: one side is undated. + dateDeltaDays: number | null; durationOk: boolean; text?: TextEvidence; }; @@ -65,6 +73,11 @@ export type CopiesTotals = { // Candidates the words said were different recordings. rejected: number; withinChannel: number; + // The runtime search (lib/copies/match.ts runtimeCandidates): videos + // searched, the candidates it proposed, those the words rejected, and the + // videos left unsearched by its cap. The date stage's figures above do not + // include them. + runtime?: { searched: number; candidates: number; rejected: number; capped: number }; }; export type CopiesFile = { @@ -84,6 +97,12 @@ export type CopiesFile = { }; pairs: CopyPairRecord[]; totals: CopiesTotals; + // How each member's videos were dated, by channel. + dating?: Record<string, ChannelDating>; + // What the scan says about its own inputs: a channel lacking its + // recorded-date rule (with the exact patch), videos it could date only by + // their upload, a scan whose members' dates never meet. + advice?: string[]; }; // Who gave a decision: the caller's word, as judge-trending takes it (the diff --git a/common/lib/copies/match.test.ts b/common/lib/copies/match.test.ts @@ -6,6 +6,7 @@ import { classifyCandidate, copyCandidates, cuesToWords, + runtimeCandidates, textEvidence, COPY_PHRASE_WORDS, type CopyRecord, @@ -205,3 +206,48 @@ test("the adjacent day's stream with the closer runtime is not linked over the t assert.deepEqual(classifyCandidate(nextDay, null), { link: "metadata" }); assert.equal(classifyCandidate(sameDay, null), null); }); + +test("the runtime search: only for a video its date cannot pair, both sides with words, nearest runtimes first, bounded", async () => { + const up = (channel: string, dir: string, duration: number): CopyRecord => ({ ...rec(channel, dir, "20260310", duration), dateFrom: "upload" }); + const lv = (dir: string, date: string, duration: number): CopyRecord => ({ ...rec("mirror-chan", dir, date, duration), dateFrom: "live" }); + const records = [ + up("pref-chan", "p1", 7200), + up("pref-chan", "p2", 7200), // no words + up("pref-chan", "p3", 7200), // already paired by date + up("pref-chan", "p4", 7205), // same channel: never its own candidate + lv("m1", "20230101", 7260), + lv("m2", "20230102", 7100), + lv("m3", "20230103", 7400), // runtimes apart + lv("m4", "20230104", 7210), + lv("m5", "20230105", 7190), + ]; + const noWords = new Set(["pref-chan/p2"]); + const hasText = (r: CopyRecord) => !noWords.has(`${r.channel}/${r.dir}`); + const dated = new Set(["pref-chan/p3"]); + const s = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3 }); + assert.deepEqual( + s.candidates.map((c) => [c.a.dir, c.b.dir, c.via, c.durationOk]), + [ + ["p1", "m5", "runtime", true], + ["p1", "m4", "runtime", true], + ["p1", "m1", "runtime", true], + ["p4", "m4", "runtime", true], + ["p4", "m5", "runtime", true], + ["p4", "m1", "runtime", true], + ], + "nearest three each; never p2 (no words), p3 (paired by date), m3 (runtimes apart) or p1 with p4", + ); + assert.equal(s.searched, 2, "p1 and p4; a live mirror's own day pairs it, so it is never searched from"); + // The scan's cap: once reached, the rest are counted, not searched. + const capped = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, maxPairs: 2 }); + assert.equal(capped.candidates.length, 2); + assert.deepEqual([capped.searched, capped.capped], [1, 1]); + // A channel with a recordedDate rule is dated by it and never searched from. + const ruled = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, ruled: new Set(["pref-chan"]) }); + assert.deepEqual([ruled.candidates.length, ruled.searched, ruled.capped], [0, 0, 0]); + // A runtime candidate has nothing but its runtime: without words, no pair at all. + assert.equal(classifyCandidate(s.candidates[0], null), null); + assert.deepEqual(classifyCandidate(s.candidates[0], textEvidence(stream(5, 3000), shift(stream(5, 3000), 30))), { + link: "confirmed", + }); +}); diff --git a/common/lib/copies/match.ts b/common/lib/copies/match.ts @@ -37,6 +37,7 @@ // reads a time across copies. import type { SourceGroup } from "./settings"; +import type { DateFrom } from "./dating"; export const COPY_PHRASE_WORDS = 6; export const COPY_PROBES = 40; @@ -66,6 +67,8 @@ export type CopyRecord = { duration: number; // YYYYMMDD, or null when undated. date: string | null; + // Where `date` came from (lib/copies/dating.ts); absent: not said. + dateFrom?: DateFrom | null; }; export type Word = { w: string; t: number }; @@ -112,8 +115,13 @@ export type CopyLink = "confirmed" | "metadata" | "part-of" | "overlaps"; export type CopyCandidate = { a: CopyRecord; b: CopyRecord; - dateDeltaDays: number; + // Days between the two dates; null when one side is undated (a runtime + // candidate). + dateDeltaDays: number | null; durationOk: boolean; + // How it was proposed: dated within the window (the default), or — one side + // dated only by its upload — by runtime, for the words to decide. + via?: "date" | "runtime"; }; export type CopyClassification = { link: CopyLink; part?: "a" | "b" } | null; @@ -315,6 +323,7 @@ export function copyCandidates( b, dateDeltaDays: Math.abs(dd), durationOk: runtimesAgree(a.duration, b.duration, group), + via: "date", }); } } @@ -322,6 +331,119 @@ export function copyCandidates( return out.sort((x, y) => order(x.a, y.a) || order(x.b, y.b)); } +// THE RUNTIME SEARCH, for a video of a channel with NO recordedDate rule whose +// date says nothing about its stream (lib/copies/dating.ts: only an upload +// date, or none) and which found no candidate by date (a channel with a rule +// is dated by the operator's word, and is never searched from, as before): the other members' videos whose runtimes agree, nearest +// first, at most COPY_RUNTIME_PER_VIDEO of them, and at most +// COPY_RUNTIME_MAX_PAIRS such pairs in one scan. Both sides must have words: +// a runtime alone is no evidence of anything, so a runtime candidate is +// decided by its words or dropped (classifyCandidate), never held. The bound: +// at most min(8 × such videos, 2,000) text comparisons per scan, each about +// 0.15 s of one core measured on 4-hour streams — five minutes at worst. +export const COPY_RUNTIME_PER_VIDEO = 8; +export const COPY_RUNTIME_MAX_PAIRS = 2000; + +export type RuntimeSearch = { + candidates: CopyCandidate[]; + // Videos searched (undated or upload-dated, with words and a runtime, no date candidate). + searched: number; + // Such videos left unsearched once the scan's cap was reached. + capped: number; +}; + +const needsRuntimeSearch = (r: CopyRecord, ruled: ReadonlySet<string>) => + (!r.date || r.dateFrom === "upload") && !ruled.has(r.channel); + +/** Whether any record would be searched by runtime (the scan reads no cue file otherwise). */ +export function wantsRuntimeSearch(records: readonly CopyRecord[], ruled: ReadonlySet<string>): boolean { + return records.some((r) => needsRuntimeSearch(r, ruled)); +} + +/** + * Runtime candidates for the videos whose date cannot pair them (above). + * `hasText` says which videos have words; `dated` holds the keys + * (`<channel>/<dir>`) of videos that already have a date candidate; `ruled` + * the channels with a recordedDate rule (never searched from); `breathe` is + * awaited before each searched video (the scan yields to the event loop there). + * Deterministic: by the searched video's rank and dir, then runtime distance. + */ +export async function runtimeCandidates( + group: Pick<SourceGroup, "channels" | "durationToleranceSeconds" | "durationToleranceRatio">, + records: readonly CopyRecord[], + opts: { + hasText: (r: CopyRecord) => boolean; + dated: ReadonlySet<string>; + ruled?: ReadonlySet<string>; + perVideo?: number; + maxPairs?: number; + breathe?: () => Promise<void>; + }, +): Promise<RuntimeSearch> { + const ruled = opts.ruled ?? new Set<string>(); + const perVideo = opts.perVideo ?? COPY_RUNTIME_PER_VIDEO; + const maxPairs = opts.maxPairs ?? COPY_RUNTIME_MAX_PAIRS; + const rank = new Map(group.channels.map((c, i) => [c, i])); + const order = (x: CopyRecord, y: CopyRecord) => + rank.get(x.channel)! - rank.get(y.channel)! || (x.dir < y.dir ? -1 : x.dir > y.dir ? 1 : 0); + const keyOf = (r: CopyRecord) => `${r.channel}/${r.dir}`; + const pool = records + .filter((r) => rank.has(r.channel) && r.duration > 0 && opts.hasText(r)) + .sort((x, y) => x.duration - y.duration || order(x, y)); + const wanted = pool.filter((r) => needsRuntimeSearch(r, ruled) && !opts.dated.has(keyOf(r))).sort(order); + const seen = new Set<string>(); + const out: CopyCandidate[] = []; + let searched = 0; + let capped = 0; + for (const r of wanted) { + if (out.length >= maxPairs) { + capped++; + continue; + } + await opts.breathe?.(); + searched++; + // The pool is sorted by runtime: walk out from r's place both ways. + let lo = 0; + let hi = pool.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (pool[mid].duration < r.duration) lo = mid + 1; + else hi = mid; + } + const near: CopyRecord[] = []; + let i = lo - 1; + let j = lo; + const ok = (o: CopyRecord) => o.channel !== r.channel && runtimesAgree(r.duration, o.duration, group); + while (near.length < perVideo && (i >= 0 || j < pool.length)) { + const left = i >= 0 ? pool[i] : null; + const right = j < pool.length ? pool[j] : null; + const inLeft = left !== null && runtimesAgree(r.duration, left.duration, group); + const inRight = right !== null && runtimesAgree(r.duration, right.duration, group); + if (!inLeft && !inRight) break; + const takeLeft = inLeft && (!inRight || r.duration - left!.duration <= right!.duration - r.duration); + const o = takeLeft ? left! : right!; + if (takeLeft) i--; + else j++; + if (ok(o)) near.push(o); + } + for (const o of near) { + if (out.length >= maxPairs) break; + const [a, b] = order(r, o) <= 0 ? [r, o] : [o, r]; + const key = `${keyOf(a)}\u0000${keyOf(b)}`; + if (seen.has(key)) continue; + seen.add(key); + out.push({ + a, + b, + dateDeltaDays: a.date && b.date ? Math.abs(dayNumber(a.date) - dayNumber(b.date)) : null, + durationOk: true, + via: "runtime", + }); + } + } + return { candidates: out, searched, capped }; +} + /** * What a candidate is, given its text evidence (null = one side has no text). * With words on both sides they decide, and CONFIRMED needs the runtimes to @@ -346,5 +468,7 @@ export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null): return null; } } + // A runtime candidate has nothing but its runtime: no words, no pair. + if (c.via === "runtime") return null; return c.durationOk ? { link: "metadata" } : null; } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,21 @@ # Changelog ## [Unreleased] +- **The copies scan dates a re-upload by the stream's day, not the upload's, and says what it could not date.** + - Before, it dated every video by its channel's `recordedDate` rule, else its upload day. A re-upload channel with + no rule was dated by its uploads, months after the streams its live mirror held, and the scan answered "0 + candidate pairs" with nothing to say why. + - Now each video is dated by the best evidence it has: the channel's rule, else a live stream's own day, else (no + rule set) a date the channel's titles carry in a shape the scan recognises (it must read at least half the + channel's videos that are not live streams), else the upload day. Each pair's members record where their date came from. + - The runtime search: on a channel with NO `recordedDate` rule, a video with only an upload day, or none, that + finds no candidate by date is compared, by its words, with the videos of the other channels whose runtimes agree + (its 8 nearest, at most 2,000 such pairs a scan). Such a pair is decided by its words only; without words on both + sides it is no pair, never a hold. A channel with a rule is never searched from, so a group whose channels all + have rules is scanned exactly as before. + - The scan's result and log carry `advice`: a channel dated from its titles with no rule set, with the exact + `pnpm ops channel-config` patch that sets one; videos dated only by their upload; and, when no two members' + videos are dated near each other, each member's dated span. `dating` gives each channel's count by source. - **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.** - Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a 3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -3304,8 +3304,18 @@ export function usage() { 'copies-scan pairs a source group\'s channels video by video: {"group",', ' "dryRun"?} -> {jobId}. The group is settings.sourceGroups\' (an ordered', " list of channels holding the same recordings, the preferred source first;", - " pnpm ops settings sets it). Two videos are candidates when their recorded", - " dates are at most dateWindowDays apart. Where both have a cue file their", + " pnpm ops settings sets it). Two videos are candidates when their dates", + " are at most dateWindowDays apart. A video is dated by the best evidence", + " it has: its channel's recordedDate rule, else a live stream's own day,", + " else (no rule set) a date the channel's titles carry in a shape the scan", + " recognises, else its upload day. On a channel with no rule, a video with", + " only an upload day (on a re-upload channel, the copy's day) or none, and", + " no candidate by date, is looked for by runtime instead: its 8 nearest", + " agreeing runtimes on the other channels, at most 2,000 such pairs a", + " scan, decided by their words", + " only (no words, no pair). The result's advice says what the scan could", + " not date well, with the exact channel-config patch that sets a", + " channel's rule. Where both have a cue file their", " words decide, probed both ways (40 phrases each way, each counted once):", " each copy holding at least 75 % of the other AND runtimes within the", " group's tolerance is confirmed; one inside the other, or the words the", @@ -3321,7 +3331,7 @@ export function usage() { " reported only (get copies says each one's reason). Cancelling the job", " stops it with nothing written; dryRun writes nothing. The log ends with", " @@copies-scan {group, dryRun, unchanged, file?, channels, missing?,", - " totals}.", + " totals, dating, advice?}.", "", 'copies-release releases copies to their lanes: {"group", "video":', ' "<channel>/<dir>" | "videos": [...], "undo"?, "note"?, "by"?} ->',