refactor: change worker to run-once cron style script for missing videos

This commit is contained in:
Jannik committed 2026-09-05 19:05:59 +02:00
1 parent 72dd356175
commit 71007c880a
2 files changed
+104 -121

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0"
echo Starte zyklischen Viz Auto-Render Check...
node worker.mjs
+100 -121
View File
@@ -1,121 +1,99 @@
import fs from 'fs';
import path from 'path';
import chokidar from 'chokidar';
import puppeteer from 'puppeteer';
import fetch from 'node-fetch';
import { pipeline } from 'stream/promises';
const WATCH_DIR = 'D:/Google Drive/Videos/AIWentNonsense/*/Viz';
const BASE_DIR = 'D:/Google Drive/Videos/AIWentNonsense';
const VIZ_URL = 'http://localhost:3000';
const NTFY_URL = 'https://ntfy.orfel.de/viz_errors';
const queue = [];
let isProcessing = false;
// Initialize watcher
const watcher = chokidar.watch(WATCH_DIR, {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true,
depth: 0
});
console.log(`\n👁️ Watching for JSON presets in: ${WATCH_DIR}\n`);
watcher.on('add', async (filePath) => {
// Ignoriere Dateien in done/ oder failed/
if (
filePath.toLowerCase().endsWith('.json') &&
!filePath.includes('\\done\\') && !filePath.includes('/done/') &&
!filePath.includes('\\failed\\') && !filePath.includes('/failed/')
) {
console.log(`\n📥 Neues Preset gefunden: ${filePath}`);
queue.push(filePath);
processQueue();
async function main() {
console.log(`\n🔍 Suche nach anstehenden Render-Jobs in: ${BASE_DIR}\n`);
if (!fs.existsSync(BASE_DIR)) {
console.error(`Ordner nicht gefunden: ${BASE_DIR}`);
process.exit(1);
}
});
async function processQueue() {
if (isProcessing || queue.length === 0) return;
isProcessing = true;
const filePath = queue.shift();
const dirName = path.dirname(filePath);
// ensure done/ failed/ folders exist
fs.mkdirSync(path.join(dirName, 'done'), { recursive: true });
fs.mkdirSync(path.join(dirName, 'failed'), { recursive: true });
const fileName = path.basename(filePath);
try {
await processPreset(filePath);
// Move to done
fs.renameSync(filePath, path.join(dirName, 'done', fileName));
console.log(`✅ Job abgeschlossen und verschoben nach done/${fileName}`);
} catch (err) {
console.error(`\n❌ Fehler bei der Verarbeitung von ${fileName}:`, err.message);
// Write error log
fs.writeFileSync(path.join(dirName, 'failed', fileName + '.error.log'), err.stack || err.message);
// Move to failed
fs.renameSync(filePath, path.join(dirName, 'failed', fileName));
// Send ntfy notification
try {
await fetch(NTFY_URL, {
method: 'POST',
body: `Viz Auto-Render fehlgeschlagen für ${fileName}: ${err.message}`,
headers: {
'Title': 'Viz Render Error',
'Tags': 'warning,video'
const songFolders = fs.readdirSync(BASE_DIR, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
const pendingJobs = [];
for (const folder of songFolders) {
const vizDir = path.join(BASE_DIR, folder, 'Viz');
if (!fs.existsSync(vizDir)) continue;
const files = fs.readdirSync(vizDir);
for (const file of files) {
if (file.toLowerCase().endsWith('.json')) {
const jsonPath = path.join(vizDir, file);
try {
const job = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
// Zieldateiname bestimmen
const targetFormat = job.format === 'prores4444' ? 'prores' : (job.format || 'prores');
const outExt = (targetFormat === 'prores' || targetFormat === 'qtrle') ? '.mov' : (targetFormat === 'webm_alpha' ? '.webm' : '.mp4');
const finalTitle = job.title ? job.title.replace(/[^a-zA-Z0-9_-]/g, '_') : 'Output';
const expectedVideoPath = path.join(vizDir, `${finalTitle}${outExt}`);
// Job nur vormerken, wenn das Video noch NICHT existiert
if (!fs.existsSync(expectedVideoPath)) {
pendingJobs.push({ jsonPath, job, expectedVideoPath, targetFormat });
}
} catch (e) {
console.error(`⚠️ Fehler beim Lesen von ${jsonPath}: ${e.message}`);
}
});
console.log('📬 Ntfy-Benachrichtigung gesendet.');
} catch (ntfyErr) {
console.error('⚠️ Konnte Ntfy Benachrichtigung nicht senden:', ntfyErr.message);
}
}
}
isProcessing = false;
// Nächsten Job starten
setTimeout(processQueue, 1000);
if (pendingJobs.length === 0) {
console.log('✅ Keine neuen JSON-Dateien ohne zugehöriges Video gefunden. Beende.');
process.exit(0);
}
console.log(`🚀 ${pendingJobs.length} anstehende(r) Job(s) gefunden.`);
for (const jobItem of pendingJobs) {
await processJob(jobItem);
}
console.log('\n🎉 Alle Jobs abgearbeitet!');
process.exit(0);
}
async function processPreset(presetPath) {
const jobRaw = fs.readFileSync(presetPath, 'utf8');
let job;
try {
job = JSON.parse(jobRaw);
} catch(e) {
throw new Error('Ungültiges JSON-Format: ' + e.message);
}
async function processJob({ jsonPath, job, expectedVideoPath, targetFormat }) {
const fileName = path.basename(jsonPath);
console.log(`\n---------------------------------------------------`);
console.log(`🎬 Starte Render-Job für: ${job.title} (${job.id})`);
console.log(`\n🎬 Starte Render-Job für: ${job.title} (${job.id})`);
const audioFileAbs = path.resolve(path.dirname(presetPath), job.audio);
const audioFileAbs = path.resolve(path.dirname(jsonPath), job.audio);
if (!fs.existsSync(audioFileAbs)) {
throw new Error(`Audiodatei nicht gefunden: ${audioFileAbs}`);
console.error(`❌ Audiodatei nicht gefunden: ${audioFileAbs}`);
await sendError(fileName, `Audiodatei nicht gefunden: ${audioFileAbs}`);
return;
}
console.log(`🎵 Audio geladen: ${audioFileAbs}`);
const browser = await puppeteer.launch({
headless: 'new',
args: [
'--autoplay-policy=no-user-gesture-required',
'--use-gl=egl',
'--ignore-gpu-blocklist',
'--enable-gpu-rasterization',
'--mute-audio',
'--window-size=1920,1080'
]
});
let browser;
try {
browser = await puppeteer.launch({
headless: 'new',
args: [
'--autoplay-policy=no-user-gesture-required',
'--use-gl=egl',
'--ignore-gpu-blocklist',
'--enable-gpu-rasterization',
'--mute-audio',
'--window-size=1920,1080'
]
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
@@ -161,22 +139,17 @@ async function processPreset(presetPath) {
}
window.VIZ_API.updateConfigFromUI();
}, job.title, job.artist, job.aspect, job.format || 'prores');
}, job.title, job.artist, job.aspect, targetFormat);
// 4. Render-Knopf drücken
console.log('🚀 Starte Export-Prozess...');
await page.click('#btnStartExport');
// 5. Überwache den History API Endpunkt bis der Job done ist
// 5. Überwache den History API Endpunkt
console.log('⏳ Warte auf den Abschluss des Renderings...');
let isDone = false;
let targetFormat = job.format === 'prores4444' ? 'prores' : (job.format || 'prores');
if (targetFormat === 'prores4444') targetFormat = 'prores';
let lastStatus = '';
// Kurz warten bis die Session in der History auftaucht
await new Promise(r => setTimeout(r, 4000));
const historyRes = await fetch(`${VIZ_URL}/api/export/history`);
@@ -190,18 +163,13 @@ async function processPreset(presetPath) {
await new Promise(r => setTimeout(r, 2000));
const pollRes = await fetch(`${VIZ_URL}/api/export/history`);
if (!pollRes.ok) continue; // Server vllt kurz busy
if (!pollRes.ok) continue;
const hData = await pollRes.json();
const sess = hData.find(s => s.id === sessionId);
if (!sess) {
throw new Error('Session plötzlich verschwunden');
}
if (sess.error) {
throw new Error('Server Render Fehler: ' + sess.error);
}
if (!sess) throw new Error('Session plötzlich verschwunden');
if (sess.error) throw new Error('Server Render Fehler: ' + sess.error);
if (sess.currentStatus !== lastStatus) {
lastStatus = sess.currentStatus;
@@ -210,29 +178,40 @@ async function processPreset(presetPath) {
if (sess.done && sess.formats[targetFormat] && sess.formats[targetFormat].ready) {
isDone = true;
const serverPath = sess.formats[targetFormat].path;
const outExt = (targetFormat === 'prores' || targetFormat === 'qtrle') ? '.mov' : (targetFormat === 'webm_alpha' ? '.webm' : '.mp4');
const finalTitle = job.title ? job.title.replace(/[^a-zA-Z0-9_-]/g, '_') : 'Output';
const finalDest = path.join(path.dirname(presetPath), `${finalTitle}${outExt}`);
console.log(`\n💾 Kopiere fertiges Video nach: ${finalDest}`);
console.log(`\n💾 Speichere Video: ${expectedVideoPath}`);
if (fs.existsSync(serverPath)) {
fs.copyFileSync(serverPath, finalDest);
fs.copyFileSync(serverPath, expectedVideoPath);
} else {
// Fallback HTTP Download falls Pfade lokal nicht uebereinstimmen
console.log(` Lokale Datei ${serverPath} nicht gefunden. Lade über HTTP herunter...`);
const res = await fetch(`${VIZ_URL}/api/export/download/${sessionId}/${targetFormat}`);
if (!res.ok) throw new Error('HTTP Download fehlgeschlagen');
await pipeline(res.body, fs.createWriteStream(finalDest));
await pipeline(res.body, fs.createWriteStream(expectedVideoPath));
}
console.log(`✅ Video erfolgreich erstellt!`);
} else if (sess.done) {
// done ist true, aber das gewünschte Format ist nicht da?
throw new Error(`Render abgeschlossen, aber Format ${targetFormat} nicht verfügbar.`);
}
}
} catch (err) {
console.error(`\n❌ Fehler bei ${fileName}:`, err.message);
await sendError(fileName, err.message);
} finally {
await browser.close();
if (browser) await browser.close();
}
}
async function sendError(fileName, message) {
try {
await fetch(NTFY_URL, {
method: 'POST',
body: `Viz Auto-Render fehlgeschlagen für ${fileName}: ${message}`,
headers: { 'Title': 'Viz Render Error', 'Tags': 'warning,video' }
});
} catch (e) {
console.error('⚠️ Konnte Ntfy Benachrichtigung nicht senden:', e.message);
}
}
main();