mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
053d780f31 | ||
|
|
dcfaaba739 | ||
|
|
118b58f4de | ||
|
|
ec691c7e8d | ||
|
|
7f8937d357 | ||
|
|
15be70a394 |
No files matched your search
@@ -120,6 +120,9 @@ image = (
|
||||
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063 /opt/yolox_s.onnx "
|
||||
"03f550c6b406fda8bf54bd8327815f6c7e2edd98cea02348c93d879254366587 /opt/ppocr_det.onnx | sha256sum -c"
|
||||
)
|
||||
# /v1/scene's texts (11-30): RapidOCR's PP-OCRv4 reads each line of text in a frame, for raea goal check's captions
|
||||
# pack (what an export shows, held to what it says). Apache-2.0; its ONNX models ship in the wheel
|
||||
.pip_install("rapidocr_onnxruntime==1.4.4")
|
||||
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
|
||||
# RAEA_GOAL_RENDER 0: a render here ends without raea goal check's render moment, which the box that sent it runs
|
||||
# on the export it gets back (server/offload.ts), beside the project's brief.ts
|
||||
@@ -485,7 +488,8 @@ def api():
|
||||
"""what's in a video's frames, for raea goal check's frames and place packs and `raea make place` (farm_scene.py): the body is
|
||||
{"frames": [base64 JPEG, ...]} (at most 400), the answer each frame's size, its faces and split-screen seams
|
||||
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things
|
||||
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], in that frame's pixels"""
|
||||
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
|
||||
[x, y, w, h, "the text", score], in that frame's pixels"""
|
||||
import base64
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -510,7 +514,7 @@ def api():
|
||||
r = SCENE.read(im)
|
||||
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
|
||||
out.append(r)
|
||||
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar", "frames": out}
|
||||
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
|
||||
|
||||
@web.post("/v1/words")
|
||||
async def words(req: Request):
|
||||
|
||||
@@ -8,6 +8,7 @@ Four small ONNX models from OpenCV's zoo, on the CPU through cv2.dnn, each pinne
|
||||
YOLOX-S (2022nov, Apache-2.0): COCO's 80 things, as boxes, at 640x640
|
||||
PP-OCRv3 DB (2023may, Apache-2.0): words in the shot (a sign someone holds, a shop's name), as boxes labelled "text"
|
||||
YuNet (2023mar, MIT): faces, as boxes (the frames pack's)
|
||||
And RapidOCR's PP-OCRv4 (1.4.4, Apache-2.0), which reads each line of text, for the captions pack.
|
||||
|
||||
A frame's answer: its size, a grid of how much of each cell is a person (0-9, a cell ~1/27 of the shorter side), the
|
||||
faces and the things as [x, y, w, h, label, score] in the frame's pixels."""
|
||||
@@ -48,6 +49,7 @@ class Scene:
|
||||
self.words_model.setPolygonThreshold(0.5)
|
||||
self.words_model.setMaxCandidates(200)
|
||||
self.words_model.setUnclipRatio(2.0)
|
||||
self.ocr = None
|
||||
self.face_path = face
|
||||
self.face, self.face_size = None, None
|
||||
|
||||
@@ -121,10 +123,31 @@ class Scene:
|
||||
_, found = self.face.detect(im)
|
||||
return [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), "face", round(float(f[14]), 3)] for f in (found if found is not None else [])]
|
||||
|
||||
def read(self, im):
|
||||
def texts(self, im, least=0.5):
|
||||
"""each line of text in the frame, read, as [x, y, w, h, "the text", score] (11-30, the captions pack: what an
|
||||
export shows, held to what it says). RapidOCR's PP-OCRv4 (Apache-2.0, its ONNX models in the wheel), on the
|
||||
CPU; it reads 540-wide frames' captions word for word in about 0.13 s a frame, where OpenCV's zoo CRNN dropped
|
||||
spaces and misread them. Loaded on first use"""
|
||||
if self.ocr is None:
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
|
||||
self.ocr = RapidOCR()
|
||||
found, _ = self.ocr(im, use_cls=False)
|
||||
out = []
|
||||
for box, text, score in found or []:
|
||||
if float(score) < least:
|
||||
continue
|
||||
xs, ys = [p[0] for p in box], [p[1] for p in box]
|
||||
out.append([round(float(min(xs)), 1), round(float(min(ys)), 1), round(float(max(xs) - min(xs)), 1), round(float(max(ys) - min(ys)), 1), str(text), round(float(score), 3)])
|
||||
return out
|
||||
|
||||
def read(self, im, texts=True):
|
||||
h, w = im.shape[:2]
|
||||
p = self.people(im)
|
||||
return {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
|
||||
out = {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
|
||||
if texts:
|
||||
out["texts"] = self.texts(im)
|
||||
return out
|
||||
|
||||
|
||||
def grid(p, w, h):
|
||||
|
||||
@@ -27,6 +27,11 @@ export interface Workflow {
|
||||
/** raea's packs by name (packs/index.ts): what each holds a job to */
|
||||
export const PACKS = {
|
||||
words: "every word a cut's lines say is heard whole in its export, none faded under a crossfade",
|
||||
captions: "every caption on screen says exactly what's heard there: nothing added or changed, no words dropped from a captioned line",
|
||||
voice: "the dialogue on top of the mix (10 dB over what's under it) and every line as loud as the others, measured on the export",
|
||||
hook: "the hook opens on words and picture together: no dead air before the first word",
|
||||
airgaps: "no air between words: gaps tightened in the hook's first 3 s, no long pause after (tighten() cuts between words only)",
|
||||
reading: "every block of text that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture",
|
||||
sound: "edit points in the pauses, every line within 6 dB of the others, every effect heard",
|
||||
frames: "no face cut by the frame or a split screen's seam, no text too small to read",
|
||||
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
|
||||
@@ -55,13 +60,13 @@ export type PackName = keyof typeof PACKS
|
||||
|
||||
/** each kind's packs, on unless the brief switches them off (surprise is on only where a brief turns it on) */
|
||||
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
|
||||
cut: ["words", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
|
||||
cut: ["words", "captions", "voice", "reading", "hook", "airgaps", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
|
||||
rules: ["deliverables", "stills"],
|
||||
scene: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
kit: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
shot: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
// a project with no `goal`: what any made video is held to, and any composition as it's saved
|
||||
floor: ["frames", "floor", "seen", "stills"],
|
||||
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
|
||||
}
|
||||
|
||||
/** a `says` rule: what a fresh critic must find true of the work (`raea goal judge`) */
|
||||
|
||||
@@ -234,7 +234,8 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
|
||||
}
|
||||
const fs = (g.faces as any[][]) ?? []
|
||||
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs } as Scene)
|
||||
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
|
||||
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
|
||||
}
|
||||
}
|
||||
return { rate: at?.length ? 0 : RATE, faces, scenes }
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
// The captions pack (11-30, Shane: "running a transcription and ocr pass on the final output as fast as possible would
|
||||
// be helpful because it also helps catch if audio captions pick up something else that's not supposed to be there or if
|
||||
// we cut off words"): what an export SHOWS against what it SAYS, both read off the export itself, so it can't be passed
|
||||
// by what the edit meant to show. Elfster's captions, typed by hand, said "for a bad gift" (said: "when they get a bad
|
||||
// gift"), "Oh my god" (said: "Oh my"), dropped half a line and two words of the brief's own call to action; every
|
||||
// check passed them, since none read the picture.
|
||||
//
|
||||
// read: the scene reader (raea cloud's farm, POST /v1/scene) reads the text in each frame, two a second (PP-OCRv4).
|
||||
// heard: the words pass's transcript of the same export.
|
||||
// captions: a line of text whose letters mostly match what's said around it (within 2.5 s before to 1 s after) is a
|
||||
// caption; hook text, a title, a logo or a sign isn't, and is left alone.
|
||||
// shown, not said: a run of three letters or more in the captions that nothing heard near it accounts for is an
|
||||
// error (a word added or changed: "god").
|
||||
// said, not shown: while captions are up, a heard word the captions leave out is a warning, two or more in a row an
|
||||
// error (words dropped: "when they get"). Fillers (um, uh) aren't counted.
|
||||
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import type { TextLine } from "./place.ts"
|
||||
|
||||
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
|
||||
export type Read = TextLine
|
||||
export type Finding = { level: "error" | "warn" | "note"; kind: "shown" | "dropped" | "none"; at: number; says: string }
|
||||
|
||||
/** a word or a line as it's compared: lower case letters and digits, nothing else */
|
||||
export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
|
||||
/** what's said that a caption may leave out without changing what's said */
|
||||
const FILLER = new Set(["um", "uh", "uhh", "umm", "mm", "mhm", "hmm", "er", "erm", "ah"])
|
||||
/** a line is a caption when this share of its letters is matched by what's said around it */
|
||||
export const CAPTION = 0.6
|
||||
/** the time around a caption that what it says may be heard: before it shows, after */
|
||||
const BEFORE = 2.5
|
||||
const AFTER = 1.0
|
||||
/** least score a read line counts at */
|
||||
export const LEAST = 0.6
|
||||
|
||||
/** a caption against what's said around it: the caption's letters aligned to the stretch of the heard letters they fit
|
||||
* best (an edit distance with the heard text's start and end free). dist: the edits; bad: for each caption letter,
|
||||
* whether it was changed or added (no heard letter matches it) */
|
||||
export function fit(cap: string, said: string): { dist: number; bad: boolean[]; from: number; to: number } {
|
||||
const n = cap.length
|
||||
const m = said.length
|
||||
// D[i][j]: edits to make cap[0..i) end at said[j); a free start anywhere in said
|
||||
const D = Array.from({ length: n + 1 }, (_, i) => new Uint16Array(m + 1).fill(i))
|
||||
for (let i = 1; i <= n; i++)
|
||||
for (let j = 1; j <= m; j++) D[i][j] = Math.min(D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1), D[i - 1][j] + 1, D[i][j - 1] + 1)
|
||||
let j = 0
|
||||
for (let k = 1; k <= m; k++) if (D[n][k] < D[n][j]) j = k
|
||||
const dist = D[n][j]
|
||||
const to = j
|
||||
const bad = new Array<boolean>(n).fill(false)
|
||||
let i = n
|
||||
while (i > 0 && j > 0) {
|
||||
const d = D[i][j]
|
||||
if (d === D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1)) {
|
||||
if (cap[i - 1] !== said[j - 1]) bad[i - 1] = true
|
||||
i--
|
||||
j--
|
||||
} else if (d === D[i - 1][j] + 1) bad[--i] = true
|
||||
else j--
|
||||
}
|
||||
while (i > 0) bad[--i] = true
|
||||
return { dist, bad, from: j, to }
|
||||
}
|
||||
|
||||
/** the heard words whose time falls in [a, b] */
|
||||
const heardIn = (heard: Word[], a: number, b: number) => heard.filter((w) => w.end >= a && w.start <= b)
|
||||
const saidAround = (heard: Word[], a: number, b: number) => heardIn(heard, a - BEFORE, b + AFTER).map((w) => letters(w.text)).join("")
|
||||
|
||||
/** a caption's showings: one line of text, from its first frame to its last (the same line in frames side by side), and
|
||||
* how far down the frame its middle is (a share of the frame's height) */
|
||||
export type Shown = { text: string; key: string; from: number; to: number; y: number }
|
||||
/** a frame's lines, and the frame's height */
|
||||
export type Frame = { h: number; lines: Read[] }
|
||||
/** lines whose middles are this close (a share of the frame's height) are the same line in the next frame */
|
||||
const ROW = 0.03
|
||||
/** a showing longer than this (s) is a title, a badge or a card, not a caption */
|
||||
const HELD = 4.5
|
||||
/** a caption fits what's said while it's up with at most this share of its letters edited; a line in capitals (a
|
||||
* badge's style: "BODY BUTTER · UP TO 96 HOURS" over "Body Butter delivers up to 96 hours") with at most CAPS_FIT */
|
||||
const FIT = 0.45
|
||||
const CAPS_FIT = 0.3
|
||||
/** captions are a track: up for at least this share of what's said, else the cut has none (hook text alone) */
|
||||
const TRACK = 0.4
|
||||
const CARDS = 8
|
||||
/** more lines than this in a frame is a screen or a card */
|
||||
const BUSY = 3
|
||||
/** words a transcriber often leaves out of what it hears (so a caption that has them may be right) */
|
||||
const SOFT = new Set(["yeah", "yes", "okay", "like", "wow", "hey", "right", "sorry", "well"])
|
||||
/** words this close are one line (s) */
|
||||
const LINE = 0.7
|
||||
|
||||
/** the frames' captions. First every line, the same line in consecutive frames joined into one showing (a line the
|
||||
* reader garbled a little in one frame still joins its neighbours); then the showings that are captions: short, and
|
||||
* fitting what's said while they're up with few edits. A badge, an app's screen, a sign or an end card stays up or
|
||||
* says something else. With captions up for under TRACK of the speech, the cut has none to hold */
|
||||
export function captionsOf(frames: Frame[], rate: number, heard: Word[]): Shown[] {
|
||||
const all: (Shown & { caps: boolean })[] = []
|
||||
frames.forEach((fr, i) => {
|
||||
const t = i / rate
|
||||
// a frame full of text is a screen or a card (an app, an end card, a product's label), not a caption over the picture
|
||||
if (fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4).length > BUSY) return
|
||||
for (const [, y, , h, text, score] of fr.lines) {
|
||||
const key = letters(text)
|
||||
if (score < LEAST || key.length < 4) continue
|
||||
const mid = (y + h / 2) / Math.max(1, fr.h)
|
||||
const last = all.findLast((s) => s.to >= t - 1.01 / rate && Math.abs(s.y - mid) <= ROW && similar(s.key, key))
|
||||
if (last) {
|
||||
last.to = t + 1 / rate
|
||||
// the longest reading of the line is kept (a frame mid-fade reads part of it)
|
||||
if (key.length > last.key.length) Object.assign(last, { text, key })
|
||||
} else all.push({ text, key, from: t, to: t + 1 / rate, y: mid, caps: false })
|
||||
}
|
||||
})
|
||||
const caps = (t: string) => /[A-Z]/.test(t) && !/[a-z]/.test(t)
|
||||
const fitted = all.filter((s) => {
|
||||
if (s.to - s.from > HELD) return false
|
||||
const said = heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join("")
|
||||
return fit(s.key, said).dist / s.key.length <= (caps(s.text) ? CAPS_FIT : FIT)
|
||||
}).map(({ caps: _, ...s }) => s)
|
||||
// kept to caption rows: where three captions or more sit (a label beside a product, a sign, sits on its own)
|
||||
const rowed = fitted.filter((s) => fitted.filter((o) => Math.abs(o.y - s.y) <= ROW).length >= 3)
|
||||
const talk = heard.filter((w) => !FILLER.has(letters(w.text)))
|
||||
const out = rowed
|
||||
const up = talk.filter((w) => out.some((s) => w.end >= s.from - 0.3 && w.start <= s.to + 0.3)).length
|
||||
// and a sequence: captions come one after another (CARDS showings at least, each starting apart), where hook text
|
||||
// that echoes the host is one card of a few lines at once
|
||||
const starts = [...new Set(out.map((s) => Math.round(s.from * 2)))].sort((a, b) => a - b)
|
||||
const cards = starts.filter((x, i) => i === 0 || x - starts[i - 1] >= 1).length
|
||||
if (!talk.length || up / talk.length < TRACK || cards < CARDS) return []
|
||||
return out.sort((a, b) => a.from - b.from)
|
||||
}
|
||||
|
||||
export const similar = (a: string, b: string) => {
|
||||
const [s, l] = a.length <= b.length ? [a, b] : [b, a]
|
||||
return fit(s, l).dist / Math.max(1, s.length) <= 0.25 && s.length / l.length >= 0.6
|
||||
}
|
||||
|
||||
/** letters [i, j) of a line's key are a whole word of the line as read (its spaces kept) */
|
||||
function wholeWord(text: string, key: string, i: number, j: number): boolean {
|
||||
let k = 0
|
||||
for (const w of text.split(/\s+/)) {
|
||||
const lw = letters(w)
|
||||
if (k === i && k + lw.length === j) return true
|
||||
k += lw.length
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** the captions held to what's heard: letters shown that weren't said, and words said that no caption up then shows */
|
||||
export function compare(shown: Shown[], heard: Word[]): Finding[] {
|
||||
if (!shown.length) return []
|
||||
const out: Finding[] = []
|
||||
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have
|
||||
for (const s of shown) {
|
||||
const f = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
|
||||
for (let i = 0; i < f.bad.length; ) {
|
||||
if (!f.bad[i]) { i++; continue }
|
||||
let j = i
|
||||
while (j < f.bad.length && f.bad[j]) j++
|
||||
if (j - i >= 3) out.push({ level: (j - i >= 5 || wholeWord(s.text, s.key, i, j)) && !SOFT.has(s.key.slice(i, j)) ? "error" : "warn", kind: "shown", at: s.from, says: `the caption "${s.text}" at ${s.from.toFixed(1)} s shows "${s.key.slice(i, j)}", which isn't said there: a caption is the speaker's exact words, built from the words file, never retyped` })
|
||||
i = j
|
||||
}
|
||||
}
|
||||
// said, not shown: a heard word while a caption is up whose letters none of the captions up around it holds
|
||||
const dropped: { w: Word; k: number }[] = []
|
||||
heard.forEach((w, k) => {
|
||||
const key = letters(w.text)
|
||||
if (!key || FILLER.has(key)) return
|
||||
const up = shown.filter((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
|
||||
if (!up.length) return
|
||||
const near = shown.filter((s) => w.end >= s.from - 2 && w.start <= s.to + 1.5).map((s) => s.key).join("")
|
||||
const allowed = key.length >= 5 ? 1 : 0
|
||||
if (fit(key, near).dist > allowed) dropped.push({ w, k })
|
||||
})
|
||||
// read two frames a second, a caption up for under a second can be missed between frames: words dropped are held as
|
||||
// errors only where the captions are phrases (up a second or more, typically), and only three or more in a row
|
||||
const lasts = shown.map((x) => x.to - x.from).sort((x, y) => x - y)
|
||||
const phrases = lasts[Math.floor(lasts.length / 2)] >= 1
|
||||
// a run inside captioned speech (the words either side of it are shown, within a line of it) is words a caption
|
||||
// left out: an error. A run at a line's edge is a line left uncaptioned, which an editor may mean (the CTA under its
|
||||
// badges): a warning
|
||||
const lost = new Set(dropped.map((d) => d.k))
|
||||
const shownAt = (k: number) => k >= 0 && k < heard.length && !lost.has(k) && shown.some((s) => heard[k].end >= s.from - 0.6 && heard[k].start <= s.to + 0.3)
|
||||
for (let i = 0; i < dropped.length; ) {
|
||||
let j = i + 1
|
||||
while (j < dropped.length && dropped[j].k === dropped[j - 1].k + 1) j++
|
||||
const run = dropped.slice(i, j).map((d) => d.w)
|
||||
const a = dropped[i].k - 1
|
||||
const b = dropped[j - 1].k + 1
|
||||
const inside = phrases && run.length >= 3 && shownAt(a) && shownAt(b) && run[0].start - heard[a].end < LINE && heard[b].start - run[run.length - 1].end < LINE
|
||||
const words = run.map((w) => w.text).join(" ")
|
||||
out.push(inside
|
||||
? { level: "error", kind: "dropped", at: run[0].start, says: `"${words}" is said at ${run[0].start.toFixed(1)} s, between words the captions show, but no caption shows ${run.length > 1 ? "them" : "it"}: build the captions from the words file so they say every word` }
|
||||
: { level: "warn", kind: "dropped", at: run[0].start, says: `"${words}" at ${run[0].start.toFixed(1)} s has no caption while the captions around it run: caption it from the words file, unless it's meant to go uncaptioned` })
|
||||
i = j
|
||||
}
|
||||
return out.sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "captions", text: "every caption on screen says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
if (!heard.length) return
|
||||
const sc = await f.scene()
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
|
||||
const shown = captionsOf(frames, sc.rate || 2, heard)
|
||||
for (const x of compare(shown, heard)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
// The hook and air-gap packs (11-30, Shane), on the export's own words and levels.
|
||||
//
|
||||
// hook: the first seconds have sound and picture working together. Elfster's Voted cut opened on 1.5 s of whiteboard
|
||||
// with nothing said (-27 dB): "a whiteboard people will read as the hook ... that's not a hook, a hook really should
|
||||
// have audio and video stimulation". The first word later than LEAD_ERROR into the cut, with nothing loud under the
|
||||
// opening either, is an error; later than LEAD_WARN, a warning. Sound alone (a hit, a song's first beat) under a
|
||||
// wordless opening is a warning, to be decided, not an error.
|
||||
// airgaps: the silences between words. "Measuring and cutting air gaps ... especially in a hook ... for social media
|
||||
// content or ads, especially if it is at all trying to look organic." In the hook's first HOOK seconds a gap over
|
||||
// HOOK_ERROR is an error and over HOOK_WARN a warning; later, one over BODY_WARN is a warning. The fix is raea's
|
||||
// tighten() (@raea/video airgaps), which cuts only between words and never into one.
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { airGaps } from "../../../video/src/airgaps.ts"
|
||||
|
||||
/** the first word this late (s): an error with a quiet opening, a warning */
|
||||
export const LEAD_ERROR = 1.0
|
||||
export const LEAD_WARN = 0.5
|
||||
/** the opening counts as carrying sound when its loud end is within this of the speech's (dB) */
|
||||
const OPENING_LOUD = 10
|
||||
/** the hook's seconds, and the gaps held in them (s) */
|
||||
export const HOOK = 3
|
||||
export const HOOK_ERROR = 0.5
|
||||
export const HOOK_WARN = 0.3
|
||||
/** a gap this long after the hook (s): a warning */
|
||||
export const BODY_WARN = 0.8
|
||||
|
||||
const pct = (xs: number[], q: number) => {
|
||||
if (!xs.length) return -100
|
||||
const s = [...xs].sort((a, b) => a - b)
|
||||
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
|
||||
}
|
||||
|
||||
export type HookFinding = { level: "error" | "warn"; at: number; says: string }
|
||||
|
||||
/** the opening and the gaps, from the words heard and the levels every 10 ms */
|
||||
export function hookAndGaps(words: { text: string; start: number; end: number }[], db: number[]): { hook: HookFinding[]; gaps: HookFinding[] } {
|
||||
const hook: HookFinding[] = []
|
||||
const gaps: HookFinding[] = []
|
||||
if (words.length < 3) return { hook, gaps }
|
||||
const first = words[0].start
|
||||
const speech = pct(words.flatMap((w) => db.slice(Math.floor(w.start * 100), Math.ceil(w.end * 100))), 0.8)
|
||||
const opening = pct(db.slice(0, Math.max(1, Math.floor(first * 100))), 0.8)
|
||||
const loud = opening > speech - OPENING_LOUD
|
||||
if (first > LEAD_WARN + 0.005) {
|
||||
const level = first > LEAD_ERROR && !loud ? "error" : "warn"
|
||||
hook.push({
|
||||
level,
|
||||
at: 0,
|
||||
says: loud
|
||||
? `the first word comes ${first.toFixed(1)} s in, over sound alone (${opening.toFixed(0)} dB against the speech's ${speech.toFixed(0)}): a hook has words and picture together from the first frame, so open on the first line unless the sound is the hook`
|
||||
: `${first.toFixed(1)} s of dead air before the first word ("${words[0].text}"), the opening ${(speech - opening).toFixed(0)} dB under the speech: a hook has sound and picture working together from the first frame. Open on the first line (cut the silent lead-in, or have the line land over the opening shot); a sign or a board people are meant to read is not a hook`,
|
||||
})
|
||||
}
|
||||
for (const g of airGaps(words.map((w) => ({ text: w.text, start: w.start, end: w.end })), HOOK)) {
|
||||
if (g.from === 0) continue // the lead-in is the hook pack's
|
||||
const inHook = g.from < HOOK
|
||||
const over = (x: number) => g.seconds > x + 0.005 // a transcript's times land on 10 ms steps
|
||||
const level = inHook ? (over(HOOK_ERROR) ? "error" : over(HOOK_WARN) ? "warn" : null) : over(BODY_WARN) ? "warn" : null
|
||||
if (!level) continue
|
||||
gaps.push({ level, at: g.from, says: `${g.seconds.toFixed(2)} s of air between "${g.after}" and "${g.before}" at ${g.from.toFixed(1)} s${inHook ? " in the hook" : ""}: tighten it to about ${inHook ? 0.15 : 0.25} s with tighten() (raea's air-gap cut: between words only, never into one), unless the pause is the beat` })
|
||||
}
|
||||
return { hook, gaps }
|
||||
}
|
||||
|
||||
export const hookPack = check<FileFacts>(
|
||||
{ id: "hook", text: "the hook opens on words and picture together, no dead air", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
for (const x of hookAndGaps(heard, f.levels().db).hook) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
|
||||
export const airgapsPack = check<FileFacts>(
|
||||
{ id: "airgaps", text: "no air between words: tight in the hook, no long pause after", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const heard = await f.words()
|
||||
for (const x of hookAndGaps(heard, f.levels().db).gaps) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -1,6 +1,7 @@
|
||||
// raea's packs by name (contract.ts PACKS says what each holds a job to).
|
||||
import type { Check } from "raea/check"
|
||||
import type { PackName } from "../contract.ts"
|
||||
import captions from "./captions.ts"
|
||||
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.ts"
|
||||
import { floorPack, stillsPack } from "./floor.ts"
|
||||
import frames from "./frames.ts"
|
||||
@@ -10,13 +11,21 @@ import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
|
||||
import { seenPack, surprisePack } from "./look.ts"
|
||||
import naming from "./naming.ts"
|
||||
import place from "./place.ts"
|
||||
import sizes from "./sizes.ts"
|
||||
import sizes, { allSizes } from "./sizes.ts"
|
||||
import sound from "./sound.ts"
|
||||
import reading from "./reading.ts"
|
||||
import { airgapsPack, hookPack } from "./hook.ts"
|
||||
import voice from "./voice.ts"
|
||||
import words from "./words.ts"
|
||||
|
||||
/** each pack's checks (say holds each cut, and the phrases one cut is enough for across them) */
|
||||
export const PACK_CHECKS: Record<PackName, Check[]> = {
|
||||
words: [words],
|
||||
captions: [captions],
|
||||
voice: [voice],
|
||||
reading: [reading],
|
||||
hook: [hookPack],
|
||||
airgaps: [airgapsPack],
|
||||
sound: [sound],
|
||||
frames: [frames],
|
||||
montage: [montage],
|
||||
@@ -24,7 +33,7 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
|
||||
seen: [seenPack],
|
||||
surprise: [surprisePack],
|
||||
naming: [naming],
|
||||
sizes: [sizes],
|
||||
sizes: [sizes, allSizes],
|
||||
quotes: [quotesPack],
|
||||
count: [countPack],
|
||||
open: [openPack],
|
||||
|
||||
@@ -18,7 +18,9 @@ import type { FileFacts } from "../facts.ts"
|
||||
import { RATE } from "../media.ts"
|
||||
|
||||
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
|
||||
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[] } | null
|
||||
/** the scene reader's reading of a frame's text: [x, y, w, h, text, score] a line (the captions pack) */
|
||||
export type TextLine = [number, number, number, number, string, number]
|
||||
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[]; texts?: TextLine[] } | null
|
||||
/** [x, y, w, h, label, score] */
|
||||
export type Thing = [number, number, number, number, string, number]
|
||||
/** a box in shares of the frame: x, y, w, h */
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// The reading pack (11-30, Shane: "the words on screen relative to duration ... if a wordy CTA or component or scene is
|
||||
// meant to be fully read or if it just adds glossable content or context, and if it's on screen long enough to be
|
||||
// read"). From the scene reader's text (the farm's texts, two frames a second), every block of text that isn't a
|
||||
// caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
|
||||
//
|
||||
// time to read: READ_BASE s to find it, then WPS words a second (a feed viewer's skim of short ad text; subtitle
|
||||
// standards sit near 3 words a second). A block up for under its time is a warning; under SHORT of it an error,
|
||||
// unless it holds GLOSS words or more: a screen, fine print or a dense card can't be read in an ad anyway, so it's
|
||||
// texture, and the finding asks which it is meant to be.
|
||||
// the measure: every finding says words, seconds and words a second, so a CTA's reading load is a number the
|
||||
// editor holds (and the skill's end card rule: few words, held long enough).
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
|
||||
|
||||
export type Block = { text: string; words: number; from: number; to: number; size?: number }
|
||||
export type Finding = { level: "error" | "warn"; at: number; says: string; block: Block }
|
||||
|
||||
/** seconds to find a block before reading it */
|
||||
export const READ_BASE = 0.5
|
||||
/** words read a second */
|
||||
export const WPS = 3
|
||||
/** under this share of its time to read, an error */
|
||||
export const SHORT = 0.6
|
||||
/** a block of this many words or more is texture unless the editor means it read */
|
||||
export const GLOSS = 25
|
||||
/** fewer words than this is a logo, a label or a button, read at a glance */
|
||||
const FEW = 4
|
||||
|
||||
const wordsIn = (t: string) => t.split(/\s+/).filter((w) => letters(w).length > 0).length
|
||||
/** the time a block of `words` needs on screen */
|
||||
export const need = (words: number) => READ_BASE + words / WPS
|
||||
|
||||
/** a frame with more lines read than this is a screen, a shelf or a page (an app shot whole, a product line-up's
|
||||
* labels): texture by nature, left out */
|
||||
export const SCREEN = 6
|
||||
/** lines whose middles are this close (a share of the frame's height) in consecutive frames are one line */
|
||||
const ROW = 0.03
|
||||
/** lines that come up within this of each other (s), up together, are one block */
|
||||
const TOGETHER = 0.6
|
||||
/** a line that fits what's said around it with at most this share of its letters edited is read with the voice */
|
||||
const SAID = 0.35
|
||||
/** a phone's status bar clock: the block is an app's screen, shown, not read */
|
||||
/** text this small (its lines' median height, a share of the frame's) is an app's screen or fine print, not a
|
||||
* designed line: 1080x1920's 54 px */
|
||||
const SMALL = 0.028
|
||||
const CLOCK = /\d{1,2}:\d{2}/
|
||||
|
||||
/** the frames' blocks of text. Each line that isn't a caption is followed from frame to frame (same row, same text,
|
||||
* its fullest reading kept: text building on, or a frame mid-fade); lines that come up together and overlap are one
|
||||
* block, read as one. Frames that are screens are left out */
|
||||
export function blocksOf(frames: Frame[], rate: number, isCaption: (t: number, key: string) => boolean, heard: Word[] = []): Block[] {
|
||||
type Line = { text: string; key: string; from: number; to: number; y: number; size: number }
|
||||
const lines: Line[] = []
|
||||
frames.forEach((fr, i) => {
|
||||
const t = i / rate
|
||||
const read = fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 2)
|
||||
if (read.length > SCREEN) return
|
||||
for (const [, y, , h, text] of read) {
|
||||
const key = letters(text)
|
||||
if (isCaption(t, key)) continue
|
||||
// words shown as they're said (kinetic type, a caption the captions pack didn't take as one) are read with the voice
|
||||
const said = heard.filter((w) => w.end >= t - 1.5 && w.start <= t + 2.5).map((w) => letters(w.text)).join("")
|
||||
if (key.length >= 4 && fit(key, said).dist / key.length <= SAID) continue
|
||||
const mid = (y + h / 2) / Math.max(1, fr.h)
|
||||
const last = lines.findLast((l) => l.to >= t - 1.01 / rate && Math.abs(l.y - mid) <= ROW && (similar(l.key, key) || l.key.includes(key) || key.includes(l.key)))
|
||||
if (last) {
|
||||
last.to = t + 1 / rate
|
||||
if (key.length > last.key.length) Object.assign(last, { text, key })
|
||||
} else lines.push({ text, key, from: t, to: t + 1 / rate, y: mid, size: h / Math.max(1, fr.h) })
|
||||
}
|
||||
})
|
||||
const blocks: (Block & { parts: Line[] })[] = []
|
||||
for (const l of [...lines].sort((a, b) => a.from - b.from || a.y - b.y)) {
|
||||
const b = blocks.find((x) => Math.abs(x.from - l.from) <= TOGETHER && l.from < x.to)
|
||||
if (b) {
|
||||
b.parts.push(l)
|
||||
b.to = Math.max(b.to, l.to)
|
||||
} else blocks.push({ text: "", words: 0, from: l.from, to: l.to, parts: [l] })
|
||||
}
|
||||
return blocks.map(({ parts, ...b }) => {
|
||||
const text = parts.sort((x, y) => x.y - y.y).map((x) => x.text).join(" ")
|
||||
// a block is read for as long as most of it is up: its lines' median time up
|
||||
const ups = parts.map((x) => x.to - x.from).sort((x, y) => x - y)
|
||||
const sizes = parts.map((x) => x.size).sort((x, y) => x - y)
|
||||
return { ...b, text, words: wordsIn(text), to: b.from + ups[Math.floor(ups.length / 2)], size: sizes[Math.floor(sizes.length / 2)] }
|
||||
})
|
||||
}
|
||||
|
||||
/** blocks up for less time than their words take to read */
|
||||
export function reading(blocks: Block[]): Finding[] {
|
||||
const out: Finding[] = []
|
||||
for (const b of blocks) {
|
||||
if (b.words < FEW) continue
|
||||
const up = b.to - b.from
|
||||
const n = need(b.words)
|
||||
if (up >= n) continue
|
||||
const quote = b.text.length > 70 ? `${b.text.slice(0, 67)}...` : b.text
|
||||
const load = `${b.words} words up ${up.toFixed(1)} s (${(b.words / up).toFixed(1)} words a second; reading takes about ${n.toFixed(1)} s at ${WPS} a second)`
|
||||
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
|
||||
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
|
||||
async (f) => {
|
||||
if (!f.made || f.kind !== "video") return
|
||||
const sc = await f.scene()
|
||||
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
|
||||
if (!frames.some((x) => x.lines.length)) return
|
||||
const rate = sc.rate || 2
|
||||
const heard = await f.words()
|
||||
const caps = captionsOf(frames, rate, heard)
|
||||
const isCaption = (t: number, key: string) => caps.some((c) => t >= c.from - 0.01 && t < c.to && (similar(c.key, key) || c.key.includes(key)))
|
||||
for (const x of reading(blocksOf(frames, rate, isCaption, heard))) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -3,9 +3,13 @@
|
||||
// (11-28, Shane: "always does all concepts first in one size or aspect ratio ... and then once approved we can then do
|
||||
// any other resizes ... generally lean toward 9:16 first"). The approval is the brief's `open` item about "sizes",
|
||||
// answered by the person (`by`).
|
||||
// And every size by the end (11-30, Shane: "it will show completed but what about doing all the resizes"): Dutch
|
||||
// finished on its 9:16 masters alone, the brief's 4:5, 1:1 and 16:9 never made. At done, every ad's newest version is
|
||||
// there in every format its brief names (brief.ts cut `formats`), unless a person's answer to the open item about "sizes"
|
||||
// says fewer.
|
||||
import { check, found } from "raea/check"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { bookkeeping, sizeOf } from "./naming.ts"
|
||||
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
|
||||
|
||||
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
|
||||
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
|
||||
@@ -24,3 +28,36 @@ export default check<Job>({ id: "sizes", text: "one size first: no other size be
|
||||
fix: `finish and show every ad in ${first[0]} first; recut the other sizes from the approved version once a person answers the brief's open item about "sizes" (with \`by\`)`,
|
||||
})
|
||||
})
|
||||
|
||||
/** a format as a name's size: "9:16" is 9x16 */
|
||||
const asSize = (f: string) => f.replace(":", "x").toLowerCase()
|
||||
/** a version's number in a name (v3), else 0 */
|
||||
const versionOf = (name: string) => Number(/_v(\d+)(?=_|\.|$)/i.exec(name)?.[1] ?? 0)
|
||||
|
||||
export const allSizes = check<Job>({ id: "sizes-all", text: "every size the brief asks for, by the end", over: "job", at: ["done"] }, async (j) => {
|
||||
if (j.contract?.kind !== "cut") return
|
||||
const c = j.contract.cut
|
||||
const want = [...new Set([...(c?.formats ?? []), ...(c?.cuts ?? []).flatMap((p) => p.formats ?? [])].map(asSize))]
|
||||
if (want.length < 2) return
|
||||
const sizesItem = (c?.open ?? []).find((o) => o.about === "sizes" && o.answer?.trim() && o.by?.trim())
|
||||
// a person said which sizes (or that one is enough): only the sizes their answer names
|
||||
const wanted = sizesItem ? want.filter((s) => new RegExp(s.replace("x", "[:x]"), "i").test(sizesItem.answer ?? "")) : want
|
||||
if (wanted.length < 2) return
|
||||
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image") && sizeOf(f.path))
|
||||
// each ad at its newest version, and the sizes that version is in
|
||||
const ads = new Map<string, { v: number; sizes: Set<string> }>()
|
||||
for (const f of made) {
|
||||
const ad = adOf(f.path), v = versionOf(f.path), s = sizeOf(f.path)!
|
||||
const cur = ads.get(ad)
|
||||
if (!cur || v > cur.v) ads.set(ad, { v, sizes: new Set([s]) })
|
||||
else if (v === cur.v) cur.sizes.add(s)
|
||||
}
|
||||
for (const [ad, { v, sizes }] of ads) {
|
||||
const missing = wanted.filter((s) => !sizes.has(s))
|
||||
if (!missing.length) continue
|
||||
found({
|
||||
says: `${ad} v${v} is in ${[...sizes].join(", ")} but the brief asks for ${wanted.join(", ")}: ${missing.join(", ")} not made`,
|
||||
fix: `recut ${ad} v${v} in ${missing.join(", ")} from the approved version (same version, a new size: ${ad}_v${v}_${missing[0]}), check each, and deliver them before you finish; a person's answer to the brief's open item about "sizes" is the only way to deliver fewer`,
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -36,13 +36,26 @@ const LEVEL_WARN = 4
|
||||
const SFX_UNDER = 10
|
||||
/** music: further under than this isn't heard, closer than this fights the words */
|
||||
const MUSIC_LOST = 26
|
||||
const MUSIC_FIGHTS = 6
|
||||
const MUSIC_FIGHTS = 10
|
||||
|
||||
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
|
||||
|
||||
const MUSIC = /music|bed|score/i
|
||||
const SFX = /sfx|fx|effect|foley|sting/i
|
||||
export const busOf = (c: Clip): "voice" | "music" | "sfx" => (c.bus && MUSIC.test(c.bus) ? "music" : c.bus && SFX.test(c.bus) ? "sfx" : c.bus === "voice" || !c.bus ? (SFX.test(path.basename(c.src)) ? "sfx" : MUSIC.test(path.basename(c.src)) ? "music" : "voice") : "voice")
|
||||
/** a sound with no bus, as raea's default mix routes it (systems/mix default_bus, 11-30): footage and voice files are the
|
||||
* talking, effects stay effects, any other audio file is the music, ducked DEFAULT_DUCK under the talking */
|
||||
const VIDEO_EXT = /\.(mp4|mov|m4v|webm|mkv|avi|mxf)$/i
|
||||
const VOICE_NAME = /voice|narrat|dialog|speech|_vo|vo_|-vo|vo-|interview/i
|
||||
const SFX_NAME = /sfx|foley|whoosh|swoosh|sting|riser|impact|click|_fx|fx_/i
|
||||
export const busOf = (c: Clip): "voice" | "music" | "sfx" => {
|
||||
if (c.bus) return MUSIC.test(c.bus) ? "music" : SFX.test(c.bus) ? "sfx" : "voice"
|
||||
const name = path.basename(c.src)
|
||||
if (VIDEO_EXT.test(name) || VOICE_NAME.test(name)) return "voice"
|
||||
if (SFX_NAME.test(name) || SFX.test(name)) return "sfx"
|
||||
return "music"
|
||||
}
|
||||
/** how far raea's default mix ducks a music file with no bus under the talking (dB, systems/mix DEFAULT_DUCK_DB) */
|
||||
export const DEFAULT_DUCK = -6
|
||||
|
||||
const pct = (xs: number[], q: number) => {
|
||||
if (!xs.length) return -100
|
||||
@@ -165,7 +178,8 @@ export function balance(heard: Heard[], fps: number): Finding[] {
|
||||
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
|
||||
}
|
||||
for (const h of heard.filter((x) => x.kind === "music")) {
|
||||
const d = h.level - mid
|
||||
// a music file on no bus is ducked under the talking by the default mix, so it's heard that much lower
|
||||
const d = h.level - mid + (h.clip.bus ? 0 : DEFAULT_DUCK)
|
||||
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
|
||||
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// The voice pack (11-30, Shane: "we should be checking audio if its too quiet for dialogue or what is supposed to be
|
||||
// primary"): whether the dialogue is on top in the export as it was mixed, measured on the export itself. The sound pack
|
||||
// levels each line from its source take and the edit's gains, before the mix: ducking, the limiter and the loudness pass
|
||||
// all come after it, and a line that's even in the edit can sink in the mix.
|
||||
//
|
||||
// on top: the speech (the words pass's words, every 10 ms inside them) against what's under it in the gaps between
|
||||
// words while people are talking (music, effects, the street): under 6 dB above it is an error (the bed is as loud
|
||||
// as the voice), under 10 dB a warning.
|
||||
// even: each line (words with less than 0.7 s between them) against the export's typical line: 6 dB or more quieter
|
||||
// is an error (a line too quiet to follow that a transcriber still hears), 4 dB a warning.
|
||||
import { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import type { Word } from "../media.ts"
|
||||
|
||||
export type Finding = { level: "error" | "warn"; kind: "buried" | "quiet"; at: number; says: string }
|
||||
|
||||
/** the speech's level over what's under it (dB): under ON_TOP_ERROR an error, under ON_TOP_WARN a warning */
|
||||
export const ON_TOP_ERROR = 6
|
||||
export const ON_TOP_WARN = 10
|
||||
/** a line this far under the typical line (dB) */
|
||||
export const QUIET_ERROR = 6
|
||||
export const QUIET_WARN = 4
|
||||
/** words this close together are one line (s) */
|
||||
const LINE_GAP = 0.7
|
||||
/** a gap between words counts as the bed from this far after a word to this far before the next (s): the word's tail
|
||||
* and breath are left out */
|
||||
const CLEAR = 0.12
|
||||
/** a gap shorter than this is too short to read the bed in (s) */
|
||||
const GAP_MIN = 0.2
|
||||
/** the bed is judged only on this many gaps between words, this many 10 ms frames of them in all */
|
||||
const BED_GAPS = 3
|
||||
const BED_FRAMES = 100
|
||||
/** the level a span is read at: its loud end (this percentile of its 10 ms frames), so pauses inside words don't count */
|
||||
const Q = 0.8
|
||||
|
||||
const pct = (xs: number[], q: number) => {
|
||||
if (!xs.length) return -100
|
||||
const s = [...xs].sort((a, b) => a - b)
|
||||
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
|
||||
}
|
||||
const frames = (db: number[], a: number, b: number) => db.slice(Math.max(0, Math.floor(a * 100)), Math.min(db.length, Math.ceil(b * 100)))
|
||||
|
||||
/** the lines: words with under LINE_GAP between them */
|
||||
export function linesOf(heard: Word[]): Word[][] {
|
||||
const out: Word[][] = []
|
||||
for (const w of heard) {
|
||||
const last = out[out.length - 1]
|
||||
if (last && w.start - last[last.length - 1].end < LINE_GAP) last.push(w)
|
||||
else out.push([w])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** the speech against the bed under it, and each line against the typical line */
|
||||
export function voice(db: number[], heard: Word[]): Finding[] {
|
||||
if (heard.length < 4) return []
|
||||
const out: Finding[] = []
|
||||
const speech: number[] = []
|
||||
for (const w of heard) speech.push(...frames(db, w.start, w.end))
|
||||
const bed: number[] = []
|
||||
let gaps = 0
|
||||
const lines = linesOf(heard)
|
||||
// the gaps inside lines and between lines close together: what's under the talking, not the end card's music
|
||||
for (let k = 1; k < heard.length; k++) {
|
||||
const a = heard[k - 1].end + CLEAR
|
||||
const b = heard[k].start - CLEAR
|
||||
if (b - a >= GAP_MIN && b - a < 2.5) { bed.push(...frames(db, a, b)); gaps++ }
|
||||
}
|
||||
const S = pct(speech, Q)
|
||||
// enough of the bed to judge: a tightly cut take has few gaps, and one of them is often still a hum or a breath
|
||||
// (11-30: Body Shop's host hook read 1.5 dB off a single 0.34 s gap between two "Mmm"s)
|
||||
if (gaps >= BED_GAPS && bed.length >= BED_FRAMES) {
|
||||
const B = pct(bed, Q)
|
||||
const over = S - B
|
||||
if (over < ON_TOP_WARN) out.push({ level: over < ON_TOP_ERROR ? "error" : "warn", kind: "buried", at: heard[0].start, says: `the dialogue is only ${over.toFixed(1)} dB above what's under it between words (music, effects, the street): it should be ${ON_TOP_WARN} dB or more on top. Duck the music further under the voice, or lift the voice` })
|
||||
}
|
||||
const lv = lines.map((l) => ({ l, db: pct(frames(db, l[0].start, l[l.length - 1].end), Q) }))
|
||||
const typical = pct(lv.map((x) => x.db), 0.5)
|
||||
for (const { l, db: d } of lv) {
|
||||
const under = typical - d
|
||||
if (under < QUIET_WARN || l.length < 2) continue
|
||||
const text = l.map((w) => w.text).join(" ")
|
||||
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${text.length > 60 ? `${text.slice(0, 57)}...` : text}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
|
||||
}
|
||||
return out.sort((a, b) => a.at - b.at)
|
||||
}
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "voice", text: "the dialogue on top of the mix in the export, every line as loud as the others", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
|
||||
async (f) => {
|
||||
if (!f.made || (f.kind !== "video" && f.kind !== "audio")) return
|
||||
const heard = await f.words()
|
||||
if (!heard.length) return
|
||||
for (const x of voice(f.levels().db, heard)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { captionsOf, compare, fit, letters } from "../src/packs/captions.ts"
|
||||
import { voice } from "../src/packs/voice.ts"
|
||||
|
||||
// what the reader saw, two frames a second: phrase captions in one row (y 120 of 960), as Elfster's cut 1 had them
|
||||
const w = (text: string, start: number, end: number) => ({ text, start, end })
|
||||
const said = "Everyone has a fake I love it face when they get a bad gift. How bad is yours? Thanks. Oh my, like how did you know? Now I know for sure, okay, this is what they wanted, and everyone's happy."
|
||||
.split(" ").map((t, i) => w(t, 0.2 + i * 0.3, 0.45 + i * 0.3))
|
||||
const at = (t: number) => said.find((x) => x.start <= t && x.end >= t)
|
||||
const shownLines: [number, number, string][] = [
|
||||
[0.1, 1.4, "Everyone has a fake"], [1.4, 2.6, "'I love it' face"], [2.6, 3.8, "for a bad gift."], [3.8, 5.0, "How bad is yours?"],
|
||||
[5.0, 5.9, "Oh, thanks!"], [5.9, 7.1, "Oh my god,"], [7.1, 8.6, "like, how did you know?"], [8.6, 9.6, "Now I know for sure"],
|
||||
[9.6, 11.4, "what they wanted,"], [11.4, 12.6, "and everyone's happy."],
|
||||
]
|
||||
const frames = Array.from({ length: 27 }, (_, i) => {
|
||||
const t = i / 2
|
||||
const l = shownLines.find(([a, b]) => t >= a && t < b)
|
||||
return { h: 960, lines: l ? [[60, 110, 420, 26, l[2], 0.95] as [number, number, number, number, string, number]] : [] }
|
||||
})
|
||||
|
||||
test("a caption is fitted to the stretch of speech it says", () => {
|
||||
expect(fit("forabadgift", letters("when they get a bad gift")).dist).toBe(3)
|
||||
// a badge in capitals that echoes the line ("BODY BUTTER · UP TO 96") is held to the stricter fit (0.3), and misses it
|
||||
expect(fit("bodybutterupto96", letters("body butter delivers up to 96 hours")).dist / 16).toBeGreaterThan(0.3)
|
||||
})
|
||||
|
||||
test("captions that change or drop words are found; the same words pass", () => {
|
||||
void at
|
||||
const shown = captionsOf(frames, 2, said)
|
||||
expect(shown.length).toBeGreaterThanOrEqual(8)
|
||||
const f = compare(shown, said)
|
||||
// "for" stands in for "get", "god" was never said
|
||||
expect(f.some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
|
||||
// "when they" (before "get"), and "okay, this is" between captioned words, are dropped
|
||||
expect(f.some((x) => x.kind === "dropped" && x.level === "error" && x.says.includes("okay, this is"))).toBe(true)
|
||||
// captions that say exactly what's said find nothing
|
||||
const exact = said.reduce<[number, number, string][]>((a, x, i) => (i % 4 === 0 ? [...a, [x.start, said[Math.min(i + 3, said.length - 1)].end, said.slice(i, i + 4).map((y) => y.text).join(" ")]] : a), [])
|
||||
const fr2 = Array.from({ length: 27 }, (_, i) => {
|
||||
const t = i / 2
|
||||
const l = exact.find(([a, b]) => t >= a && t < b)
|
||||
return { h: 960, lines: l ? [[60, 110, 420, 26, l[2], 0.95] as [number, number, number, number, string, number]] : [] }
|
||||
})
|
||||
expect(compare(captionsOf(fr2, 2, said), said).filter((x) => x.level === "error")).toEqual([])
|
||||
})
|
||||
|
||||
test("hook text alone isn't a caption track", () => {
|
||||
const hook = Array.from({ length: 27 }, (_, i) => ({ h: 960, lines: i < 6 ? [[60, 110, 420, 26, "Everyone has a fake 'I love it' face", 0.95] as [number, number, number, number, string, number]] : [] }))
|
||||
expect(captionsOf(hook, 2, said)).toEqual([])
|
||||
})
|
||||
|
||||
test("the voice pack: dialogue on top of the mix, every line even", () => {
|
||||
const words = Array.from({ length: 25 }, (_, i) => w("word", 0.2 + i * 0.8, 0.5 + i * 0.8))
|
||||
// speech at -20 dB, the bed between words at -40: 20 dB on top, nothing found
|
||||
const level = (bed: number, quietFrom = 99) => Array.from({ length: 2100 }, (_, f) => {
|
||||
const t = f / 100
|
||||
const inWord = words.some((x) => t >= x.start && t < x.end)
|
||||
return inWord ? (t >= quietFrom ? -29 : -20) : bed
|
||||
})
|
||||
expect(voice(level(-40), words)).toEqual([])
|
||||
// the bed at -24 between words: 4 dB on top, buried
|
||||
expect(voice(level(-24), words).some((x) => x.kind === "buried" && x.level === "error")).toBe(true)
|
||||
// a line 9 dB quieter than the rest (words 15 on are one line with no gap > 0.7 s: all of them here, so split a line)
|
||||
const two = [...words.slice(0, 20), ...words.slice(20).map((x) => ({ ...x, start: x.start + 1, end: x.end + 1 }))]
|
||||
const lv = Array.from({ length: 2300 }, (_, f) => {
|
||||
const t = f / 100
|
||||
const x = two.find((y) => t >= y.start && t < y.end)
|
||||
return x ? (two.indexOf(x) >= 20 ? -29 : -20) : -45
|
||||
})
|
||||
const third = [...two, ...words.slice(0, 10).map((x) => ({ ...x, start: x.start + 23, end: x.end + 23 }))]
|
||||
const lv3 = [...lv, ...Array.from({ length: 600 }, (_, f) => (third.slice(40).some((y) => (2300 + f) / 100 >= y.start && (2300 + f) / 100 < y.end) ? -20 : -45))]
|
||||
expect(voice(lv3, third).some((x) => x.kind === "quiet" && x.level === "error")).toBe(true)
|
||||
})
|
||||
@@ -17,7 +17,7 @@ test("a cut holds the craft by default, surprise only when asked", () => {
|
||||
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "stills", "run", "says"])
|
||||
expect(packsOf(cut({ cut: { brief: "b.txt" }, rules: [{ id: "t", run: "true" }] }))).toContain("run")
|
||||
// no contract: the floor every made video is held to
|
||||
expect(packsOf(null)).toEqual(["frames", "floor", "seen", "stills"])
|
||||
expect(packsOf(null)).toEqual(["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"])
|
||||
})
|
||||
|
||||
test("a project's own check runs at its moments", async () => {
|
||||
|
||||
@@ -14,7 +14,7 @@ beforeAll(() => {
|
||||
const BRIEF = 'Deliverables: 10 total videos (4 solos / 1 mashup per angle).\nUse the phrase "free, fun, and easy."\nDon\'t let it read as White Elephant.\nEnd on the CTA: "Make your Wishlist and organize your Gift Exchange on Elfster. It\'s free."\nCTV specs from the client [TO CONFIRM]\n'
|
||||
const contract = (cut: Record<string, unknown> = {}) => ({
|
||||
kind: "cut",
|
||||
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false },
|
||||
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false, hook: false, airgaps: false },
|
||||
cut: {
|
||||
brief: "media/brief.txt",
|
||||
count: { value: 2, from: "10 total videos" },
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// The hook and air-gap packs, and @raea/video's tighten() they point to (11-30, Shane): no dead air before the first
|
||||
// word, tight gaps in the hook, and a cut that only ever lands between words.
|
||||
import { expect, test } from "bun:test"
|
||||
import { hookAndGaps } from "../src/packs/hook.ts"
|
||||
import { airGaps, tighten } from "../../video/src/airgaps.ts"
|
||||
|
||||
const W = (spec: [string, number, number][]) => spec.map(([text, start, end]) => ({ text, start, end }))
|
||||
/** levels every 10 ms: `on` dB inside the words, `off` between them */
|
||||
const levels = (words: { start: number; end: number }[], secs: number, on = -18, off = -50) =>
|
||||
Array.from({ length: Math.ceil(secs * 100) }, (_, i) => (words.some((w) => i / 100 >= w.start && i / 100 < w.end) ? on : off))
|
||||
|
||||
test("Voted's opening: 1.5 s of a silent whiteboard before the first word is dead air", () => {
|
||||
const words = W([["Do", 1.54, 1.6], ["you", 1.6, 1.76], ["use", 1.76, 2.0], ["Elfster?", 2.0, 2.46]])
|
||||
const { hook } = hookAndGaps(words, levels(words, 4))
|
||||
expect(hook).toHaveLength(1)
|
||||
expect(hook[0].level).toBe("error")
|
||||
expect(hook[0].says).toMatch(/1\.5 s of dead air/)
|
||||
})
|
||||
|
||||
test("a cut that talks from its first frame has no hook finding; sound under a late first word is only a warning", () => {
|
||||
const now = W([["Every", 0.08, 0.3], ["friend", 0.3, 0.6], ["group", 0.6, 0.9]])
|
||||
expect(hookAndGaps(now, levels(now, 2)).hook).toEqual([])
|
||||
const late = W([["So", 1.2, 1.4], ["good", 1.4, 1.7], ["really", 1.7, 2.0]])
|
||||
const db = levels(late, 3).map((d, i) => (i < 120 ? -20 : d)) // a song's first beat under the opening
|
||||
expect(hookAndGaps(late, db).hook[0].level).toBe("warn")
|
||||
})
|
||||
|
||||
test("gaps: tight in the hook, only long ones after it", () => {
|
||||
const words = W([["I", 0.0, 0.2], ["use", 0.8, 1.0], ["it", 1.35, 1.5], ["every", 5.0, 5.3], ["Christmas", 6.5, 7.0], ["really", 7.3, 7.6]])
|
||||
const { gaps } = hookAndGaps(words, levels(words, 8))
|
||||
expect(gaps.map((g) => [g.level, +g.at.toFixed(1)])).toEqual([["error", 0.2], ["warn", 1.0], ["error", 1.5], ["warn", 5.3]])
|
||||
})
|
||||
|
||||
test("tighten() cuts only between words, leaves a pad on each, and the lead-in down to a pad", () => {
|
||||
const words = W([["Do", 1.54, 1.6], ["you", 1.6, 1.76], ["use", 1.76, 2.0], ["Elfster?", 2.0, 2.46], ["I", 3.4, 3.5], ["do", 3.5, 3.7]])
|
||||
const { keep, cuts } = tighten(words)
|
||||
expect(cuts[0]).toEqual({ from: 0, to: 1.46 })
|
||||
// every word lies whole inside what's kept
|
||||
for (const w of words) expect(keep.some((k) => k.from <= w.start - 0.079 && k.to >= w.end + 0.079 - 1e-9 || (k.from <= w.start && k.to >= w.end))).toBe(true)
|
||||
// the 0.94 s gap after "Elfster?" (past the 3 s hook? no: it starts at 2.46) is left at the hook's 0.16 s
|
||||
const left = airGaps(words).find((g) => g.after === "Elfster?")!
|
||||
const taken = cuts.filter((c) => c.from >= left.from && c.to <= left.to).reduce((n, c) => n + c.to - c.from, 0)
|
||||
expect(+(left.seconds - taken).toFixed(2)).toBe(0.16)
|
||||
})
|
||||
|
||||
test("tighten() with levels never cuts where it's still loud: a word the transcript ended early stays whole", () => {
|
||||
// "gifts" is heard to 2.3 s but the transcript ends it at 2.0
|
||||
const words = W([["buy", 1.0, 1.4], ["gifts", 1.5, 2.0], ["now", 3.0, 3.3]])
|
||||
const db = levels(W([["buy", 1.0, 1.4], ["gifts", 1.5, 2.3], ["now", 3.0, 3.3]]), 4)
|
||||
const { cuts } = tighten(words, { levels: db, lead: false })
|
||||
const c = cuts.find((x) => x.from > 2)!
|
||||
expect(c.from).toBeGreaterThanOrEqual(2.3)
|
||||
expect(c.to).toBeLessThanOrEqual(3.0)
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { blocksOf, need, reading } from "../src/packs/reading.ts"
|
||||
|
||||
type L = [number, number, number, number, string, number]
|
||||
const line = (y: number, text: string, h = 48): L => [60, y, 420, h, text, 0.95]
|
||||
const frames = (n: number, at: (t: number) => L[]) => Array.from({ length: n }, (_, i) => ({ h: 960, lines: at(i / 2) }))
|
||||
const none = () => false
|
||||
|
||||
test("time to read: half a second, then 3 words a second", () => {
|
||||
expect(need(6)).toBeCloseTo(2.5)
|
||||
})
|
||||
|
||||
test("a wordy card up for a second is an error; held long enough, it passes", () => {
|
||||
const card = [line(300, "How does your group do"), line(360, "Secret Santa this year?"), line(420, "Names in a hat or chaos")]
|
||||
const quick = blocksOf(frames(10, (t) => (t < 1 ? card : [])), 2, none)
|
||||
expect(quick.length).toBe(1)
|
||||
expect(quick[0].words).toBe(15)
|
||||
expect(reading(quick)[0].level).toBe("error")
|
||||
expect(reading(blocksOf(frames(16, (t) => (t < 6 ? card : [])), 2, none))).toEqual([])
|
||||
})
|
||||
|
||||
test("a phone's screen and small print are texture: a warning that asks, never an error", () => {
|
||||
const screen = [line(40, "12:59", 18), line(300, "Awesome, your exchange is created! Invite everyone", 18)]
|
||||
const f = reading(blocksOf(frames(6, (t) => (t < 0.5 ? screen : [])), 2, none))
|
||||
expect(f.length).toBe(1)
|
||||
expect(f[0].level).toBe("warn")
|
||||
expect(f[0].says).toContain("texture")
|
||||
})
|
||||
|
||||
test("a frame full of lines (a shelf of labels) is left out, and words said as they show are read with the voice", () => {
|
||||
const shelf = Array.from({ length: 9 }, (_, i) => line(100 + i * 80, `Body Butter Mango ${i}`))
|
||||
expect(blocksOf(frames(4, () => shelf), 2, none)).toEqual([])
|
||||
const heard = "so good I want to eat it".split(" ").map((t, i) => ({ text: t, start: 0.2 + i * 0.3, end: 0.45 + i * 0.3 }))
|
||||
expect(blocksOf(frames(4, (t) => (t < 0.5 ? [line(300, "SO GOOD I WANT TO EAT IT")] : [])), 2, none, heard)).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
// The sizes pack's end (11-30, Shane: "it will show completed but what about doing all the resizes"): at done, every ad's
|
||||
// newest version in every format the brief names, unless a person's answer about "sizes" says fewer.
|
||||
import { beforeAll, expect, test } from "bun:test"
|
||||
import { goalCheck } from "../src/run.ts"
|
||||
import { CLIP, project, put } from "./project.ts"
|
||||
import { readFileSync } from "node:fs"
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.RAEA_REAL = "/usr/bin/false"
|
||||
delete process.env.RAEA_CLOUD_GPU_URL
|
||||
})
|
||||
const off = { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, captions: false, voice: false, reading: false, montage: false, quotes: false, count: false, open: false, say: false, never: false, cta: false, shape: false }
|
||||
const contract = (open: unknown[] = []) => ({ kind: "cut", packs: off, cut: { brief: "media/brief.txt", formats: ["9:16", "4:5", "1:1"], cuts: [{ id: "a1" }], open } })
|
||||
const clip = readFileSync(CLIP)
|
||||
const all = async (open: unknown[] = [], files: string[]) => {
|
||||
const d = project(contract(open))
|
||||
put(d, "media/brief.txt", "Deliver 9:16, 4:5 and 1:1.\n")
|
||||
for (const f of files) put(d, f, clip)
|
||||
const r = await goalCheck({ cwd: d, at: "done" })
|
||||
return r.findings.filter((x) => /sizes/.test(x.check))
|
||||
}
|
||||
|
||||
test("done on the first size alone: every other size the brief names is missing", async () => {
|
||||
const f = await all([], ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4", "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4"])
|
||||
expect(f.some((x) => /v2 is in 9x16 .* 4x5, 1x1 not made/.test(x.says))).toBe(true)
|
||||
})
|
||||
|
||||
test("every size of the newest version passes; a person's answer can say fewer", async () => {
|
||||
const sizes = ["9x16", "4x5", "1x1"].map((s) => `out/cuts/dutch_vetbill_hooka_v2_${s}.mp4`)
|
||||
const answered = [{ question: "Which sizes?", from: "Deliver 9:16, 4:5 and 1:1.", about: "sizes", answer: "9:16 only for now", by: "shane" }]
|
||||
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
|
||||
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
|
||||
})
|
||||
@@ -20,6 +20,7 @@
|
||||
"./cutout": "./src/cutout.ts",
|
||||
"./adjust": "./src/adjust.ts",
|
||||
"./words": "./src/words.tsx",
|
||||
"./airgaps": "./src/airgaps.ts",
|
||||
"./region": "./src/region.tsx",
|
||||
"./overlay": "./src/overlay.tsx",
|
||||
"./panel": "./src/panel.ts",
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Air gaps: the silences between words, measured and cut safely (11-30, Shane: "measuring and cutting air gaps safely
|
||||
// would be good, especially in a hook. It CANNOT destroy words as sometimes air gaps can, but generally having an
|
||||
// automated air gap cleanup would be solid ... for social media content or ads, especially if it is at all trying to look
|
||||
// organic").
|
||||
//
|
||||
// airGaps(words) every gap between words, with how long it is and whether it's in the hook
|
||||
// tighten(words, options) the spans of the source to keep: each gap longer than allowed cut down to `pad` either side
|
||||
// of its words, the lead-in before the first word too
|
||||
//
|
||||
// What keeps a word whole: a cut lies only between two words, never closer than `pad` to either; words that overlap or
|
||||
// touch are never cut between; and with `levels` (the take's level every 10 ms, raea goal's levels()), each cut is pulled
|
||||
// in from either end until it's quiet there, `quiet` dB under the speech, because a transcript's word ends are often
|
||||
// early (a trailing "s", a breath into the next word) and that's how a cut clips a word.
|
||||
|
||||
/** a word as raea words writes it (start_ms, end_ms) or as seconds (start, end) */
|
||||
export type GapWord = { text: string; start?: number; end?: number; start_ms?: number; end_ms?: number }
|
||||
export type Span = { from: number; to: number }
|
||||
export type Gap = Span & { seconds: number; hook: boolean; after: string; before: string }
|
||||
|
||||
export interface TightenOptions {
|
||||
/** the longest gap left as it is, in the body (s): 0.25 by default, the pace of an edited social cut */
|
||||
gap?: number
|
||||
/** the hook's first seconds, where gaps are held tighter (s): 3 */
|
||||
hook?: number
|
||||
/** the longest gap left in the hook (s): 0.15 */
|
||||
hookGap?: number
|
||||
/** what's kept either side of a cut, so a word's onset and tail stay whole (s): 0.08 */
|
||||
pad?: number
|
||||
/** the shortest cut worth making (s): 0.06 */
|
||||
least?: number
|
||||
/** cut the silence before the first word down to `pad`: true (a hook starts on its first word) */
|
||||
lead?: boolean
|
||||
/** the source's level every 10 ms (dB): a cut ends where the sound is still within `quiet` dB of the speech */
|
||||
levels?: number[]
|
||||
/** how far under the speech counts as quiet (dB): 18 */
|
||||
quiet?: number
|
||||
}
|
||||
|
||||
const secs = (w: GapWord, k: "start" | "end") => (typeof w[k] === "number" ? (w[k] as number) : ((w[`${k}_ms`] as number | undefined) ?? 0) / 1000)
|
||||
|
||||
/** the words in time order, as seconds */
|
||||
function timed(words: readonly GapWord[]) {
|
||||
return words.map((w) => ({ text: w.text, start: secs(w, "start"), end: secs(w, "end") })).filter((w) => w.end > w.start).sort((a, b) => a.start - b.start)
|
||||
}
|
||||
|
||||
/** every gap between two words (and the lead-in before the first), longest first not implied: in time order */
|
||||
export function airGaps(words: readonly GapWord[], hook = 3): Gap[] {
|
||||
const w = timed(words)
|
||||
const out: Gap[] = []
|
||||
if (w.length && w[0].start > 0) out.push({ from: 0, to: w[0].start, seconds: w[0].start, hook: true, after: "", before: w[0].text })
|
||||
for (let i = 1; i < w.length; i++) {
|
||||
const from = w[i - 1].end, to = w[i].start
|
||||
if (to > from) out.push({ from, to, seconds: to - from, hook: from < hook, after: w[i - 1].text, before: w[i].text })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const pct = (xs: number[], q: number) => {
|
||||
if (!xs.length) return -100
|
||||
const s = [...xs].sort((a, b) => a - b)
|
||||
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
|
||||
}
|
||||
|
||||
/** the spans of the source to keep, and the cuts that make them; `saved` is the seconds taken out */
|
||||
export function tighten(words: readonly GapWord[], o: TightenOptions = {}): { keep: Span[]; cuts: Span[]; saved: number } {
|
||||
const { gap = 0.25, hook = 3, hookGap = 0.15, pad = 0.08, least = 0.06, lead = true, levels, quiet = 18 } = o
|
||||
const w = timed(words)
|
||||
if (!w.length) return { keep: [], cuts: [], saved: 0 }
|
||||
const end = w[w.length - 1].end + pad
|
||||
// the speech's level: its loud end, over the words
|
||||
const speech = levels ? pct(w.flatMap((x) => levels.slice(Math.floor(x.start * 100), Math.ceil(x.end * 100))), 0.8) : 0
|
||||
const loud = (t: number) => !!levels && (levels[Math.floor(t * 100)] ?? -100) > speech - quiet
|
||||
const cuts: Span[] = []
|
||||
const cut = (a: number, b: number) => {
|
||||
// pulled in from either end while it's still loud there (a word the transcript ended early)
|
||||
if (levels) {
|
||||
while (a < b && loud(a)) a += 0.01
|
||||
while (b > a && loud(b - 0.01)) b -= 0.01
|
||||
}
|
||||
if (b - a >= least) cuts.push({ from: +a.toFixed(3), to: +b.toFixed(3) })
|
||||
}
|
||||
if (lead && w[0].start - pad > 0) cut(0, w[0].start - pad)
|
||||
for (let i = 1; i < w.length; i++) {
|
||||
const a = w[i - 1].end, b = w[i].start
|
||||
// what's left of the gap: the allowed gap, never less than a pad on each word
|
||||
const left = Math.max(a < hook ? hookGap : gap, 2 * pad)
|
||||
if (b - a > left) cut(a + left / 2, b - left / 2)
|
||||
}
|
||||
const keep: Span[] = []
|
||||
let at = 0
|
||||
for (const c of cuts) {
|
||||
if (c.from > at) keep.push({ from: +at.toFixed(3), to: c.from })
|
||||
at = c.to
|
||||
}
|
||||
if (end > at) keep.push({ from: +at.toFixed(3), to: +end.toFixed(3) })
|
||||
return { keep, cuts, saved: +cuts.reduce((n, c) => n + c.to - c.from, 0).toFixed(3) }
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export * from "./nudge";
|
||||
export * from "./speed";
|
||||
export * from "./transition";
|
||||
export * from "./words";
|
||||
export * from "./airgaps";
|
||||
export * from "./region";
|
||||
export * from "./overlay";
|
||||
export * from "./panel";
|
||||
@@ -0,0 +1,20 @@
|
||||
//! The default mix (DEFAULT_GRAPH): a bus-less music file ducks DEFAULT_DUCK_DB under talking, then comes back (two bounces' difference).
|
||||
use crate::{RATE, Sound, offline::Cue};
|
||||
|
||||
#[test]
|
||||
fn music_ducks_under_the_talking_by_default() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-mixer-test-duck-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap();
|
||||
let tone = |name: &str, hz: f32| {
|
||||
let ch: Vec<f32> = (0..6 * RATE as usize).map(|i| 0.5 * (i as f32 * hz * std::f32::consts::TAU / RATE as f32).sin()).collect();
|
||||
crate::write_wav(&raea_io_media::Audio { rate: RATE, channels: vec![ch.clone(), ch] }, &dir.join(name)).unwrap();
|
||||
dir.join(name)
|
||||
};
|
||||
let (song, talk) = (tone("song.wav", 220.0), tone("interview_voice.wav", 990.0));
|
||||
let s = |k: &str, f: &std::path::Path, at: i64| Sound { key: k.into(), file: f.into(), at: at as f64 / 30.0, volume: 0.25, rate: 1.0, fade_in: 0.0, fade_out: 0.0, bus: None };
|
||||
let cues = |song_on: bool| -> Vec<Cue> { (0..150).map(|f| Cue { sounds: [song_on.then(|| s("song", &song, f)), (45..105).contains(&f).then(|| s("talk", &talk, f - 45))].into_iter().flatten().collect(), ..Default::default() }).collect() };
|
||||
let (both, alone) = (crate::offline::bounce_raw(&cues(true), 30.0).unwrap(), crate::offline::bounce_raw(&cues(false), 30.0).unwrap());
|
||||
let db = |a: f64, b: f64| { let r = (a * RATE as f64) as usize..(b * RATE as f64) as usize; let n = r.len() as f64; 10.0 * (r.map(|k| ((both.channels[0][k] - alone.channels[0].get(k).copied().unwrap_or(0.0)) as f64).powi(2)).sum::<f64>() / n).log10() };
|
||||
let (before, under, after) = (db(0.5, 1.4), db(2.2, 3.3), db(4.3, 4.9));
|
||||
assert!((under - before - crate::DEFAULT_DUCK_DB).abs() < 1.5, "the music under the talk is {:.1} dB from before it", under - before);
|
||||
assert!((after - before).abs() < 1.0, "the music came back to {:.1} dB from before", after - before);
|
||||
}
|
||||
@@ -12,6 +12,8 @@ pub mod live;
|
||||
pub mod nodes;
|
||||
pub mod offline;
|
||||
pub mod score;
|
||||
#[cfg(test)]
|
||||
mod duck_test;
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
@@ -60,6 +62,7 @@ impl ToneCue {
|
||||
}
|
||||
}
|
||||
|
||||
pub use raea_sys_tone::defaults::{DEFAULT_DUCK_DB, DEFAULT_GRAPH, default_bus};
|
||||
/// A source a Tone graph names (a Sampler's sample, a Player's file), opened whole: it's short, and the audio thread
|
||||
/// never waits for its blocks.
|
||||
pub fn open_whole(file: &str) -> Option<std::sync::Arc<raea_io_media::pcm::Pcm>> {
|
||||
|
||||
@@ -278,8 +278,8 @@ impl Live {
|
||||
}
|
||||
}
|
||||
// the edit's Tone graph, built the first frame it shows (and again if it changes)
|
||||
if let Some(g) = &tone.graph
|
||||
&& raea_sys_tone::tonegraph::hash(g) != self.built.hash
|
||||
let g = tone.graph.as_ref().unwrap_or(&crate::DEFAULT_GRAPH);
|
||||
if raea_sys_tone::tonegraph::hash(g) != self.built.hash
|
||||
{
|
||||
self.built.tear_down(&mut self.cx, self.voices);
|
||||
match raea_sys_tone::tonegraph::build(&mut self.cx, self.voices, self.master, g, origin, &mut |f| crate::open_whole(f)) {
|
||||
@@ -294,7 +294,7 @@ impl Live {
|
||||
evs.extend(score.chunk(f, a));
|
||||
}
|
||||
if let Some(a) = &tone.speech {
|
||||
evs.extend(score.chunk_on(f, a, self.built.bus_port.get("voice").copied().unwrap_or(0)));
|
||||
evs.extend(score.chunk_on(f, a, self.built.bus_port.get("voice").or(self.built.bus_port.get("talk")).copied().unwrap_or(0)));
|
||||
}
|
||||
let tone_evs = score.tone(f, &self.built, &tone.evs);
|
||||
for (t, ev) in evs {
|
||||
|
||||
@@ -64,8 +64,8 @@ impl Engine {
|
||||
let pcms = &mut self.pcms;
|
||||
let items: Vec<(Sound, Arc<Pcm>)> = cue.sounds.iter().filter_map(|s| pcms.entry(s.file.to_path_buf()).or_insert_with(|| Pcm::open(&s.file, true)).clone().map(|p| (s.clone(), p))).collect();
|
||||
// the edit's Tone graph, built the first frame it shows (and again if it changes)
|
||||
if let Some(g) = &cue.tone.graph
|
||||
&& raea_sys_tone::tonegraph::hash(g) != self.built.hash
|
||||
let g = cue.tone.graph.as_ref().unwrap_or(&crate::DEFAULT_GRAPH);
|
||||
if raea_sys_tone::tonegraph::hash(g) != self.built.hash
|
||||
{
|
||||
self.built.tear_down(&mut self.cx, self.voices);
|
||||
self.built = raea_sys_tone::tonegraph::build(&mut self.cx, self.voices, self.master, g, origin, &mut |f| crate::open_whole(f))?;
|
||||
@@ -75,7 +75,7 @@ impl Engine {
|
||||
evs.extend(self.score.chunk(f, a));
|
||||
}
|
||||
if let Some(a) = &cue.tone.speech {
|
||||
evs.extend(self.score.chunk_on(f, a, self.built.bus_port.get("voice").copied().unwrap_or(0)));
|
||||
evs.extend(self.score.chunk_on(f, a, self.built.bus_port.get("voice").or(self.built.bus_port.get("talk")).copied().unwrap_or(0)));
|
||||
}
|
||||
for (t, ev) in evs {
|
||||
self.cx.schedule_event_for(self.voices, event(ev), Some(EventInstant::AtClockSamples(InstantSamples(origin + t))));
|
||||
|
||||
@@ -143,7 +143,8 @@ impl Score {
|
||||
let fade_in = if s.fade_in < 0.0 { 0 } else if first && s.fade_in > 0.0 { self.samples(s.fade_in) } else { edge };
|
||||
let id = self.next;
|
||||
self.next += 1;
|
||||
let port = s.bus.as_ref().and_then(|b| buses.get(&**b)).copied().unwrap_or(0);
|
||||
// a sound with no bus takes the default mix's (crate::default_bus), which only the default graph has
|
||||
let port = match s.bus.as_deref() { Some(b) => buses.get(b).copied(), None => crate::default_bus(&s.file).and_then(|b| buses.get(b)).copied() }.unwrap_or(0);
|
||||
out.push((t, Ev::Start { id, pcm: pcm.clone(), at: s.at, rate: s.rate, gain: s.volume, fade_in, port }));
|
||||
self.runs.insert(k.to_string(), Run { id, pcm: pcm.clone(), f, at: s.at, rate: s.rate, volume: s.volume, fade_out: s.fade_out });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! The mix an edit gets when it writes no Tone graph of its own (raea-sys-mix routes bus-less sounds by it).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// How far the default mix ducks a music file under the talking (dB): slight, enough that the voice sits on top
|
||||
/// (11-30, Shane: the StreetTalk cuts' music was "about 4 or 5 decibels too loud ... move audio down in the mix
|
||||
/// especially while talking, but a CTA or something with no audio, that's fine"). It lets go where nobody talks.
|
||||
pub const DEFAULT_DUCK_DB: f64 = -6.0;
|
||||
|
||||
/// The mix an edit gets when it writes no Tone graph of its own: a `talk` bus (footage and voice files) and a `bed` bus
|
||||
/// (music files) ducked DEFAULT_DUCK_DB under it, both at unity; effects stay on the master. The names aren't
|
||||
/// raea/tone's (music, voice), so an edit's own buses are never changed by it, and `bus="master"` (any name no bus has)
|
||||
/// keeps a sound out of it.
|
||||
pub static DEFAULT_GRAPH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
|
||||
format!(
|
||||
r#"{{"nodes":[{{"id":0,"kind":"Destination","options":{{"volume":0}}}},{{"id":1,"kind":"Channel","name":"bed","options":{{"volume":0,"pan":0,"duck":{{"amount":{DEFAULT_DUCK_DB},"threshold":-42,"attack":0.08,"release":0.45}}}}}},{{"id":2,"kind":"Channel","name":"talk","options":{{"volume":0,"pan":0}}}}],"edges":[[1,0,0],[2,0,0],[2,1,1]]}}"#
|
||||
)
|
||||
});
|
||||
|
||||
/// Whether `hay` holds any of `needles`, ignoring ASCII case, without allocating (the live mixer calls it each frame)
|
||||
fn has_any(hay: &str, needles: &[&str]) -> bool {
|
||||
let h = hay.as_bytes();
|
||||
needles.iter().any(|n| h.windows(n.len()).any(|w| w.eq_ignore_ascii_case(n.as_bytes())))
|
||||
}
|
||||
|
||||
/// The default mix's bus for a sound with none (DEFAULT_GRAPH): footage (a video file: the people on screen talking) and
|
||||
/// a voice file (vo, voice, narration, dialogue, speech in its name) on `talk`; an effect (sfx, foley, whoosh, sting,
|
||||
/// riser, hit) on the master; any other audio file, the music, on `bed`.
|
||||
pub fn default_bus(file: &Path) -> Option<&'static str> {
|
||||
let name = file.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
|
||||
if ["mp4", "mov", "m4v", "webm", "mkv", "avi", "mxf"].iter().any(|e| ext.eq_ignore_ascii_case(e)) {
|
||||
return Some("talk");
|
||||
}
|
||||
if has_any(name, &["voice", "narrat", "dialog", "speech", "_vo", "vo_", "-vo", "vo-", "interview"]) {
|
||||
return Some("talk");
|
||||
}
|
||||
if has_any(name, &["sfx", "foley", "whoosh", "swoosh", "sting", "riser", "impact", "click", "_fx", "fx_"]) {
|
||||
return None;
|
||||
}
|
||||
Some("bed")
|
||||
}
|
||||
@@ -7,3 +7,4 @@ pub mod dsp;
|
||||
pub mod fx;
|
||||
pub mod tone;
|
||||
pub mod tonegraph;
|
||||
pub mod defaults;
|
||||
Reference in new issue
Block a user