fix: Readiness pro answer_type + Objekt-Zuweisung & Audio-Nachholen im Publish-Flow

- computeReadiness: yes_no braucht keinen Positiv-Satz (nur answer-Flag),
  word-Pairs prüfen verlinkte Wörter (Titel + Audio) statt Statement-Sätze
  → behebt 'bei jedem Pair fehlt ein Audio' im Publish-Review
- Bundle liefert Placeholder-Kandidaten: Objekt-Wörter, die im deutschen
  Satz vorkommen (außerhalb bestehender Placeholder, inkl. Flexion)
- POST /pipeline/assign-object: Wort in allen 3 Sprachen als
  {{wort.o:objectId}} markieren (über die Wort-Übersetzungen)
- POST /pipeline/picture/:id/audio-fill: fehlende Audios nachgenerieren

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-10 21:48:03 +02:00
parent 6af2428df5
commit fb93d2296e
3 changed files with 178 additions and 18 deletions

View File

@@ -3,7 +3,49 @@ const router = require('express').Router();
const { query } = require('../db');
const { LANGS } = require('../lib/translate');
const { loadPairContext, computeReadiness, loadPairContent } = require('../lib/pairContent');
const { enqueue } = require('../lib/pipeline');
const { enqueue, loadPairs, collectAudioUnits, generateWithBackoff } = require('../lib/pipeline');
const { PLACEHOLDER_RE } = require('../lib/placeholders');
// ── Objekt-Wort-Erkennung in Sätzen (für die manuelle Zuweisung beim Review) ──
// Findet `title` als eigenständiges Wort (inkl. einfacher Flexionsendung) außerhalb
// bestehender Placeholder. Liefert den getroffenen Text oder null.
function findWordInSentence(sentence, title) {
if (!sentence || !(title || '').trim()) return null;
const esc = title.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`(?<![A-Za-zÄÖÜäöüßÅÄÖåäö])(${esc}[a-zäöüßåö]{0,2})(?![A-Za-zÄÖÜäöüßÅÄÖåäö])`, 'iu');
// Nur außerhalb von {{…}} suchen
const segments = sentence.split(PLACEHOLDER_RE);
// split mit Capture-Groups liefert [text, label, type, uuid, text, …] → nur die Text-Segmente (Schrittweite 4)
for (let i = 0; i < segments.length; i += 4) {
const m = (segments[i] || '').match(re);
if (m) return m[1];
}
return null;
}
// Ersetzt das erste Vorkommen von `title` (außerhalb von Placeholdern) durch {{match.o:objectId}}.
function wrapWordAsObject(sentence, title, objectId) {
const hit = findWordInSentence(sentence, title);
if (!hit) return null;
// Sicher ersetzen: Satz an Placeholdern entlang neu zusammensetzen
const parts = [];
let replaced = false;
const tokens = sentence.split(/(\{\{[^}]+\}\})/g);
for (const t of tokens) {
if (!replaced && !t.startsWith('{{')) {
const idx = t.toLowerCase().indexOf(hit.toLowerCase());
if (idx >= 0) {
const actual = t.slice(idx, idx + hit.length);
parts.push(t.slice(0, idx) + `{{${actual}.o:${objectId}}}` + t.slice(idx + hit.length));
replaced = true;
continue;
}
}
parts.push(t);
}
return replaced ? parts.join('') : null;
}
// POST /api/pipeline/release/:pictureId — Bild in die Pipeline geben
router.post('/release/:pictureId', async (req, res, next) => {
@@ -80,8 +122,17 @@ router.get('/picture/:id/bundle', async (req, res, next) => {
WHERE op.object_id = $1 AND p.status <> 'blocked'
ORDER BY p.created_at`, [obj.id])).rows;
obj.pairs = pairs;
}
// Objekt-Wort-Kandidaten: alle Wörter aller Objekte dieses Bildes
const objectWordCandidates = objects.flatMap(o =>
o.words.filter(w => (w.titel_de || '').trim())
.map(w => ({ object_id: o.id, word_id: w.id, titel_de: w.titel_de })));
for (const obj of objects) {
// Audio-Abdeckung pro Pair × Sprache (für die 🔊-Indikatoren)
for (const p of pairs) {
for (const p of obj.pairs) {
p.content = await loadPairContent(p);
p.audio = {};
for (const lang of LANGS) {
@@ -89,15 +140,91 @@ router.get('/picture/:id/bundle', async (req, res, next) => {
const r = computeReadiness(p, ctx, lang, { skipPicturePublished: true, skipStatusChecks: true });
p.audio[lang] = { ready: r.ready, missing: r.missing };
}
// Placeholder-Kandidaten: Objekt-Wörter, die im deutschen Satz vorkommen,
// aber noch keinem Objekt zugewiesen sind (manuelle Zuweisung im Review).
p.candidates = [];
const fields = [
['questions', p.question_id, 'sentence', p.content.question?.sentence_de],
['statements', p.positive_statement_id, 'positive_sentence', p.content.positive?.sentence?.positive_sentence_de],
['statements', p.negative_statement_id, 'negative_sentence', p.content.negative?.sentence?.negative_sentence_de],
];
for (const [table, id, field, sentence] of fields) {
if (!id || !(sentence || '').trim()) continue;
for (const cand of objectWordCandidates) {
const hit = findWordInSentence(sentence, cand.titel_de);
if (hit) p.candidates.push({
source_table: table, source_id: id, source_field: field,
object_id: cand.object_id, word_id: cand.word_id, label: hit,
});
}
}
delete p.question_id; delete p.positive_statement_id; delete p.negative_statement_id;
}
obj.pairs = pairs;
}
res.json({ picture, objects });
} catch (err) { next(err); }
});
// POST /api/pipeline/assign-object — markiert ein Wort im Satz als Objekt-Referenz
// Body: { source_table, source_id, source_field, object_id, word_id }
// Ersetzt das Wort in ALLEN Sprachen (über die Wort-Übersetzungen) durch {{wort.o:objectId}}.
router.post('/assign-object', async (req, res, next) => {
try {
const { source_table, source_id, source_field, object_id, word_id } = req.body || {};
const FIELDS = { questions: ['sentence'], statements: ['positive_sentence', 'negative_sentence'] };
if (!FIELDS[source_table]?.includes(source_field))
return res.status(400).json({ error: 'Ungültige source_table/source_field' });
if (!source_id || !object_id || !word_id)
return res.status(400).json({ error: 'source_id, object_id und word_id sind Pflicht' });
const obj = await query(`SELECT id FROM objects WHERE id = $1`, [object_id]);
if (!obj.rows.length) return res.status(404).json({ error: 'Objekt nicht gefunden' });
const wr = await query(`SELECT titel_de, titel_en, titel_sv FROM words WHERE id = $1`, [word_id]);
if (!wr.rows.length) return res.status(404).json({ error: 'Wort nicht gefunden' });
const word = wr.rows[0];
const cols = LANGS.map(l => `${source_field}_${l}`);
const rr = await query(`SELECT ${cols.join(', ')} FROM ${source_table} WHERE id = $1`, [source_id]);
if (!rr.rows.length) return res.status(404).json({ error: 'Satz-Zeile nicht gefunden' });
const row = rr.rows[0];
const updates = {}, updated = [], skipped = [];
for (const l of LANGS) {
const sentence = row[`${source_field}_${l}`] || '';
const wrapped = wrapWordAsObject(sentence, word[`titel_${l}`], object_id);
if (wrapped) { updates[`${source_field}_${l}`] = wrapped; updated.push(l); }
else skipped.push(l);
}
if (updated.length) {
const cells = Object.keys(updates);
await query(
`UPDATE ${source_table} SET ${cells.map((c, i) => `${c} = $${i + 1}`).join(', ')} WHERE id = $${cells.length + 1}`,
[...cells.map(c => updates[c]), source_id]);
}
res.json({ updated_langs: updated, skipped_langs: skipped });
} catch (err) { next(err); }
});
// POST /api/pipeline/picture/:id/audio-fill — fehlende Audios dieses Bildes nachgenerieren
router.post('/picture/:id/audio-fill', async (req, res, next) => {
try {
const pairs = await loadPairs(req.params.id);
if (!pairs.length) return res.status(400).json({ error: 'Bild hat keine Pairs' });
const units = (await collectAudioUnits(req.params.id, pairs)).filter(u => !u.hasAudio);
const result = { generated: 0, failed: 0, errors: [] };
for (const u of units) {
try { await generateWithBackoff(u); result.generated++; }
catch (err) {
result.failed++;
result.errors.push({ source: `${u.source_table}/${u.source_field}/${u.language}`, error: err.message });
}
}
res.json(result);
} catch (err) { next(err); }
});
// GET /api/pipeline/settings
router.get('/settings', async (req, res, next) => {
try {