Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4d0b18920 | ||
|
|
bd8ead7ef9 | ||
|
|
3fd491c839 | ||
|
|
93bf3dc325 | ||
|
|
5753f4048a | ||
|
|
841bfa7d06 | ||
|
|
0ffb6a576b | ||
|
|
5656144a9f | ||
|
|
3b16d1e254 | ||
|
|
dff58e6b88 | ||
|
|
ef06093d56 | ||
|
|
8582a0219d |
@@ -4,6 +4,21 @@ All notable changes to ComfyUI-AusBoss are documented here.
|
||||
|
||||
## Unreleased
|
||||
|
||||
- **New example: Pika H3 Flex.** One MiniMax H3 workflow for pictures,
|
||||
video and sound. Give each picture a job on H3 Prompt Writer, or switch on
|
||||
Video to swap someone into a clip or copy its moves. Keep the clip's sound
|
||||
carries the clip's own words and music through a swap, and lets them steer
|
||||
the mouths. Video swaps stop at 10 seconds and come out at about 480p,
|
||||
where they hold best. Voice and Song use the new Load Audio node.
|
||||
- **H3 Prompt Writer swaps two people.** With Swap the person and two person
|
||||
pictures, Picture 1 takes the place of the person on the left and Picture 2
|
||||
the person on the right. Type who goes to change that, one line each, such
|
||||
as `@1 the man in the hat` and `@2 the woman in red`.
|
||||
- **New node: Load Audio.** Load a sound file and keep only the part you
|
||||
want. The node shows the sound as a wave: drag the IN and OUT handles to
|
||||
trim it, and press play to hear just that part. Set Max length to the
|
||||
longest sound the next step takes, and anything longer shows in red as
|
||||
cut off, so you see exactly what comes out before you run.
|
||||
- **Resizing one node of a selection now resizes them all.** With two or more
|
||||
nodes selected, pull the edge or corner of one: nodes stacked in a column
|
||||
get its width, nodes side by side in a row get its height, and a grid gets
|
||||
|
||||
@@ -162,6 +162,12 @@ Upload a video, or pick one from the Source list, which plays the clip under the
|
||||
|
||||
It returns the frames, audio, frame count, fps, width, height, duration and a core `VIDEO`. Only the part you kept is decoded, and it checks memory before a large load. When you save the frames, wire its fps into the save node.
|
||||
|
||||
### Load Audio
|
||||
|
||||
Upload a sound file, or pick one from the Source list, and the node shows it as a wave. Drag the IN and OUT handles to keep only the part you want, or type the times. Press play to hear just that part. Set **Max length** to the longest sound the next step can take, such as a video's length: anything past it turns red and is cut off, so you see what comes out before you run. Click the red length next to OUT to move OUT to the cut.
|
||||
|
||||
It returns the `audio` you kept and its length in `seconds`. Only that part is decoded. [Help page](js/docs/AUSBOSS_NODES_LoadAudio.md).
|
||||
|
||||
### Video Crop + Rotate + Pad → Frame
|
||||
|
||||
Picks one frame from a video, then gives you the same rotate, crop and pad controls as the image node, plus an optional megapixel resize. Scrub to the frame with the playhead on the node; the editor adds frame-by-frame stepping and playback. It returns the transformed `image`, a `mask` of the added area, a `stitcher`, the chosen `original` frame, and the output `width` and `height`. For a whole clip, use the Clip version below.
|
||||
|
||||
@@ -36,6 +36,7 @@ NODE_MODULES = [
|
||||
"node_layout_boxes",
|
||||
"node_literals",
|
||||
"node_load_image_pad",
|
||||
"node_load_audio",
|
||||
"node_load_video",
|
||||
"node_lora_loader",
|
||||
"node_mask_by_name",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,52 @@
|
||||
# Load Audio
|
||||
|
||||
Loads a sound file and hands on only the part you pick. Use it for a voice
|
||||
clip, a song or any sound a video model or a save node takes, when you want
|
||||
one part of the file and not the whole thing.
|
||||
|
||||
The node shows the whole file as a wave, so you can see where the loud parts
|
||||
are. The part that comes out is bright. Drag the white **IN** and **OUT**
|
||||
handles to set where it starts and stops, drag the bright part to slide it,
|
||||
or click somewhere else on the wave to move it there. You can also type a time
|
||||
under the wave, in seconds (`12.5`) or minutes and seconds (`1:02.5`).
|
||||
|
||||
Press **▶** to hear only the part that comes out. **LOOP** plays it again and
|
||||
again.
|
||||
|
||||
## Max length
|
||||
|
||||
Set **Max length** to the longest sound the next step can take, such as the
|
||||
length of the video you are making. The start stays where it is, and anything
|
||||
past the limit turns red with a dashed line where it is cut. Next to OUT,
|
||||
the node shows how long the sound that comes out is, such as `15.0 s`. It
|
||||
turns red when part of your pick is cut; hold the mouse over it to see how
|
||||
much, and click it to move OUT to the cut. Play stops at the cut, so what you
|
||||
hear is what comes out. `0` means no limit.
|
||||
|
||||
Max length can be wired. When the wire comes from a number node such as
|
||||
Float 🆎, the wave shows the cut for that number; otherwise the length's tooltip says
|
||||
`max wired` and the run still cuts the sound to the wired length.
|
||||
|
||||
## Controls
|
||||
|
||||
- **Source** (`audio`): a sound file in ComfyUI's input folder. **Upload**
|
||||
adds one. Videos are listed as well, for their sound.
|
||||
- **Max length** (`max_seconds`): the longest the sound may be, in seconds.
|
||||
`0` means no limit.
|
||||
- **IN** (`start_seconds`): where the sound starts.
|
||||
- **OUT** (`end_seconds`): where the sound stops. `0` means the end of the
|
||||
file.
|
||||
|
||||
## Outputs
|
||||
|
||||
- `audio`: the part you picked, for any node that takes `AUDIO`.
|
||||
- `seconds`: how long that sound is.
|
||||
|
||||
## Technical details
|
||||
|
||||
- Only the picked part is decoded: decoding stops once the window is full,
|
||||
so a short pick from a long recording stays quick.
|
||||
- The sound keeps its own sample rate and channels.
|
||||
- A start past the end of the file stops the run with a message that says so.
|
||||
- The wave is drawn in the browser from the file itself; nothing extra is
|
||||
stored with the workflow besides the four values above.
|
||||
@@ -33,6 +33,7 @@ help panel.
|
||||
| Apply a stack of LoRAs | LoRA Loader (`AUSBOSS_NODES_LoraLoader`) |
|
||||
| Krea 2 prompt, and Krea 2 outpainting | Krea 2 Encode (`AUSBOSS_NODES_Krea2Encode`), Krea 2 Outpaint Model Patch (`AUSBOSS_NODES_Krea2OutpaintModelPatch`) |
|
||||
| Load or save a video | Load Video (`AUSBOSS_NODES_LoadVideo`), Save Video (`AUSBOSS_NODES_SaveVideo`) |
|
||||
| Load a sound file and keep only part of it, up to a set length | Load Audio (`AUSBOSS_NODES_LoadAudio`) |
|
||||
| Turn, crop and pad a video: one frame, or the whole clip | Video Crop + Rotate + Pad → Frame (`AUSBOSS_NODES_VideoCropRotatePad`), → Clip (`AUSBOSS_NODES_VideoCropRotatePadClip`) |
|
||||
| Change a clip's frame rate | Frame Interpolate (`AUSBOSS_NODES_FrameInterpolate`) |
|
||||
| Work with frame batches | Select Frame, Select Every Nth, Split Batch, Merge Batches (`AUSBOSS_NODES_SelectFrame`, `_SelectEveryNth`, `_SplitBatch`, `_MergeBatches`) |
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Load Audio's window rules for the face, mirroring audio_window in
|
||||
// nodes/_audio_trim_helpers.py so the wave shows exactly what one Run hands
|
||||
// on. Pure: tests/load_audio_window.test.mjs runs it without a browser.
|
||||
|
||||
function finite(value, fallback = 0) {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : fallback;
|
||||
}
|
||||
|
||||
// The pick, and what comes out of it. `end` 0 means "to the end of the
|
||||
// file". A max above 0 keeps the start and cuts off anything past
|
||||
// start + max. All times in seconds; duration is the file's length.
|
||||
export function outputWindow(durationValue, startValue, endValue, maxValue = 0) {
|
||||
const duration = Math.max(0, finite(durationValue));
|
||||
const start = Math.min(Math.max(0, finite(startValue)), duration);
|
||||
const pickedEnd = finite(endValue) > 0 ? Math.min(finite(endValue), duration) : duration;
|
||||
const end = Math.max(start, pickedEnd);
|
||||
const max = Math.max(0, finite(maxValue));
|
||||
const keepEnd = max > 0 && end - start > max ? Math.min(duration, start + max) : end;
|
||||
return { start, end, keepEnd, length: keepEnd - start, cut: Math.max(0, end - keepEnd) };
|
||||
}
|
||||
|
||||
// "0:12.0" style, the way the IN and OUT fields write a time.
|
||||
export function secondsLabel(value) {
|
||||
const seconds = Math.max(0, finite(value));
|
||||
if (seconds < 60) return `${seconds.toFixed(1)} s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${minutes}:${(seconds - minutes * 60).toFixed(1).padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
// The line between IN and OUT: what comes out, and what the max cuts off.
|
||||
export function outputSummary(window, { maxFromLink = false } = {}) {
|
||||
if (!window || window.length <= 0) return "";
|
||||
const parts = [secondsLabel(window.length)];
|
||||
if (window.cut > 0.005) parts.push(`cut ${secondsLabel(window.cut)}`);
|
||||
if (maxFromLink) parts.push("max wired");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
// Loud and quiet across the file: for each of `buckets` slices, the lowest
|
||||
// and highest sample of the channels mixed down. Channel data is a list of
|
||||
// Float32Arrays (AudioBuffer.getChannelData). Returns a Float32Array of
|
||||
// [min0, max0, min1, max1, ...].
|
||||
export function wavePeaks(channels, bucketsValue = 1200) {
|
||||
const list = Array.isArray(channels) ? channels.filter(Boolean) : [];
|
||||
const buckets = Math.max(1, Math.floor(finite(bucketsValue, 1200)));
|
||||
const peaks = new Float32Array(buckets * 2);
|
||||
const length = list.length ? list[0].length : 0;
|
||||
if (!length) return peaks;
|
||||
const count = list.length;
|
||||
for (let bucket = 0; bucket < buckets; bucket += 1) {
|
||||
const from = Math.floor((bucket * length) / buckets);
|
||||
const to = Math.max(from + 1, Math.floor(((bucket + 1) * length) / buckets));
|
||||
let low = 0;
|
||||
let high = 0;
|
||||
for (let index = from; index < to && index < length; index += 1) {
|
||||
let sample = 0;
|
||||
for (let channel = 0; channel < count; channel += 1) sample += list[channel][index] || 0;
|
||||
sample /= count;
|
||||
if (sample < low) low = sample;
|
||||
if (sample > high) high = sample;
|
||||
}
|
||||
peaks[bucket * 2] = low;
|
||||
peaks[bucket * 2 + 1] = high;
|
||||
}
|
||||
return peaks;
|
||||
}
|
||||
|
||||
// Which part of the wave a press at `fraction` (0..1 across it) grabs: a
|
||||
// handle within `hitPixels` of it, the inside of the pick to slide it, or
|
||||
// "jump" to move the pick there.
|
||||
export function grabZone(window, durationValue, fraction, widthValue, hitPixels = 10) {
|
||||
const duration = Math.max(0, finite(durationValue));
|
||||
const width = Math.max(0, finite(widthValue));
|
||||
if (duration <= 0 || width <= 0) return "none";
|
||||
const x = Math.min(1, Math.max(0, finite(fraction))) * width;
|
||||
const startX = (window.start / duration) * width;
|
||||
const endX = (window.end / duration) * width;
|
||||
const toStart = Math.abs(x - startX);
|
||||
const toEnd = Math.abs(x - endX);
|
||||
if (Math.min(toStart, toEnd) <= hitPixels) return toStart <= toEnd ? "start" : "end";
|
||||
if (x > startX && x < endX) return "move";
|
||||
return "jump";
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
// Load Audio 🆎 - the wave, the trim and the player.
|
||||
//
|
||||
// The card above (js/widget_cards) holds Source and Max length. This panel
|
||||
// draws the whole file as a wave: the part that comes out is bright, the
|
||||
// part a Max length cuts off is red, and the rest is dim. Drag a handle to
|
||||
// move IN or OUT, drag the middle to slide the pick, or click elsewhere to
|
||||
// move it there. Play plays only what comes out. The widgets underneath
|
||||
// (start_seconds, end_seconds, max_seconds) stay the source of truth.
|
||||
import { api } from "/scripts/api.js";
|
||||
import { app } from "/scripts/app.js";
|
||||
import { BRAND, chainCallback, keepDomWidgetWidthAuto, notifyAusbossChange } from "../shared/index.mjs";
|
||||
import { keepKeyInField } from "../shared/canvas_passthrough.mjs";
|
||||
import { WIDGET_FRAME, fillNodeHeight } from "../shared/panel_layout.mjs";
|
||||
import { formatTimecode, parseTimecode } from "../shared/timecode.mjs";
|
||||
import { parseImageReference } from "../shared/pad_canvas.mjs";
|
||||
import { mediaViewQuery, splitMediaName } from "../shared/video_preview.mjs";
|
||||
import { ensureVideoCss, hideCanvasWidget, makeToolButton } from "../shared/video_ui.mjs";
|
||||
import { MIN_TRIM_SECONDS, dragTrimHandle, slideTrimWindow } from "../load_video/trim_preview.mjs";
|
||||
import { grabZone, outputSummary, outputWindow, secondsLabel, wavePeaks } from "./audio_window.mjs";
|
||||
|
||||
const NODE_NAME = "AUSBOSS_NODES_LoadAudio";
|
||||
const PANEL_WIDGET = "ausboss_load_audio_wave";
|
||||
// The frontend's own player for an audio_upload input. The wave replaces it.
|
||||
const CORE_AUDIO_WIDGET = "audioUI";
|
||||
const MIN_WIDTH = 280;
|
||||
// 8px root padding + the wave's 28px floor + 6px gap + the 22px play, IN/OUT and loop row.
|
||||
const PANEL_MIN_HEIGHT = 64;
|
||||
// Opens small and neat: 300 px wide, with a wave about as tall as a field
|
||||
// (32 px). Drag the corner down for a taller wave.
|
||||
const DEFAULT_WIDTH = 300;
|
||||
const DEFAULT_WAVE_EXTRA = 4;
|
||||
const CUT_RED = "#e0525a";
|
||||
const PEAK_BUCKETS = 1600;
|
||||
const END_EPSILON = 0.03;
|
||||
|
||||
// Decoded once per file and kept small: only the peaks and the length.
|
||||
const peakCache = new Map();
|
||||
|
||||
function findWidget(node, name) {
|
||||
return node.widgets?.find((widget) => widget.name === name);
|
||||
}
|
||||
|
||||
function roundHundredth(value) {
|
||||
return Math.round(Number(value || 0) * 100) / 100;
|
||||
}
|
||||
|
||||
function hideCoreAudio(node) {
|
||||
for (const widget of node.widgets ?? []) {
|
||||
if (widget?.name === CORE_AUDIO_WIDGET) hideCanvasWidget(widget, widget.element);
|
||||
}
|
||||
}
|
||||
|
||||
// A wired Max length: the number the wire carries, when the far end is a
|
||||
// node that shows it (Float, Integer, a Primitive). null when it can't be known.
|
||||
function wiredMax(node) {
|
||||
const input = node.inputs?.find((slot) => slot?.widget?.name === "max_seconds");
|
||||
if (!input || input.link == null) return { wired: false, value: null };
|
||||
const graph = node.graph;
|
||||
const link = graph?.getLink?.(input.link) ?? graph?.links?.get?.(input.link) ?? graph?.links?.[input.link];
|
||||
const origin = link ? graph?.getNodeById?.(link.origin_id) : null;
|
||||
const shown = origin?.widgets?.find((widget) => typeof widget?.value === "number");
|
||||
return { wired: true, value: shown ? Number(shown.value) : null };
|
||||
}
|
||||
|
||||
function maxSeconds(state) {
|
||||
const wired = wiredMax(state.node);
|
||||
if (wired.wired) return { value: wired.value ?? 0, fromLink: true, known: wired.value != null };
|
||||
return { value: Number(state.maxWidget?.value) || 0, fromLink: false, known: true };
|
||||
}
|
||||
|
||||
function currentWindow(state) {
|
||||
return outputWindow(state.duration, state.startWidget.value, state.endWidget.value, maxSeconds(state).value);
|
||||
}
|
||||
|
||||
async function loadPeaks(name, route) {
|
||||
const key = name;
|
||||
if (peakCache.has(key)) return peakCache.get(key);
|
||||
const job = (async () => {
|
||||
const response = await api.fetchApi(route, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`the file could not be read (${response.status})`);
|
||||
const bytes = await response.arrayBuffer();
|
||||
const Context = window.AudioContext || window.webkitAudioContext;
|
||||
const context = new Context();
|
||||
try {
|
||||
const buffer = await context.decodeAudioData(bytes);
|
||||
const channels = [];
|
||||
for (let index = 0; index < buffer.numberOfChannels; index += 1) channels.push(buffer.getChannelData(index));
|
||||
return { duration: buffer.duration, peaks: wavePeaks(channels, PEAK_BUCKETS) };
|
||||
} finally {
|
||||
context.close?.();
|
||||
}
|
||||
})();
|
||||
peakCache.set(key, job);
|
||||
job.catch(() => peakCache.delete(key));
|
||||
return job;
|
||||
}
|
||||
|
||||
function ensureAudioCss() {
|
||||
ensureVideoCss();
|
||||
if (document.getElementById("ausboss-load-audio-css")) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = "ausboss-load-audio-css";
|
||||
style.textContent = `
|
||||
.ausboss-audio-root .ausboss-video-stage{min-height:28px;background:#050b0b;cursor:pointer;touch-action:none;}
|
||||
.ausboss-audio-root canvas.ausboss-audio-wave{position:absolute;inset:0;width:100%;height:100%;display:block;}
|
||||
.ausboss-audio-root .ausboss-video-stage:not(.is-empty) .ausboss-video-status{display:none;}
|
||||
.ausboss-audio-root .ausboss-audio-row{display:flex;align-items:center;gap:6px;flex:none;padding:0 2px;}
|
||||
.ausboss-audio-root .ausboss-audio-row .ausboss-video-values{flex:1 1 auto;min-width:0;}
|
||||
.ausboss-audio-root .ausboss-audio-play{min-width:30px;font-size:10px;}
|
||||
.ausboss-audio-root .ausboss-audio-length{flex:none;padding:0 2px;color:#7fd9d2;font-size:10px;font-variant-numeric:tabular-nums;white-space:nowrap;cursor:default;}
|
||||
.ausboss-audio-root .ausboss-audio-length:empty{display:none;}
|
||||
.ausboss-audio-root .ausboss-audio-length.has-cut{color:#ff9aa0;cursor:pointer;text-decoration:underline dotted rgba(224,82,90,.8);text-underline-offset:2px;}
|
||||
.ausboss-audio-root .ausboss-audio-row .ausboss-video-tool{flex:none;}
|
||||
.ausboss-audio-root .ausboss-video-values{display:flex;gap:8px;}
|
||||
.ausboss-audio-root .ausboss-video-value input{width:48px;}
|
||||
.ausboss-audio-root .ausboss-audio-length{margin-left:auto;}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function draw(state) {
|
||||
const { canvas } = state;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const scale = window.devicePixelRatio || 1;
|
||||
const width = Math.max(1, Math.round(rect.width * scale));
|
||||
const height = Math.max(1, Math.round(rect.height * scale));
|
||||
if (canvas.width !== width || canvas.height !== height) {
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
if (!state.peaks || state.duration <= 0) return;
|
||||
const win = currentWindow(state);
|
||||
const xOf = (seconds) => (seconds / state.duration) * width;
|
||||
const startX = xOf(win.start);
|
||||
const keepX = xOf(win.keepEnd);
|
||||
const endX = xOf(win.end);
|
||||
// Backdrops: the part that comes out, then the part cut off.
|
||||
ctx.fillStyle = "rgba(0,180,170,0.13)";
|
||||
ctx.fillRect(startX, 0, keepX - startX, height);
|
||||
if (endX > keepX) {
|
||||
ctx.fillStyle = "rgba(224,82,90,0.16)";
|
||||
ctx.fillRect(keepX, 0, endX - keepX, height);
|
||||
}
|
||||
// The wave, one bar per pixel column.
|
||||
const mid = height / 2;
|
||||
const reach = mid * 0.92;
|
||||
const buckets = state.peaks.length / 2;
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const from = Math.floor((x / width) * buckets);
|
||||
const to = Math.max(from + 1, Math.floor(((x + 1) / width) * buckets));
|
||||
let low = 0;
|
||||
let high = 0;
|
||||
for (let bucket = from; bucket < to && bucket < buckets; bucket += 1) {
|
||||
low = Math.min(low, state.peaks[bucket * 2]);
|
||||
high = Math.max(high, state.peaks[bucket * 2 + 1]);
|
||||
}
|
||||
if (x >= startX && x < keepX) ctx.fillStyle = BRAND;
|
||||
else if (x >= keepX && x < endX) ctx.fillStyle = CUT_RED;
|
||||
else ctx.fillStyle = "#3a4948";
|
||||
const top = mid - high * reach;
|
||||
ctx.fillRect(x, top, 1, Math.max(1, (high - low) * reach));
|
||||
}
|
||||
// The handles: IN and OUT, and a dashed line where the max cuts off.
|
||||
// The grips stay small on a short wave so they don't hide it.
|
||||
const grip = Math.round(Math.max(3, Math.min(7, rect.height * 0.12)) * scale);
|
||||
const handle = (x, color) => {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(Math.round(x) - scale, 0, 2 * scale, height);
|
||||
ctx.fillRect(Math.round(x) - 4 * scale, 0, 8 * scale, grip);
|
||||
ctx.fillRect(Math.round(x) - 4 * scale, height - grip, 8 * scale, grip);
|
||||
};
|
||||
handle(startX, "#f4ffff");
|
||||
handle(endX, "#f4ffff");
|
||||
if (endX > keepX + 1) {
|
||||
ctx.strokeStyle = CUT_RED;
|
||||
ctx.lineWidth = 2 * scale;
|
||||
ctx.setLineDash([4 * scale, 3 * scale]);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(keepX, 0);
|
||||
ctx.lineTo(keepX, height);
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
// The playhead while it plays, or where it paused inside the pick.
|
||||
if (state.audio && !state.audio.paused) {
|
||||
const x = xOf(state.audio.currentTime);
|
||||
ctx.fillStyle = "#ffffff";
|
||||
ctx.fillRect(x - scale / 2, 0, scale, height);
|
||||
}
|
||||
}
|
||||
|
||||
function updateFace(state) {
|
||||
const win = currentWindow(state);
|
||||
const max = maxSeconds(state);
|
||||
if (document.activeElement !== state.startInput) state.startInput.value = formatTimecode(win.start);
|
||||
if (document.activeElement !== state.endInput) state.endInput.value = formatTimecode(win.end);
|
||||
if (state.duration > 0) {
|
||||
const summary = outputSummary(win, { maxFromLink: max.fromLink && !max.known });
|
||||
state.summary.textContent = win.length > 0 ? secondsLabel(win.length) : "";
|
||||
state.summary.classList.toggle("has-cut", win.cut > 0.005);
|
||||
state.summary.title = win.cut > 0.005
|
||||
? `${summary}. Max length is ${max.value} s, so ${formatTimecode(win.keepEnd)} to ${formatTimecode(win.end)} is cut off (red). Click to move OUT to ${formatTimecode(win.keepEnd)}.`
|
||||
: `${summary}: ${formatTimecode(win.start)} to ${formatTimecode(win.keepEnd)} comes out.`;
|
||||
} else {
|
||||
state.summary.textContent = "";
|
||||
}
|
||||
draw(state);
|
||||
}
|
||||
|
||||
function writeWidget(widget, value) {
|
||||
const next = roundHundredth(value);
|
||||
if (Math.abs(Number(widget.value || 0) - next) < 0.0001) return;
|
||||
widget.value = next;
|
||||
widget.callback?.(next);
|
||||
}
|
||||
|
||||
function writeTrim(state, bounds) {
|
||||
state.writing = true;
|
||||
try {
|
||||
writeWidget(state.startWidget, bounds.start);
|
||||
// OUT at the very end stays 0, the widget's own "to the end".
|
||||
writeWidget(state.endWidget, bounds.end >= state.duration - 0.005 ? 0 : bounds.end);
|
||||
} finally {
|
||||
state.writing = false;
|
||||
}
|
||||
updateFace(state);
|
||||
state.node.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
|
||||
function installDrag(state) {
|
||||
const surface = state.stage;
|
||||
const infoAt = (clientX) => {
|
||||
const rect = state.canvas.getBoundingClientRect();
|
||||
const fraction = rect.width ? Math.min(1, Math.max(0, (clientX - rect.left) / rect.width)) : 0;
|
||||
const win = currentWindow(state);
|
||||
return { fraction, win, zone: grabZone(win, state.duration, fraction, rect.width) };
|
||||
};
|
||||
surface.addEventListener("pointermove", (event) => {
|
||||
if (state.dragging || state.duration <= 0) return;
|
||||
const { zone } = infoAt(event.clientX);
|
||||
surface.style.cursor = zone === "start" || zone === "end" ? "ew-resize" : zone === "move" ? "grab" : "pointer";
|
||||
});
|
||||
surface.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0 || state.dragging || state.duration <= 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const initial = infoAt(event.clientX);
|
||||
const bounds = { start: initial.win.start, end: initial.win.end };
|
||||
const anchor = initial.fraction * state.duration;
|
||||
const downX = event.clientX;
|
||||
let moved = false;
|
||||
state.dragging = true;
|
||||
try { surface.setPointerCapture(event.pointerId); } catch (_error) { /* mouse fallback */ }
|
||||
const centred = (fraction) => {
|
||||
const span = bounds.end - bounds.start;
|
||||
return slideTrimWindow(state.duration, bounds, fraction * state.duration - span / 2 - bounds.start);
|
||||
};
|
||||
const apply = (clientX) => {
|
||||
const next = infoAt(clientX);
|
||||
if (initial.zone === "start" || initial.zone === "end") {
|
||||
const now = currentWindow(state);
|
||||
writeTrim(state, dragTrimHandle(state.duration, { start: now.start, end: now.end }, initial.zone, next.fraction, MIN_TRIM_SECONDS));
|
||||
} else if (initial.zone === "move") {
|
||||
writeTrim(state, slideTrimWindow(state.duration, bounds, next.fraction * state.duration - anchor));
|
||||
} else {
|
||||
writeTrim(state, centred(next.fraction));
|
||||
}
|
||||
};
|
||||
const move = (moveEvent) => {
|
||||
if (!(moveEvent.buttons & 1)) { finish(moveEvent); return; }
|
||||
if (!moved && Math.abs(moveEvent.clientX - downX) < 3) return;
|
||||
moved = true;
|
||||
apply(moveEvent.clientX);
|
||||
};
|
||||
const finish = (finishEvent) => {
|
||||
if (!state.dragging) return;
|
||||
state.dragging = false;
|
||||
surface.removeEventListener("pointermove", move);
|
||||
try { surface.releasePointerCapture(event.pointerId); } catch (_error) { /* already released */ }
|
||||
if (!moved && initial.zone === "jump") writeTrim(state, centred(infoAt(finishEvent?.clientX ?? downX).fraction));
|
||||
if (moved || initial.zone === "jump") {
|
||||
if (state.audio && !state.audio.paused) state.audio.currentTime = currentWindow(state).start;
|
||||
notifyAusbossChange();
|
||||
}
|
||||
};
|
||||
surface.addEventListener("pointermove", move);
|
||||
surface.addEventListener("pointerup", finish, { once: true });
|
||||
surface.addEventListener("pointercancel", finish, { once: true });
|
||||
surface.addEventListener("lostpointercapture", finish, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function loopEnabled(node) {
|
||||
node.properties ??= {};
|
||||
return !!node.properties.ausboss_load_audio_loop;
|
||||
}
|
||||
|
||||
function installPlayer(state) {
|
||||
const audio = state.audio;
|
||||
const stop = () => {
|
||||
if (state.raf) cancelAnimationFrame(state.raf);
|
||||
state.raf = 0;
|
||||
state.playButton.textContent = "▶";
|
||||
state.playButton.classList.remove("active");
|
||||
draw(state);
|
||||
};
|
||||
const tick = () => {
|
||||
if (audio.paused) { stop(); return; }
|
||||
const win = currentWindow(state);
|
||||
if (audio.currentTime >= win.keepEnd - END_EPSILON || audio.currentTime < win.start - 0.25) {
|
||||
if (loopEnabled(state.node)) audio.currentTime = win.start;
|
||||
else { audio.pause(); audio.currentTime = win.start; stop(); return; }
|
||||
}
|
||||
draw(state);
|
||||
state.raf = requestAnimationFrame(tick);
|
||||
};
|
||||
audio.addEventListener("play", () => {
|
||||
state.playButton.textContent = "❚❚";
|
||||
state.playButton.classList.add("active");
|
||||
if (state.raf) cancelAnimationFrame(state.raf);
|
||||
state.raf = requestAnimationFrame(tick);
|
||||
}, { signal: state.abort.signal });
|
||||
audio.addEventListener("pause", stop, { signal: state.abort.signal });
|
||||
state.playButton.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (state.duration <= 0) return;
|
||||
if (!audio.paused) { audio.pause(); return; }
|
||||
const win = currentWindow(state);
|
||||
if (audio.currentTime < win.start || audio.currentTime >= win.keepEnd - END_EPSILON) audio.currentTime = win.start;
|
||||
audio.play().catch(() => stop());
|
||||
});
|
||||
state.stopPlayer = () => { audio.pause(); stop(); };
|
||||
}
|
||||
|
||||
function commitTimeInput(state, edge, input) {
|
||||
if (state.duration <= 0) return;
|
||||
const seconds = parseTimecode(input.value);
|
||||
const win = currentWindow(state);
|
||||
if (seconds === null) {
|
||||
input.value = formatTimecode(edge === "start" ? win.start : win.end);
|
||||
return;
|
||||
}
|
||||
writeTrim(state, dragTrimHandle(state.duration, { start: win.start, end: win.end }, edge, seconds / state.duration, MIN_TRIM_SECONDS));
|
||||
notifyAusbossChange();
|
||||
input.blur();
|
||||
}
|
||||
|
||||
function watchWidget(state, widget) {
|
||||
if (!widget || widget.__ausbossAudioWatch) return;
|
||||
widget.__ausbossAudioWatch = true;
|
||||
const prior = widget.callback;
|
||||
widget.callback = function (...args) {
|
||||
const result = prior?.apply(this, args);
|
||||
if (!state.writing) updateFace(state);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
function buildPanel(node) {
|
||||
if (node.__ausbossLoadAudio) return node.__ausbossLoadAudio;
|
||||
const audioWidget = findWidget(node, "audio");
|
||||
const startWidget = findWidget(node, "start_seconds");
|
||||
const endWidget = findWidget(node, "end_seconds");
|
||||
if (!audioWidget || !startWidget || !endWidget) return null;
|
||||
ensureAudioCss();
|
||||
hideCoreAudio(node);
|
||||
hideCanvasWidget(startWidget);
|
||||
hideCanvasWidget(endWidget);
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.className = "ausboss-video-root ausboss-audio-root";
|
||||
const stage = document.createElement("div");
|
||||
stage.className = "ausboss-video-stage is-empty";
|
||||
stage.title = "Drag a handle to set where the sound starts or stops. Drag the middle to slide it.";
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.className = "ausboss-audio-wave";
|
||||
const status = document.createElement("div");
|
||||
status.className = "ausboss-video-status";
|
||||
status.textContent = "Choose or upload a sound file";
|
||||
const playButton = makeToolButton("▶", "Play the part that comes out");
|
||||
playButton.classList.add("ausboss-audio-play");
|
||||
const loopButton = makeToolButton("LOOP", "Play it again and again");
|
||||
stage.append(canvas, status);
|
||||
|
||||
const values = document.createElement("div");
|
||||
values.className = "ausboss-video-values";
|
||||
const makeValue = (labelText, title) => {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "ausboss-video-value";
|
||||
const label = document.createElement("label");
|
||||
label.textContent = labelText;
|
||||
const input = document.createElement("input");
|
||||
input.type = "text";
|
||||
input.inputMode = "decimal";
|
||||
input.placeholder = "m:ss.s";
|
||||
input.title = title;
|
||||
input.addEventListener("keydown", (event) => {
|
||||
keepKeyInField(event);
|
||||
if (event.key === "Enter") input.dispatchEvent(new Event("change"));
|
||||
});
|
||||
wrap.append(label, input);
|
||||
return { wrap, input };
|
||||
};
|
||||
const startValue = makeValue("IN", "Where the sound starts. Type seconds (12.5) or a time (0:12.5).");
|
||||
const endValue = makeValue("OUT", "Where the sound stops. Type seconds (24) or a time (0:24.0).");
|
||||
// How long the output is, beside OUT and off the wave. Red when Max
|
||||
// length cuts the pick short; the tooltip says how much.
|
||||
const summary = document.createElement("div");
|
||||
summary.className = "ausboss-audio-length";
|
||||
values.append(startValue.wrap, endValue.wrap);
|
||||
const row = document.createElement("div");
|
||||
row.className = "ausboss-audio-row";
|
||||
row.append(playButton, values, summary, loopButton);
|
||||
root.append(stage, row);
|
||||
|
||||
const widget = node.addDOMWidget(PANEL_WIDGET, "ausboss_audio", root, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
getMinHeight: () => PANEL_MIN_HEIGHT + WIDGET_FRAME,
|
||||
});
|
||||
keepDomWidgetWidthAuto(widget);
|
||||
widget.serialize = false;
|
||||
fillNodeHeight(widget, {
|
||||
minWidth: MIN_WIDTH,
|
||||
minHeight: PANEL_MIN_HEIGHT + WIDGET_FRAME,
|
||||
minNodeSize: [MIN_WIDTH, 200],
|
||||
exactMinWidth: true,
|
||||
});
|
||||
|
||||
const audio = new Audio();
|
||||
audio.preload = "auto";
|
||||
const abort = new AbortController();
|
||||
const state = node.__ausbossLoadAudio = {
|
||||
node, root, stage, canvas, status, playButton, loopButton, summary, audio,
|
||||
startInput: startValue.input, endInput: endValue.input,
|
||||
audioWidget, startWidget, endWidget, maxWidget: findWidget(node, "max_seconds"),
|
||||
duration: 0, peaks: null, abort, writing: false, dragging: false, raf: 0, loading: 0,
|
||||
};
|
||||
|
||||
// Clicking the red length moves OUT to where the sound really ends.
|
||||
summary.addEventListener("click", (event) => {
|
||||
const win = currentWindow(state);
|
||||
if (win.cut <= 0.005) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
writeTrim(state, { start: win.start, end: win.keepEnd });
|
||||
notifyAusbossChange();
|
||||
});
|
||||
|
||||
const updateLoop = () => loopButton.classList.toggle("active", loopEnabled(node));
|
||||
updateLoop();
|
||||
loopButton.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
node.properties.ausboss_load_audio_loop = !loopEnabled(node);
|
||||
updateLoop();
|
||||
notifyAusbossChange();
|
||||
});
|
||||
|
||||
const refresh = async () => {
|
||||
state.stopPlayer?.();
|
||||
const name = audioWidget.value;
|
||||
const ticket = ++state.loading;
|
||||
state.duration = 0;
|
||||
state.peaks = null;
|
||||
if (!name || typeof name !== "string") {
|
||||
audio.removeAttribute("src");
|
||||
stage.classList.add("is-empty");
|
||||
status.textContent = "Choose or upload a sound file";
|
||||
updateFace(state);
|
||||
return;
|
||||
}
|
||||
const parts = splitMediaName(name);
|
||||
stage.classList.add("is-empty");
|
||||
status.textContent = `Loading ${parts.filename}…`;
|
||||
const type = parseImageReference(name)?.type ?? "input";
|
||||
const route = `/view?${mediaViewQuery({ ...parts, type }, "input")}`;
|
||||
audio.src = api.apiURL(route);
|
||||
try {
|
||||
const result = await loadPeaks(name, route);
|
||||
if (ticket !== state.loading) return;
|
||||
state.duration = result.duration;
|
||||
state.peaks = result.peaks;
|
||||
stage.classList.remove("is-empty");
|
||||
updateFace(state);
|
||||
} catch (error) {
|
||||
if (ticket !== state.loading) return;
|
||||
status.textContent = `This sound could not be shown: ${error?.message || error}`;
|
||||
}
|
||||
};
|
||||
state.refresh = refresh;
|
||||
|
||||
installDrag(state);
|
||||
installPlayer(state);
|
||||
watchWidget(state, startWidget);
|
||||
watchWidget(state, endWidget);
|
||||
watchWidget(state, state.maxWidget);
|
||||
startValue.input.addEventListener("change", () => commitTimeInput(state, "start", startValue.input));
|
||||
endValue.input.addEventListener("change", () => commitTimeInput(state, "end", endValue.input));
|
||||
const observer = new ResizeObserver(() => draw(state));
|
||||
observer.observe(stage);
|
||||
state.observer = observer;
|
||||
|
||||
const priorAudioCallback = audioWidget.callback;
|
||||
audioWidget.callback = function (...args) {
|
||||
const result = priorAudioCallback?.apply(this, args);
|
||||
peakCache.delete(audioWidget.value);
|
||||
refresh();
|
||||
return result;
|
||||
};
|
||||
setTimeout(refresh, 0);
|
||||
return state;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "ausboss.load_audio",
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData?.name !== NODE_NAME) return;
|
||||
// The frontend's Upload button for an audio_upload input looks for its
|
||||
// player widget and fails without one, and it adds that player only to
|
||||
// its own audio nodes. Ask for it here, ahead of the button; the panel
|
||||
// hides it, since the wave plays the sound instead.
|
||||
const required = nodeData.input?.required;
|
||||
if (required && !required.audioUI) {
|
||||
const entries = Object.entries(required);
|
||||
const at = entries.findIndex(([name]) => name === "audio") + 1;
|
||||
entries.splice(at, 0, ["audioUI", ["AUDIO_UI", {}]]);
|
||||
nodeData.input.required = Object.fromEntries(entries);
|
||||
}
|
||||
chainCallback(nodeType.prototype, "onNodeCreated", function () {
|
||||
buildPanel(this);
|
||||
// Only for a genuinely new node: onConfigure restores a saved size
|
||||
// after this runs, so a workflow's own size still wins.
|
||||
const floor = Number(this.computeSize?.()?.[1]) || 0;
|
||||
if (floor > 0) this.setSize?.([DEFAULT_WIDTH, floor + DEFAULT_WAVE_EXTRA]);
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onConfigure", function () {
|
||||
queueMicrotask(() => {
|
||||
const state = buildPanel(this);
|
||||
if (state) {
|
||||
hideCoreAudio(this);
|
||||
state.refresh?.();
|
||||
}
|
||||
});
|
||||
});
|
||||
// A wire into Max length changes what comes out; redraw when one comes or goes.
|
||||
chainCallback(nodeType.prototype, "onConnectionsChange", function () {
|
||||
const state = this.__ausbossLoadAudio;
|
||||
if (state) queueMicrotask(() => updateFace(state));
|
||||
});
|
||||
chainCallback(nodeType.prototype, "onRemoved", function () {
|
||||
const state = this.__ausbossLoadAudio;
|
||||
state?.stopPlayer?.();
|
||||
state?.abort?.abort();
|
||||
state?.observer?.disconnect();
|
||||
if (state) state.audio.removeAttribute("src");
|
||||
this.__ausbossLoadAudio = null;
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -20,6 +20,7 @@ const emptyWidget = (inputs, name) => !linked(inputs?.[name]) && blank(inputs?.[
|
||||
|
||||
const picture = (name) => (inputs) => (emptyWidget(inputs, name) ? { input: name, kind: "picture" } : null);
|
||||
const video = (name) => (inputs) => (emptyWidget(inputs, name) ? { input: name, kind: "video" } : null);
|
||||
const sound = (name) => (inputs) => (emptyWidget(inputs, name) ? { input: name, kind: "sound file" } : null);
|
||||
|
||||
function videoSource(inputs) {
|
||||
const mode = inputs?.source_mode;
|
||||
@@ -38,6 +39,7 @@ export const SOURCE_LOADERS = Object.freeze({
|
||||
AUSBOSS_NODES_ImageCropRotatePad: picture("image"),
|
||||
// A wired source_image replaces the file, so the file may stay blank.
|
||||
AUSBOSS_NODES_LoadImagePad: (inputs) => (linked(inputs?.source_image) ? null : picture("image")(inputs)),
|
||||
AUSBOSS_NODES_LoadAudio: sound("audio"),
|
||||
AUSBOSS_NODES_LoadVideo: video("video"),
|
||||
AUSBOSS_NODES_VideoCropRotatePad: videoSource,
|
||||
AUSBOSS_NODES_VideoCropRotatePadClip: videoSource,
|
||||
@@ -110,7 +112,8 @@ export function emptySourceMessage(found) {
|
||||
if (!first) return "";
|
||||
const more = found.length - 1;
|
||||
const tail = more > 0 ? ` (and ${more} more node${more === 1 ? "" : "s"})` : "";
|
||||
return `Load a ${first.kind === "video" ? "video" : "picture"} first: ${first.title}${tail}`;
|
||||
const noun = first.kind === "video" || first.kind === "sound file" ? first.kind : "picture";
|
||||
return `Load a ${noun} first: ${first.title}${tail}`;
|
||||
}
|
||||
|
||||
// "Save Image: exact_name may not ..." names the input it is about, after
|
||||
|
||||
@@ -384,6 +384,16 @@ const CARDS = {
|
||||
{ widget: "max_frames", label: "Limit" },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_LoadAudio: {
|
||||
// The wave, IN and OUT live in the panel under the card (js/load_audio).
|
||||
minWidth: 280, first: true, hide: ["upload"],
|
||||
rows: [
|
||||
{ widget: "audio", label: "Source", kind: "select",
|
||||
button: { text: "Upload", title: "Upload a sound file into ComfyUI's input folder", onClick: (node) => node.widgets?.find((w) => w.name === "upload")?.callback?.() } },
|
||||
{ widget: "max_seconds", label: "Max length", suffix: "s", decimals: 1, trimZeros: true,
|
||||
title: "The longest the sound may be. Anything past it is cut off and shows in red. 0 means no limit." },
|
||||
],
|
||||
},
|
||||
AUSBOSS_NODES_LoadImagePad: {
|
||||
minWidth: 340, first: true, hide: ["upload"],
|
||||
rows: [
|
||||
|
||||
@@ -1557,5 +1557,31 @@
|
||||
"AUSBOSS_NODES_WorkflowSwitches": {
|
||||
"display_name": "工作流开关 🆎",
|
||||
"description": "用一张小卡片开关工作流的各个部分。选中组成一个部分的节点,例如一个框和它的保存节点,按 + Switch:它们会得到一个 off | on 开关,名字由你定。每个组也可以有自己的开关。off 会旁路这些节点,图片仍然传到下一步(也可以设置为静音)。on 让它们重新运行。开关也可以改设置,而不是关闭节点:分别保存节点在 on 和 off 时的值,点一下就能把 Steps 设为 8 并打开一行 LoRA。按 Done,节点会缩成只有标签和开关。它从不运行,也没有连线。"
|
||||
},
|
||||
"AUSBOSS_NODES_LoadAudio": {
|
||||
"display_name": "加载音频 🆎",
|
||||
"description": "加载声音文件,只输出你选中的部分。节点把声音画成波形:拖动两个手柄设置起点和终点,按播放只听这一段。把最大长度设为下一步能接收的最长声音,超出的部分会显示为红色并被剪掉,运行前就能看到输出的内容。",
|
||||
"inputs": {
|
||||
"audio": {
|
||||
"name": "音频"
|
||||
},
|
||||
"start_seconds": {
|
||||
"name": "起始秒数"
|
||||
},
|
||||
"end_seconds": {
|
||||
"name": "结束秒数"
|
||||
},
|
||||
"max_seconds": {
|
||||
"name": "最大秒数"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "音频"
|
||||
},
|
||||
"1": {
|
||||
"name": "秒数"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Trimmed audio decoding for Load Audio.
|
||||
|
||||
The window rules live in ``audio_window`` so the node and its tests agree on
|
||||
what one Run hands on; ``js/load_audio/audio_window.mjs`` mirrors them for the
|
||||
face. Decoding counts samples from the start of the sound track and stops as
|
||||
soon as the window is full, so a short pick from a long file never decodes
|
||||
the whole file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from ._execution_helpers import raise_if_interrupted
|
||||
|
||||
try:
|
||||
import folder_paths
|
||||
except ImportError: # offline tests
|
||||
folder_paths = None
|
||||
|
||||
AUDIO_EXTENSIONS = {
|
||||
".aac",
|
||||
".aif",
|
||||
".aiff",
|
||||
".flac",
|
||||
".m4a",
|
||||
".mp3",
|
||||
".oga",
|
||||
".ogg",
|
||||
".opus",
|
||||
".wav",
|
||||
".webm",
|
||||
".wma",
|
||||
}
|
||||
# Video files carry sound too: a song is often only on hand inside a clip.
|
||||
SOUND_IN_VIDEO_EXTENSIONS = {".mkv", ".mov", ".mp4", ".m4v"}
|
||||
|
||||
FALLBACK_SAMPLE_RATE = 44100
|
||||
# Shorter than this is no window at all; the face keeps its handles this far apart.
|
||||
MIN_WINDOW_SECONDS = 0.1
|
||||
|
||||
|
||||
def _number(value, default: float = 0.0) -> float:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return number if math.isfinite(number) else default
|
||||
|
||||
|
||||
def list_input_audio() -> list[str]:
|
||||
"""Sound files (and videos, for their sound) in ComfyUI's input folder."""
|
||||
if folder_paths is None:
|
||||
return [""]
|
||||
root = Path(folder_paths.get_input_directory())
|
||||
kinds = AUDIO_EXTENSIONS | SOUND_IN_VIDEO_EXTENSIONS
|
||||
results = [
|
||||
path.relative_to(root).as_posix()
|
||||
for path in root.rglob("*")
|
||||
if path.is_file() and not path.name.startswith(".") and path.suffix.lower() in kinds
|
||||
]
|
||||
return sorted(results, key=str.casefold) or [""]
|
||||
|
||||
|
||||
def audio_window(start_seconds, end_seconds, max_seconds=0.0, duration=None) -> dict:
|
||||
"""The part of a sound file one Run hands on.
|
||||
|
||||
end 0 means "to the end of the file". max_seconds above 0 caps the
|
||||
window's length: the pick keeps its start and anything past
|
||||
start + max_seconds is cut off. ``duration`` is the file's length when it
|
||||
is known; None leaves an open end open.
|
||||
|
||||
Returns start, end (None when open), the end the person picked
|
||||
(``picked_end``) and how many seconds the cap cut off (``cut``).
|
||||
"""
|
||||
start = max(0.0, _number(start_seconds))
|
||||
picked_end = _number(end_seconds)
|
||||
end = picked_end if picked_end > 0 else None
|
||||
if duration is not None:
|
||||
length = max(0.0, _number(duration))
|
||||
start = min(start, length)
|
||||
end = length if end is None else min(end, length)
|
||||
if end is not None:
|
||||
end = max(start, end)
|
||||
picked = end
|
||||
limit = max(0.0, _number(max_seconds))
|
||||
if limit > 0 and (end is None or end - start > limit):
|
||||
end = start + limit
|
||||
if duration is not None:
|
||||
end = min(end, max(0.0, _number(duration)))
|
||||
cut = 0.0
|
||||
if picked is not None and end is not None:
|
||||
cut = max(0.0, picked - end)
|
||||
return {"start": start, "end": end, "picked_end": picked, "cut": cut}
|
||||
|
||||
|
||||
def decode_audio_window(path: Path, start_seconds, end_seconds, max_seconds=0.0) -> dict:
|
||||
"""ComfyUI AUDIO for the window ``audio_window`` describes.
|
||||
|
||||
Raises a plain ValueError for a file with no sound, or a start at or past
|
||||
the end of the sound.
|
||||
"""
|
||||
window = audio_window(start_seconds, end_seconds, max_seconds)
|
||||
start = window["start"]
|
||||
with av.open(str(path)) as container:
|
||||
stream = next((candidate for candidate in container.streams if candidate.type == "audio"), None)
|
||||
if stream is None:
|
||||
raise ValueError(f"{path.name} has no sound in it.")
|
||||
rate = int(stream.rate or FALLBACK_SAMPLE_RATE)
|
||||
first = round(start * rate)
|
||||
last = None if window["end"] is None else round(window["end"] * rate)
|
||||
resampler = av.AudioResampler(format="fltp", layout=stream.layout, rate=rate)
|
||||
chunks: list[np.ndarray] = []
|
||||
position = 0
|
||||
|
||||
def take(frame) -> None:
|
||||
nonlocal position
|
||||
for resampled in resampler.resample(frame):
|
||||
data = resampled.to_ndarray()
|
||||
begin = position
|
||||
position += data.shape[1]
|
||||
if position <= first:
|
||||
continue
|
||||
low = max(0, first - begin)
|
||||
high = data.shape[1] if last is None else min(data.shape[1], last - begin)
|
||||
if high > low:
|
||||
chunks.append(data[:, low:high])
|
||||
|
||||
for frame in container.decode(stream):
|
||||
raise_if_interrupted()
|
||||
take(frame)
|
||||
if last is not None and position >= last:
|
||||
break
|
||||
else:
|
||||
take(None) # the resampler hands back what it still holds
|
||||
if not chunks:
|
||||
if position == 0:
|
||||
raise ValueError(f"{path.name} has no sound in it.")
|
||||
raise ValueError(
|
||||
f"The start ({start:.2f} s) is past the end of {path.name}, "
|
||||
f"which is {position / rate:.2f} s long. Drag the start back into the sound."
|
||||
)
|
||||
data = np.concatenate(chunks, axis=1).astype(np.float32, copy=False)
|
||||
return {
|
||||
"waveform": torch.from_numpy(np.ascontiguousarray(data)).unsqueeze(0),
|
||||
"sample_rate": rate,
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AUDIO_EXTENSIONS",
|
||||
"MIN_WINDOW_SECONDS",
|
||||
"SOUND_IN_VIDEO_EXTENSIONS",
|
||||
"audio_window",
|
||||
"decode_audio_window",
|
||||
"list_input_audio",
|
||||
]
|
||||
+75
-12
@@ -37,6 +37,12 @@ NEEDS_A_PERSON = {
|
||||
MOVES: "To copy the moves, connect a picture of your person and pick person for it.",
|
||||
SWAP: "To swap the person, connect a picture of the new person and pick person for it.",
|
||||
}
|
||||
# A hat or a shirt with no person picture: the user wants the video's own person to wear it.
|
||||
DRESS_THE_VIDEO_PERSON = (
|
||||
"To put this on the person in your video, load a still of them from the video as Picture 1 "
|
||||
"and pick person for it. Give the hat or outfit its own picture, pick outfit or thing, and type "
|
||||
"\"@1 wears @2\" with video job swap the person."
|
||||
)
|
||||
|
||||
# (what the label is, how it is kept). {picture} is H3's number for the picture.
|
||||
JOB_WORDS = {
|
||||
@@ -88,14 +94,20 @@ MOVES_KEPT = (
|
||||
"keep the source performer's face, body, clothes, props, background and colours out of the target.\n"
|
||||
"<Video 1>: attribute_transfer - apply only its camera movement to the target scene."
|
||||
)
|
||||
SWAP_IS = (
|
||||
"<Video 1> supplies the place, the action, the timing, the camera movement and the look.\n"
|
||||
"{replaced} is {who} in <Video 1>, selected for replacement."
|
||||
)
|
||||
SWAP_KEPT = (
|
||||
SWAP_VIDEO = "<Video 1> supplies the place, the action, the timing, the camera movement and the look."
|
||||
SWAP_IS = "{replaced} is {who} in <Video 1>, selected for replacement."
|
||||
SWAP_VIDEO_KEPT = (
|
||||
"<Video 1>: partially_preserved - keep the place, the action, the timing, the camera movement and the look; "
|
||||
"change only the person.\n"
|
||||
"{replaced}: removed - replace {who} with {main} throughout."
|
||||
"change only the {people}."
|
||||
)
|
||||
SWAP_KEPT = "{replaced}: removed - replace {who} with {main} throughout."
|
||||
ONE_GOES = "the original person"
|
||||
# Where each person stands when two or more go and the script doesn't say, from left to right like the pictures.
|
||||
SPOTS = {2: ("left", "right"), 3: ("left", "centre", "right"), 4: ("far left", "left", "right", "far right")}
|
||||
SAYS_WHO = re.compile(
|
||||
r"^(?:is|are|replaces|takes\s+the\s+place\s+of|goes\s+in\s+for|swaps?\s+(?:in\s+)?for|in\s+place\s+of|for|as)\b\s*"
|
||||
r"|^[:=\-\u2013\u2014>]+\s*",
|
||||
re.I,
|
||||
)
|
||||
SWAPPED = "attribute_transfer - apply the defined appearance to the original performance; the background of {picture} is not transferred."
|
||||
KEEP_IS = (
|
||||
@@ -115,6 +127,11 @@ REVOICE_KEPT = (
|
||||
)
|
||||
|
||||
|
||||
def lower_first(text):
|
||||
first = text.split(" ", 1)[0]
|
||||
return text if text[:1] == "<" or (len(first) > 1 and first.isupper()) else text[:1].lower() + text[1:]
|
||||
|
||||
|
||||
def subject_label(number):
|
||||
return f"<Subject {number}>"
|
||||
|
||||
@@ -135,11 +152,16 @@ class Picture:
|
||||
subject: int = 0 # A picture that only marks the last frame has none.
|
||||
|
||||
|
||||
def swapped_in(jobs):
|
||||
"""How many people a swap puts in: one for each person or sheet picture."""
|
||||
return max(1, sum(job in (PERSON, SHEET) for job in jobs.values()))
|
||||
|
||||
|
||||
def number_pictures(jobs, video=""):
|
||||
"""Connected pictures in order, from {number on the node: job}. In a swap
|
||||
the person being replaced comes first, as <Subject 1>."""
|
||||
the people being replaced come first, as <Subject 1>, <Subject 2> and on."""
|
||||
pictures = []
|
||||
subjects = 1 if video == SWAP else 0
|
||||
subjects = swapped_in(jobs) if video == SWAP else 0
|
||||
for picture, slot in enumerate(sorted(jobs), 1):
|
||||
subjects += jobs[slot] != END
|
||||
pictures.append(Picture(slot, jobs[slot], picture, 0 if jobs[slot] == END else subjects))
|
||||
@@ -154,8 +176,12 @@ class Cast:
|
||||
self.video = video
|
||||
last = max((picture.subject for picture in pictures), default=0)
|
||||
self.moves = subject_label(last + 1) if video == MOVES else ""
|
||||
# In a swap each person or sheet picture takes one person's place in the video, in picture order. The script
|
||||
# can name who goes: "the child in the seat", or "@1 the man on the left. @2 the woman in red".
|
||||
self.swappers = [picture for picture in pictures if picture.job in (PERSON, SHEET)] if video == SWAP else []
|
||||
goes = len(self.swappers)
|
||||
self.whos = [f"the person on the {spot}" for spot in SPOTS[goes]] if goes > 1 else [ONE_GOES]
|
||||
self.replaced = subject_label(1) if video == SWAP else ""
|
||||
self.who = "the original person" # In a swap the script can name who goes: "the child in the seat".
|
||||
self.in_video = subject_label(last + 1) if video in (KEEP, REVOICE) else ""
|
||||
self.people = [picture for picture in pictures if picture.job in (PERSON, SHEET, START)]
|
||||
self.subjects = {picture.slot: subject_label(picture.subject) for picture in pictures if picture.subject}
|
||||
@@ -163,6 +189,39 @@ class Cast:
|
||||
def of(self, *jobs):
|
||||
return [picture for picture in self.pictures if picture.job in jobs]
|
||||
|
||||
@property
|
||||
def who(self):
|
||||
return self.whos[0]
|
||||
|
||||
@who.setter
|
||||
def who(self, words):
|
||||
self.whos[0] = words
|
||||
|
||||
@property
|
||||
def swaps(self):
|
||||
"""(who goes, the words for them, who comes in) for each person a swap replaces."""
|
||||
coming = [subject_label(picture.subject) for picture in self.swappers] or [self.main]
|
||||
return [(subject_label(number), who, new) for number, (who, new) in enumerate(zip(self.whos, coming), 1)]
|
||||
|
||||
def name_who_goes(self, lines):
|
||||
"""Who each new person replaces, from the lines typed in a swap. With one, the words are who goes. With more,
|
||||
each @ names one, or else the lines go in picture order; anything else keeps left to right."""
|
||||
lines = [line.strip() for line in lines if line.strip(" .")]
|
||||
text = " ".join(lines)
|
||||
if len(self.whos) == 1:
|
||||
self.who = lower_first(SAYS_WHO.sub("", TOKEN.sub("", text).strip()).rstrip(". ") or ONE_GOES)
|
||||
return
|
||||
slots = [picture.slot for picture in self.swappers]
|
||||
pieces = re.split(r"@(\d)\b", text)
|
||||
named = {int(slot): words for slot, words in zip(pieces[1::2], pieces[2::2]) if int(slot) in slots}
|
||||
if not named:
|
||||
named = dict(zip(slots, lines)) if len(lines) == len(slots) else {}
|
||||
for index, slot in enumerate(slots):
|
||||
words = SAYS_WHO.sub("", named.get(slot, "").strip(" .,;")).strip(" .,;")
|
||||
words = re.sub(r"\s+and$", "", words)
|
||||
if words:
|
||||
self.whos[index] = lower_first(words)
|
||||
|
||||
@property
|
||||
def main(self):
|
||||
"""Who a line is about when it names nobody."""
|
||||
@@ -188,6 +247,8 @@ class Cast:
|
||||
if not self.pictures and not self.video:
|
||||
return NOTHING_IN
|
||||
if self.video in NEEDS_A_PERSON and not self.people:
|
||||
if self.of(OUTFIT, THING):
|
||||
return DRESS_THE_VIDEO_PERSON
|
||||
return NEEDS_A_PERSON[self.video]
|
||||
typed = sorted({int(number) for number in TOKEN.findall(text)} - {0})
|
||||
slots = {picture.slot: picture for picture in self.pictures}
|
||||
@@ -222,7 +283,8 @@ class Cast:
|
||||
ends = self.ends
|
||||
lines = []
|
||||
if self.video == SWAP:
|
||||
lines.append(SWAP_IS.format(replaced=self.replaced, who=self.who))
|
||||
lines.append(SWAP_VIDEO)
|
||||
lines += [SWAP_IS.format(replaced=gone, who=who) for gone, who, _ in self.swaps]
|
||||
worn = set(wearers.values())
|
||||
for picture in self.pictures:
|
||||
if picture.job == END:
|
||||
@@ -276,7 +338,8 @@ class Cast:
|
||||
|
||||
lines = []
|
||||
if self.video == SWAP:
|
||||
lines.append(SWAP_KEPT.format(replaced=self.replaced, who=self.who, main=self.main))
|
||||
lines.append(SWAP_VIDEO_KEPT.format(people="people" if len(self.swaps) > 1 else "person"))
|
||||
lines += [SWAP_KEPT.format(replaced=gone, who=who, main=new) for gone, who, new in self.swaps]
|
||||
for picture in self.pictures:
|
||||
if picture.job == END:
|
||||
continue
|
||||
|
||||
@@ -13,7 +13,7 @@ import re
|
||||
import numpy as np
|
||||
|
||||
from ._h3_cast_helpers import KEEP, NEEDS_NO_WORDS, REVOICE, SWAP, Cast, number_pictures
|
||||
from ._h3_script_helpers import ACTION_GOES_ON, Moment, add_moments, add_sound, lower_first, read_script, script_parts, speakers
|
||||
from ._h3_script_helpers import ACTION_GOES_ON, Moment, add_moments, add_sound, read_script, script_parts, speakers
|
||||
|
||||
SECTIONS = (
|
||||
"subject_definitions",
|
||||
@@ -184,7 +184,7 @@ def write_prompt(script, seconds=15.0, camera="", look="", sound="", language="E
|
||||
if not scene.moments and video not in NEEDS_NO_WORDS:
|
||||
raise ValueError(NO_SCRIPT)
|
||||
if video == SWAP and scene.moments: # Typed words in a swap say which person goes, for a clip with two.
|
||||
cast.who = lower_first(" ".join(moment.text for moment in scene.moments).rstrip(". "))
|
||||
cast.name_who_goes([moment.text for moment in scene.moments])
|
||||
scene.moments = []
|
||||
if not scene.moments:
|
||||
scene.moments.append(Moment(ACTION_GOES_ON if video == KEEP else ""))
|
||||
|
||||
@@ -25,7 +25,10 @@ from ._h3_cast_helpers import (
|
||||
SOUND_GOES_ON_KEPT,
|
||||
THING,
|
||||
TOKEN,
|
||||
ONE_GOES,
|
||||
SPOTS,
|
||||
Cast,
|
||||
lower_first,
|
||||
number_pictures,
|
||||
picture_label,
|
||||
subject_label,
|
||||
@@ -124,7 +127,6 @@ VIDEO_LOOKS = {
|
||||
KEEP: "The target video keeps the look, colours and camera of <Video 1>.",
|
||||
REVOICE: "The target video keeps the look, light and camera of <Video 1>.",
|
||||
}
|
||||
SPOTS = {2: ("left", "right"), 3: ("left", "centre", "right"), 4: ("far left", "left", "right", "far right")}
|
||||
NAMES_A_SPOT = re.compile(r"\b(?:left|right|behind|in\s+front|foreground|background)\b", re.I)
|
||||
OPENS_ON_THEM = re.compile(r"^(?:She|He)\b")
|
||||
FOLLOWS_A_COMMA = re.compile(r"^(?:A|An|The|She|He|They|It|Her|His|Their|Its|This|That|These|Those|There|Someone|Everyone|Nobody)\b")
|
||||
@@ -539,9 +541,6 @@ def stamp(seconds):
|
||||
return f"{int(minutes):02d}:{rest:06.3f}"
|
||||
|
||||
|
||||
def lower_first(text):
|
||||
first = text.split(" ", 1)[0]
|
||||
return text if text[:1] == "<" or (len(first) > 1 and first.isupper()) else text[:1].lower() + text[1:]
|
||||
|
||||
|
||||
def after_comma(text):
|
||||
@@ -669,7 +668,8 @@ def before_the_action(number, text, cast, wearers):
|
||||
words = OPENS_ON if cast.ends else OPENING
|
||||
notes.append(words.format(subject=subject_label(opens.subject), picture=picture_label(opens.picture)))
|
||||
if cast.video == SWAP:
|
||||
notes += [TAKES_OVER.format(main=cast.main, who=cast.who), ONE_PERSON if cast.who == "the original person" else OTHERS_STAY]
|
||||
notes += [TAKES_OVER.format(main=new, who=who) for _, who, new in cast.swaps]
|
||||
notes.append(ONE_PERSON if cast.whos == [ONE_GOES] else OTHERS_STAY)
|
||||
if number == 1 and cast.video == KEEP:
|
||||
notes += [CARRIES_ON]
|
||||
if number == 1 and cast.video == REVOICE:
|
||||
@@ -678,7 +678,7 @@ def before_the_action(number, text, cast, wearers):
|
||||
if places and not any(place in text for place in places):
|
||||
notes.append(IN_THE_PLACE.format(place=places[0]))
|
||||
people = people_in(text, cast)
|
||||
if len(people) > 1 and not NAMES_A_SPOT.search(text):
|
||||
if len(people) > 1 and not NAMES_A_SPOT.search(text) and cast.video != SWAP: # A swap's people stand where the video has them.
|
||||
spots = [f"{person} is on the {spot}" for person, spot in zip(people, SPOTS[len(people)])]
|
||||
notes.append(sentence(", ".join(spots[:-1]) + f" and {spots[-1]} of the frame"))
|
||||
for slot, wearer in wearers.items():
|
||||
@@ -786,7 +786,8 @@ def task_of(cast):
|
||||
def summary_of(script, cast, new_places, soundtrack):
|
||||
task = task_of(cast)
|
||||
if cast.video == SWAP:
|
||||
return f"[{task}] Replace {cast.replaced} with {cast.main} while preserving the original action, place, camera and look of <Video 1>."
|
||||
swaps = " and ".join(f"{gone} with {new}" for gone, _, new in cast.swaps)
|
||||
return f"[{task}] Replace {swaps} while preserving the original action, place, camera and look of <Video 1>."
|
||||
if cast.video == REVOICE:
|
||||
return (
|
||||
f"[{task}] The target video is an edited version of <Video 1>. The picture, the timing and the lip movement "
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Load Audio 🆎."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from ._audio_trim_helpers import decode_audio_window, list_input_audio
|
||||
from ._execution_helpers import ignore_extra_inputs
|
||||
from ._media_helpers import resolve_input_path
|
||||
|
||||
|
||||
class AusBossLoadAudio:
|
||||
CATEGORY = "🆎 AusBoss/Video"
|
||||
DESCRIPTION = (
|
||||
"Loads a sound file and hands on only the part you pick. The node shows the "
|
||||
"sound as a wave, so you can see where the loud parts are. Drag the two "
|
||||
"handles to set where it starts and stops, and press play to hear just that "
|
||||
"part. Set Max length to the longest sound the next step takes: anything "
|
||||
"longer shows in red as cut off, so you see exactly what comes out before "
|
||||
"you run anything."
|
||||
)
|
||||
SEARCH_ALIASES = [
|
||||
"load audio",
|
||||
"audio loader",
|
||||
"trim audio",
|
||||
"cut audio",
|
||||
"song",
|
||||
"voice",
|
||||
"music",
|
||||
"waveform",
|
||||
"ausboss",
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"audio": (
|
||||
list_input_audio(),
|
||||
{
|
||||
"audio_upload": True,
|
||||
"tooltip": "A sound file in ComfyUI's input folder. Use Upload to add one.",
|
||||
},
|
||||
),
|
||||
"start_seconds": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 86400.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Where the sound starts. Drag the wave's IN handle or type a time.",
|
||||
},
|
||||
),
|
||||
"end_seconds": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 86400.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Where the sound stops. 0 plays to the end. Drag the OUT handle or type a time.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"max_seconds": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 86400.0,
|
||||
"step": 0.1,
|
||||
"tooltip": (
|
||||
"The longest the sound may be. Anything past it is cut off and shows "
|
||||
"in red. 0 means no limit."
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO", "FLOAT")
|
||||
RETURN_NAMES = ("audio", "seconds")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The part of the sound you picked, ready for any node that takes audio.",
|
||||
"How long that sound is, in seconds.",
|
||||
)
|
||||
FUNCTION = "load_audio"
|
||||
|
||||
async def load_audio(self, audio, start_seconds, end_seconds, max_seconds=0.0):
|
||||
path = resolve_input_path(audio)
|
||||
# Decoding blocks for as long as the pick is; a worker thread keeps
|
||||
# ComfyUI's event loop answering, and carries the context ComfyUI
|
||||
# reads to attribute an interrupt to this node.
|
||||
sound = await asyncio.to_thread(
|
||||
decode_audio_window, path, start_seconds, end_seconds, max_seconds
|
||||
)
|
||||
seconds = sound["waveform"].shape[-1] / float(sound["sample_rate"])
|
||||
return (sound, float(seconds))
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, audio, **_values):
|
||||
try:
|
||||
stat = resolve_input_path(audio).stat()
|
||||
except Exception:
|
||||
return float("nan")
|
||||
return f"{audio}:{stat.st_mtime_ns}:{stat.st_size}"
|
||||
|
||||
@classmethod
|
||||
@ignore_extra_inputs
|
||||
def VALIDATE_INPUTS(cls, audio):
|
||||
# Only the source is named: ComfyUI skips its own range checks for
|
||||
# every input named here. resolve_input_path takes a file inside the
|
||||
# input folder, or one named "[output]" or "[temp]", and nothing else.
|
||||
try:
|
||||
resolve_input_path(audio)
|
||||
except Exception as exc:
|
||||
return f"Load Audio: {exc}"
|
||||
return True
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"AUSBOSS_NODES_LoadAudio": AusBossLoadAudio}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"AUSBOSS_NODES_LoadAudio": "Load Audio 🆎"}
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -67,6 +67,7 @@ PUBLIC_NODE_IDS = {
|
||||
"AUSBOSS_NODES_Krea2OutpaintModelPatch",
|
||||
"AUSBOSS_NODES_LaMaInpaint",
|
||||
"AUSBOSS_NODES_LayoutBoxes",
|
||||
"AUSBOSS_NODES_LoadAudio",
|
||||
"AUSBOSS_NODES_LoadImagePad",
|
||||
"AUSBOSS_NODES_LoadVideo",
|
||||
"AUSBOSS_NODES_LoraLoader",
|
||||
|
||||
@@ -63,6 +63,58 @@ def named_copy_problems(node: dict) -> list[str]:
|
||||
return [f"node {node['id']} has stale named widget values: {', '.join(stale)}"] if stale else []
|
||||
|
||||
|
||||
def saved_widget(node: dict, name: str):
|
||||
"""A widget's saved value by name, or KeyError when the node keeps no named copy of it."""
|
||||
values = node.get("widgets_values")
|
||||
if isinstance(values, dict) and name in values:
|
||||
return values[name]
|
||||
named = node.get("widgets_values_named")
|
||||
if isinstance(named, dict) and name in named:
|
||||
return named[name]
|
||||
raise KeyError(name)
|
||||
|
||||
|
||||
def switch_row_problems(card: dict, by_id: dict) -> list[str]:
|
||||
"""A Workflow Switches row opens striped "changed", with neither off nor
|
||||
on picked, when the values it sets are saved half one way and half the
|
||||
other, or when its nodes run one way and its values say the other. Every
|
||||
row of an example has to open plainly off or on."""
|
||||
settings = (card.get("properties") or {}).get("ausboss_workflow_switches") or {}
|
||||
problems = []
|
||||
for row in settings.get("switches") or []:
|
||||
title = row.get("title", row.get("id"))
|
||||
sides = set()
|
||||
on, off = row.get("on") or {}, row.get("off") or {}
|
||||
for node_id, widgets in on.items():
|
||||
node = by_id.get(int(node_id)) if str(node_id).isdigit() else None
|
||||
if node is None or not isinstance(widgets, dict):
|
||||
continue
|
||||
for name, on_value in widgets.items():
|
||||
off_value = (off.get(node_id) or {}).get(name)
|
||||
lora_rows = isinstance(on_value, str) and on_value.startswith("[")
|
||||
if isinstance(on_value, (dict, list)) or lora_rows or on_value == off_value:
|
||||
continue # a LoRA stack is matched row by row, and a shared value says nothing
|
||||
try:
|
||||
saved = saved_widget(node, name)
|
||||
except KeyError:
|
||||
continue
|
||||
if saved == on_value:
|
||||
sides.add("on")
|
||||
elif saved == off_value:
|
||||
sides.add("off")
|
||||
else:
|
||||
sides.add(f"neither ({node_id} {name} is {saved!r}, not {on_value!r} or {off_value!r})")
|
||||
members = [by_id[i] for i in row.get("nodes") or [] if i in by_id]
|
||||
modes = {"on" if m.get("mode", 0) == 0 else "off" for m in members}
|
||||
if len(modes) > 1:
|
||||
problems.append(f"switch card {card['id']} row '{title}': some of its nodes are on and some off")
|
||||
odd = sorted(side for side in sides if side not in ("on", "off"))
|
||||
if odd or len(sides) > 1 or (sides and modes and sides != modes):
|
||||
detail = "; ".join(odd) if odd else f"values say {'/'.join(sorted(sides))}, nodes say {'/'.join(sorted(modes)) or '-'}"
|
||||
problems.append(f"switch card {card['id']} row '{title}' opens as changed: {detail}")
|
||||
return problems
|
||||
|
||||
|
||||
def workflow_problems(data: dict) -> list[str]:
|
||||
problems = []
|
||||
nodes = data.get("nodes", [])
|
||||
@@ -112,6 +164,8 @@ def workflow_problems(data: dict) -> list[str]:
|
||||
problems.append(f"saved zoom {scale} is below {MIN_ZOOM}; widget text would not draw")
|
||||
for n in nodes:
|
||||
problems.extend(named_copy_problems(n))
|
||||
if n["type"] == "AUSBOSS_NODES_WorkflowSwitches":
|
||||
problems.extend(switch_row_problems(n, by_id))
|
||||
if n["type"] in CORE_LORA_LOADERS:
|
||||
problems.append(f"node {n['id']} loads a LoRA with core {n['type']}; examples use LoRA Loader 🆎")
|
||||
selected = selected_files(n)
|
||||
|
||||
Vendored
+20
@@ -490,6 +490,26 @@
|
||||
]
|
||||
]
|
||||
},
|
||||
"AUSBOSS_NODES_LoadAudio": {
|
||||
"required": [
|
||||
"audio",
|
||||
"start_seconds",
|
||||
"end_seconds"
|
||||
],
|
||||
"optional": [
|
||||
"max_seconds"
|
||||
],
|
||||
"outputs": [
|
||||
[
|
||||
"AUDIO",
|
||||
"audio"
|
||||
],
|
||||
[
|
||||
"FLOAT",
|
||||
"seconds"
|
||||
]
|
||||
]
|
||||
},
|
||||
"AUSBOSS_NODES_LoadImagePad": {
|
||||
"required": [
|
||||
"image",
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { grabZone, outputSummary, outputWindow, wavePeaks } from "../js/load_audio/audio_window.mjs";
|
||||
|
||||
test("the face shows what the node hands on", () => {
|
||||
// Mirrors audio_window in nodes/_audio_trim_helpers.py.
|
||||
assert.deepEqual(outputWindow(40, 8, 30, 15), { start: 8, end: 30, keepEnd: 23, length: 15, cut: 7 });
|
||||
assert.deepEqual(outputWindow(40, 8, 12, 15), { start: 8, end: 12, keepEnd: 12, length: 4, cut: 0 });
|
||||
assert.equal(outputWindow(40, 5, 0, 0).end, 40, "OUT 0 means the end of the file");
|
||||
assert.equal(outputWindow(40, 30, 0, 20).keepEnd, 40, "a max past the end stops at the end");
|
||||
assert.equal(outputWindow(10, 50, 0).start, 10, "a start past the end is held at the end");
|
||||
assert.equal(outputWindow(10, "x", null, NaN).length, 10);
|
||||
});
|
||||
|
||||
test("the line between IN and OUT says how long and what is cut", () => {
|
||||
assert.equal(outputSummary(outputWindow(40, 8, 30, 15)), "15.0 s · cut 7.0 s");
|
||||
assert.equal(outputSummary(outputWindow(200, 0, 0, 0)), "3:20.0");
|
||||
assert.equal(outputSummary(outputWindow(40, 8, 30, 0), { maxFromLink: true }), "22.0 s · max wired");
|
||||
assert.equal(outputSummary(outputWindow(0, 0, 0)), "");
|
||||
});
|
||||
|
||||
test("a press grabs the nearest handle, the middle, or jumps", () => {
|
||||
const win = outputWindow(40, 10, 30);
|
||||
assert.equal(grabZone(win, 40, 0.25, 400), "start");
|
||||
assert.equal(grabZone(win, 40, 0.75, 400), "end");
|
||||
assert.equal(grabZone(win, 40, 0.5, 400), "move");
|
||||
assert.equal(grabZone(win, 40, 0.05, 400), "jump");
|
||||
assert.equal(grabZone(win, 0, 0.5, 400), "none");
|
||||
});
|
||||
|
||||
test("peaks keep the loudest sample of each slice, channels mixed", () => {
|
||||
const left = Float32Array.from([0, 0.5, -0.5, 0, 1, -1]);
|
||||
const right = Float32Array.from([0, 0.5, -0.5, 0, 1, -1]);
|
||||
const peaks = wavePeaks([left, right], 2);
|
||||
assert.deepEqual(Array.from(peaks), [-0.5, 0.5, -1, 1]);
|
||||
assert.equal(wavePeaks([], 3).length, 6);
|
||||
});
|
||||
@@ -116,6 +116,7 @@ test("a panel that should follow the node's height never declares computeSize",
|
||||
"image_folder",
|
||||
"input_preview",
|
||||
"layout_boxes",
|
||||
"load_audio",
|
||||
"load_image_pad",
|
||||
"load_video",
|
||||
"lora_loader",
|
||||
|
||||
@@ -184,3 +184,18 @@ test("different problems, other kinds of error and other packs' nodes are left a
|
||||
assert.equal(errors[2].errors.length, 2);
|
||||
assert.equal(collapseRepeatedErrors(null), null);
|
||||
});
|
||||
|
||||
test("an empty Load Audio asks for a sound file", () => {
|
||||
const outputs = (classType) => (classType === "SaveAudio"
|
||||
? { output_node: true, input: { required: { audio: ["AUDIO"] } } }
|
||||
: definitionOf(classType));
|
||||
const prompt = {
|
||||
1: node("AUSBOSS_NODES_LoadAudio", { audio: "" }, "Song"),
|
||||
2: node("SaveAudio", { audio: ["1", 0] }),
|
||||
};
|
||||
const found = findEmptySources(prompt, outputs);
|
||||
assert.deepEqual(found.map((entry) => entry.input), ["audio"]);
|
||||
assert.equal(emptySourceMessage(found), "Load a sound file first: Song");
|
||||
prompt[1].inputs.audio = "song.mp3";
|
||||
assert.deepEqual(findEmptySources(prompt, outputs), []);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
|
||||
del sys.modules["nodes"]
|
||||
|
||||
from nodes._audio_trim_helpers import audio_window, decode_audio_window
|
||||
|
||||
RATE = 8000
|
||||
|
||||
|
||||
def write_ramp(path: Path, seconds: float) -> None:
|
||||
"""A mono wav whose sample value tells the second it was written at."""
|
||||
samples = int(seconds * RATE)
|
||||
data = (np.arange(samples, dtype=np.float32) / RATE / 100.0).reshape(1, -1)
|
||||
with av.open(str(path), "w") as container:
|
||||
stream = container.add_stream("pcm_f32le", rate=RATE, layout="mono")
|
||||
frame = av.AudioFrame.from_ndarray(data, format="flt", layout="mono")
|
||||
frame.sample_rate = RATE
|
||||
for packet in stream.encode(frame):
|
||||
container.mux(packet)
|
||||
for packet in stream.encode(None):
|
||||
container.mux(packet)
|
||||
|
||||
|
||||
class AudioWindowTests(unittest.TestCase):
|
||||
def test_open_end_stays_open_until_the_length_is_known(self):
|
||||
self.assertEqual(audio_window(2, 0)["end"], None)
|
||||
self.assertEqual(audio_window(2, 0, duration=40)["end"], 40)
|
||||
|
||||
def test_max_keeps_the_start_and_cuts_the_rest(self):
|
||||
window = audio_window(8, 30, 15, duration=40)
|
||||
self.assertEqual((window["start"], window["end"], window["cut"]), (8, 23, 7))
|
||||
|
||||
def test_max_longer_than_the_pick_changes_nothing(self):
|
||||
window = audio_window(8, 12, 15, duration=40)
|
||||
self.assertEqual((window["end"], window["cut"]), (12, 0))
|
||||
|
||||
def test_max_with_an_open_end_caps_it(self):
|
||||
self.assertEqual(audio_window(5, 0, 10)["end"], 15)
|
||||
|
||||
def test_bad_values_fall_back(self):
|
||||
window = audio_window("x", None, float("nan"), duration=10)
|
||||
self.assertEqual((window["start"], window["end"], window["cut"]), (0, 10, 0))
|
||||
|
||||
def test_end_before_start_is_an_empty_pick(self):
|
||||
window = audio_window(6, 4, duration=10)
|
||||
self.assertEqual(window["end"], 6)
|
||||
|
||||
|
||||
class DecodeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self.folder.name, "ramp.wav")
|
||||
write_ramp(self.path, 10.0)
|
||||
|
||||
def tearDown(self):
|
||||
self.folder.cleanup()
|
||||
|
||||
def test_takes_exactly_the_pick(self):
|
||||
audio = decode_audio_window(self.path, 2.0, 5.0)
|
||||
waveform = audio["waveform"]
|
||||
self.assertEqual(audio["sample_rate"], RATE)
|
||||
self.assertEqual(tuple(waveform.shape), (1, 1, 3 * RATE))
|
||||
self.assertAlmostEqual(float(waveform[0, 0, 0]) * 100, 2.0, places=3)
|
||||
|
||||
def test_max_cuts_the_end(self):
|
||||
audio = decode_audio_window(self.path, 1.0, 9.0, 2.5)
|
||||
self.assertEqual(audio["waveform"].shape[-1], int(2.5 * RATE))
|
||||
|
||||
def test_open_end_runs_to_the_end_of_the_file(self):
|
||||
audio = decode_audio_window(self.path, 7.5, 0.0)
|
||||
self.assertEqual(audio["waveform"].shape[-1], int(2.5 * RATE))
|
||||
|
||||
def test_start_past_the_end_says_so(self):
|
||||
with self.assertRaisesRegex(ValueError, "past the end"):
|
||||
decode_audio_window(self.path, 12.0, 0.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -652,6 +652,12 @@ class VideoJobTests(unittest.TestCase):
|
||||
cast = Cast(number_pictures({1: "place"}, "copy its moves"), "copy its moves")
|
||||
self.assertIn("To copy the moves", cast.problem("She dances."))
|
||||
|
||||
def test_a_hat_with_no_person_picture_says_how_to_put_it_on_the_video_person(self):
|
||||
for job in ("outfit", "thing"):
|
||||
for video in ("swap the person", "copy its moves"):
|
||||
cast = Cast(number_pictures({1: job}, video), video)
|
||||
self.assertIn("load a still of them from the video as Picture 1", cast.problem("He wears @1."))
|
||||
|
||||
def test_a_swap_with_nobody_to_put_in_says_so(self):
|
||||
with self.assertRaisesRegex(ValueError, "new person"):
|
||||
write_prompt("", jobs={}, video="swap the person")
|
||||
@@ -676,6 +682,28 @@ class VideoJobTests(unittest.TestCase):
|
||||
self.assertIn("Everyone else stays", parts["detailed_description"])
|
||||
self.assertNotIn("Show one person", parts["detailed_description"])
|
||||
|
||||
def test_a_swap_with_two_people_puts_each_in_one_place(self):
|
||||
parts = parts_of("", jobs={1: "person", 2: "person"}, video="swap the person")
|
||||
self.assertIn("Replace <Subject 1> with <Subject 3> and <Subject 2> with <Subject 4>", parts["summary"])
|
||||
self.assertIn("<Subject 1> is the person on the left in <Video 1>", parts["subject_definitions"])
|
||||
self.assertIn("<Subject 2> is the person on the right in <Video 1>", parts["subject_definitions"])
|
||||
self.assertIn("<Subject 4> is the person in <Picture 2>", parts["subject_definitions"])
|
||||
self.assertIn("replace the person on the right with <Subject 4>", parts["retention_analysis"])
|
||||
self.assertIn("change only the people", parts["retention_analysis"])
|
||||
self.assertIn("<Subject 4> takes the place of the person on the right", parts["detailed_description"])
|
||||
self.assertNotIn("Show one person", parts["detailed_description"])
|
||||
|
||||
def test_a_swap_with_two_people_reads_who_goes_from_the_script(self):
|
||||
for script in ("@2 is the woman in red. @1 replaces the man in the hat", "The man in the hat.\nThe woman in red."):
|
||||
parts = parts_of(script, jobs={1: "person", 2: "character sheet"}, video="swap the person")
|
||||
self.assertIn("replace the man in the hat with <Subject 3>", parts["retention_analysis"])
|
||||
self.assertIn("replace the woman in red with <Subject 4>", parts["retention_analysis"])
|
||||
self.assertNotIn("@", join_sections(parts))
|
||||
|
||||
def test_one_swap_takes_the_at_out_of_who_goes(self):
|
||||
parts = parts_of("@1 replaces the child in the seat", jobs={1: "person"}, video="swap the person")
|
||||
self.assertIn("replace the child in the seat with <Subject 2>", parts["retention_analysis"])
|
||||
|
||||
def test_keeping_going_needs_no_words_and_no_picture(self):
|
||||
parts = parts_of("", jobs={}, video="keep going")
|
||||
self.assertTrue(parts["summary"].startswith("[video continuation]"))
|
||||
|
||||
@@ -43,6 +43,7 @@ NAMED = {
|
||||
"AusBossImageCropRotatePad": ["image"],
|
||||
"AusBossImageFolder": ["source", "folder"],
|
||||
"AusBossLaMaInpaint": ["model"],
|
||||
"AusBossLoadAudio": ["audio"],
|
||||
"AusBossLoadImagePad": ["image", "source_image"],
|
||||
"AusBossLoadVideo": ["video"],
|
||||
"AusBossLoraLoader": ["loras", "on_missing"],
|
||||
|
||||
@@ -38,6 +38,24 @@ class WorkflowContractTests(unittest.TestCase):
|
||||
graph["nodes"][0]["widgets_values_named"] = {"video": "someone_else.mp4", "start_seconds": 0, "upload": ""}
|
||||
self.assertIn("stale named widget values: video", " ".join(workflow_problems(graph)))
|
||||
|
||||
def test_a_switch_row_must_open_plainly_off_or_on(self):
|
||||
graph = good_graph()
|
||||
graph["nodes"][0]["widgets_values"] = {"megapixels": 0.41}
|
||||
card = {"id": 4, "type": "AUSBOSS_NODES_WorkflowSwitches", "pos": [0, 300], "size": [100, 40], "properties": {
|
||||
"ausboss_workflow_switches": {"switches": [{"id": 9, "title": "Fast test", "nodes": [],
|
||||
"on": {"1": {"megapixels": 0.26}}, "off": {"1": {"megapixels": 1}}}]}}}
|
||||
graph["nodes"].append(card)
|
||||
graph["last_node_id"] = 4
|
||||
graph["groups"][0]["bounding"] = [-20, 40, 320, 320]
|
||||
self.assertIn("row 'Fast test' opens as changed", " ".join(workflow_problems(graph)))
|
||||
card["properties"]["ausboss_workflow_switches"]["switches"][0]["off"] = {"1": {"megapixels": 0.41}}
|
||||
self.assertEqual(workflow_problems(graph), [])
|
||||
graph["nodes"][1]["widgets_values"] = {"steps": 8}
|
||||
graph["nodes"][1]["mode"] = 4
|
||||
card["properties"]["ausboss_workflow_switches"]["switches"].append(
|
||||
{"id": 10, "title": "Turbo", "nodes": [2], "on": {"2": {"steps": 8}}, "off": {"2": {"steps": 20}}})
|
||||
self.assertIn("row 'Turbo' opens as changed: values say on, nodes say off", " ".join(workflow_problems(graph)))
|
||||
|
||||
def test_workflow_id_and_zoom(self):
|
||||
graph = good_graph()
|
||||
graph["id"] = "3f2b8c1e-5d4a-4e6f-9a7b-1c2d3e4f5a6b"
|
||||
|
||||
Reference in New Issue
Block a user