Merge pull request #10 from Matewoo/rework-ai-translate

Rework ai translate
This commit is contained in:
Mateo Körber Belmonte
2025-03-15 18:41:09 +01:00
committed by GitHub
5 changed files with 1080 additions and 58 deletions
+176 -8
View File
@@ -74,6 +74,17 @@ db.exec(`
) )
`); `);
db.exec(`
CREATE TABLE IF NOT EXISTS menu_entries_en (
date TEXT PRIMARY KEY,
week TEXT,
meat_main TEXT,
meat_side TEXT,
veggi_main TEXT,
veggi_side TEXT
)
`);
db.exec(` db.exec(`
CREATE TABLE IF NOT EXISTS daily_entries ( CREATE TABLE IF NOT EXISTS daily_entries (
date TEXT PRIMARY KEY, date TEXT PRIMARY KEY,
@@ -92,6 +103,17 @@ db.exec(`
) )
`); `);
db.exec(`
CREATE TABLE IF NOT EXISTS daily_entries_en (
date TEXT PRIMARY KEY,
week TEXT,
day_index INTEGER,
daily_main TEXT,
daily_side TEXT,
daily_soup TEXT
)
`);
// LDAP-Authentifizierung Route // LDAP-Authentifizierung Route
app.post('/login', async (req, res) => { app.post('/login', async (req, res) => {
const { username, password } = req.body; const { username, password } = req.body;
@@ -308,6 +330,36 @@ app.post('/save-week', requireLogin, (req, res) => {
} }
}); });
app.post('/save-week-en', requireLogin, (req, res) => {
const { week, entries } = req.body;
const insert = db.prepare(`
INSERT OR REPLACE INTO menu_entries_en (date, week, meat_main, meat_side, veggi_main, veggi_side)
VALUES (?, ?, ?, ?, ?, ?)
`);
const transaction = db.transaction((entries) => {
for (const entry of entries) {
insert.run(
entry.date,
week,
entry.meatMain,
entry.meatSide,
entry.veggiMain,
entry.veggiSide,
);
}
});
try {
transaction(entries);
res.json({ message: 'Woche erfolgreich gespeichert' });
} catch (error) {
console.error('Error saving week:', error);
res.status(500).json({ error: 'Fehler beim Speichern der Woche' });
}
});
app.post('/save-week-daily', requireLogin, (req, res) => { app.post('/save-week-daily', requireLogin, (req, res) => {
const { week, entries } = req.body; const { week, entries } = req.body;
@@ -345,6 +397,36 @@ app.post('/save-week-daily', requireLogin, (req, res) => {
} }
}); });
app.post('/save-week-daily-en', requireLogin, (req, res) => {
const { week, entries } = req.body;
const insert = db.prepare(`
INSERT OR REPLACE INTO daily_entries_en (date, week, day_index, daily_main, daily_side, daily_soup)
VALUES (?, ?, ?, ?, ?, ?)
`);
const transaction = db.transaction((entries) => {
for (const entry of entries) {
insert.run(
entry.date,
entry.week,
entry.dayIndex,
entry.dailyMain,
entry.dailySide,
entry.dailySoup
);
}
});
try {
transaction(entries);
res.json({ message: 'Woche erfolgreich gespeichert' });
} catch (error) {
console.error('Error saving week:', error);
res.status(500).json({ error: 'Fehler beim Speichern der Woche' });
}
});
app.post('/generate-pdf', requireLogin, (req, res) => { app.post('/generate-pdf', requireLogin, (req, res) => {
const { val, type, trans } = req.body; const { val, type, trans } = req.body;
let pdfPath; let pdfPath;
@@ -393,24 +475,86 @@ app.post('/generate-pdf', requireLogin, (req, res) => {
} }
}); });
// Route for AI translation requests
app.post('/ai-request', requireAdmin, async (req, res) => { app.post('/ai-request', requireAdmin, async (req, res) => {
try { try {
const { prompt } = req.body; // Extract parameters from request body
const { prompt, systemPrompt, menuItems, menuType } = req.body;
const completion = await openai.chat.completions.create({ console.log('\n==== AI REQUEST DEBUG INFO ====');
console.log('Request Body:', JSON.stringify(req.body, null, 2));
console.log('Menu Type:', menuType);
// Define specialized prompts for different menu types
const specializedPrompts = {
weekly: `Du bist ein professioneller Übersetzer. Übersetze den folgenden Speiseplan ins Englische. Begriffe in Anführungszeichen sind Fachbegriffe oder Eigennamen und dürfen NICHT übersetzt werden. Falls ein Begriff nicht übersetzt wird, bleibt er im Output in Anführungszeichen. Die Übersetzung soll natürlich klingen: Hauptgericht und Beilage sollen mit Worten verbunden sein (Also zb statt Zeile1: Turkey schnitzel with pepper sauce, Zeile2: spaghetti; Sollst Du schreiben Zeile1: Turkey schnitzel with pepper sauce, Zeile2: served with spaghetti), aber dennoch in ZWEI getrennten Zeilen stehen. Gib das Ergebnis in folgendem Format zurück. Alles bitte in eine Zeile, ohne Leerzeichen zwischen den Json Parametern: [{'main_course':'<Hauptgericht in natürlicher Formulierung>','side_dish':'<Beilage in natürlicher Formulierung>'},{'main_course':'<Hauptgericht in natürlicher Formulierung>','side_dish':'<Beilage in natürlicher Formulierung>'}]`,
daily: `Du bist ein professioneller Übersetzer. Übersetze den folgenden Tagesgerichte-Plan ins Englische. Begriffe in Anführungszeichen sind Fachbegriffe oder Eigennamen und dürfen NICHT übersetzt werden. Falls ein Begriff nicht übersetzt wird, bleibt er im Output in Anführungszeichen. Die Übersetzung soll natürlich klingen: Hauptgericht und Beilage sollen mit Worten verbunden sein, und die Suppe soll separat übersetzt werden. Tagesgerichte und Suppen sollen in getrennten Einträgen stehen. Beispiel für ein Tagesgericht: Main: "Turkey schnitzel with pepper sauce", Side: "served with spaghetti", und für eine Suppe: Main: "Tomato soup with basil", Side: "". Gib das Ergebnis in folgendem Format zurück. Alles bitte in eine Zeile, ohne Leerzeichen zwischen den Json Parametern: [{'main_course':'<Hauptgericht in natürlicher Formulierung>','side_dish':'<Beilage in natürlicher Formulierung>'},{'main_course':'<Suppe in natürlicher Formulierung>','side_dish':''}]`
};
// Construct messages array based on available parameters
const messages = [];
// Choose the appropriate system prompt based on menuType
let effectiveSystemPrompt = systemPrompt;
if (menuType && specializedPrompts[menuType]) {
effectiveSystemPrompt = specializedPrompts[menuType];
console.log('Using specialized prompt for:', menuType);
}
// Add system message if provided
if (effectiveSystemPrompt) {
messages.push({ role: "system", content: effectiveSystemPrompt });
console.log('System prompt used:', effectiveSystemPrompt);
// If using structured menu items
if (menuItems && Array.isArray(menuItems)) {
let userPrompt = "";
menuItems.forEach(item => {
userPrompt += `- ${item.main}`;
if (item.side) {
userPrompt += ` ${item.side}`;
}
userPrompt += "\n";
});
messages.push({ role: "user", content: userPrompt });
console.log('User prompt constructed from menu items:', userPrompt);
}
}
// Fall back to simple prompt if no structured data
else if (prompt) {
messages.push({ role: "user", content: prompt });
console.log('Direct prompt used:', prompt);
} else {
throw new Error("No prompt provided");
}
console.log('Complete message array sent to OpenAI:', JSON.stringify(messages, null, 2));
// Prepare request for OpenAI
const requestOptions = {
model: "gpt-4o-mini", model: "gpt-4o-mini",
messages: [ messages: messages
{ role: "system", content: "Du bist ein professioneller Übersetzer. Übersetze den folgenden Speiseplan ins Englische. Begriffe in Anführungszeichen sind Fachbegriffe oder Eigennamen und dürfen NICHT übersetzt werden. Falls ein Begriff nicht übersetzt wird, bleibt er im Output in Anführungszeichen. Die Übersetzung soll natürlich klingen: Hauptgericht und Beilage sollen mit worten verbunden sein (Also zb statt Zeile1: Turkey schnitzel with pepper sauce, Zeile2: spaghetti; Sollst Du schreiben Zeile1: Turkey schnitzel with pepper sauce, Zeile2: served with spaghetti), aber dennoch in ZWEI getrennten Zeilen stehen. Gib das Ergebnis in folgendem Format zurück. Alles bitte in eine Zeile, ohne Leerzeichen zwischen den Json Parametern: [{'main_course':'<Hauptgericht in natürlicher Formulierung>','side_dish':'<Beilage in natürlicher Formulierung>'},{'main_course':'<Hauptgericht in natürlicher Formulierung>','side_dish':'<Beilage in natürlicher Formulierung>'}]" }, };
{ role: "user", content: prompt } console.log('OpenAI request options:', JSON.stringify(requestOptions, null, 2));
]
}); // Send request to OpenAI
const completion = await openai.chat.completions.create(requestOptions);
console.log('\n==== AI RESPONSE DEBUG INFO ====');
console.log('Complete OpenAI response:', JSON.stringify(completion, null, 2));
const messageContent = completion.choices[0].message.content; const messageContent = completion.choices[0].message.content;
console.log('Extracted message content:', messageContent);
console.log('============================\n');
res.json({ result: messageContent }); res.json({ result: messageContent });
} catch (error) { } catch (error) {
console.error('OpenAI API error:', error); console.error('OpenAI API error:', error);
res.status(500).json({ error: 'Error processing AI request' }); console.log('Error details:', error.response?.data || error.message);
res.status(500).json({ error: 'Error processing AI request: ' + error.message });
} }
}); });
@@ -427,6 +571,18 @@ app.get('/load-week', (req, res) => {
} }
}); });
app.get('/load-week-en', (req, res) => {
const { week } = req.query;
try {
const entries = db.prepare('SELECT * FROM menu_entries_en WHERE week = ?').all(week);
res.json(entries);
} catch (error) {
console.error('Error loading week:', error);
res.status(500).json({ error: 'Fehler beim Laden der Woche' });
}
});
app.get('/load-week-daily', (req, res) => { app.get('/load-week-daily', (req, res) => {
const { week } = req.query; const { week } = req.query;
@@ -439,6 +595,18 @@ app.get('/load-week-daily', (req, res) => {
} }
}); });
app.get('/load-week-daily-en', (req, res) => {
const { week } = req.query;
try {
const entries = db.prepare('SELECT * FROM daily_entries_en WHERE week = ?').all(week);
res.json(entries);
} catch (error) {
console.error('Error loading daily English translations:', error);
res.status(500).json({ error: 'Fehler beim Laden der englischen Tagesgerichte' });
}
});
app.get('/load-day-menu', (req, res) => { app.get('/load-day-menu', (req, res) => {
const { date } = req.query; const { date } = req.query;
+2
View File
@@ -61,6 +61,8 @@
<div class="bottom-controls"> <div class="bottom-controls">
<button onclick="saveWeek()">Tag speichern</button> <button onclick="saveWeek()">Tag speichern</button>
<button onclick="generatePDF('day')">PDF generieren</button> <button onclick="generatePDF('day')">PDF generieren</button>
<button onclick="displayEnglishTranslations()">Englisch anzeigen</button>
<button onclick="sendAiTranslateRequest()" class="admin-only">KI übersetzen</button>
</div> </div>
</div> </div>
+2 -1
View File
@@ -55,7 +55,8 @@
<div class="bottom-controls"> <div class="bottom-controls">
<button onclick="saveWeek()">Woche speichern</button> <button onclick="saveWeek()">Woche speichern</button>
<button onclick="generatePDF('week', '')">PDF generieren</button> <button onclick="generatePDF('week', '')">PDF generieren</button>
<button onclick="sendAiTranslateRequest()" class="admin-only">KI Übersetzung (Beta)</button> <button onclick="displayEnglishTranslations()">Englisch anzeigen</button>
<button onclick="sendAiTranslateRequest()" class="admin-only">KI übersetzen (Beta)</button>
<button onclick='sendTestTranslateRequest()' class="admin-only">Test KI Übersetzung (Beta)</button> <button onclick='sendTestTranslateRequest()' class="admin-only">Test KI Übersetzung (Beta)</button>
</div> </div>
</div> </div>
+621
View File
@@ -243,6 +243,627 @@ function loadWeekData(week) {
}); });
} }
async function sendAiTranslateRequest() {
try {
// Get current date for the active day
const currentDate = new Date(currentWeek);
currentDate.setDate(currentDate.getDate() + currentDayIndex);
const date = currentDate.toISOString().split('T')[0];
// Fetch the current day's data
const response = await fetch(`/load-day-daily?date=${encodeURIComponent(date)}`);
let entry;
try {
entry = await response.json();
} catch (e) {
console.error('Error parsing daily dish data:', e);
alert('Keine Daten für diesen Tag gefunden');
return;
}
if (!entry || (!entry.daily_main && !entry.daily_soup)) {
alert('Keine Daten zum Übersetzen für diesen Tag gefunden');
return;
}
// Construct menu item list
const menuItems = [];
// Add daily dish to menu items
if (entry.daily_main) {
menuItems.push({
main: entry.daily_main,
side: entry.daily_side || ''
});
}
// Add soup to menu items
if (entry.daily_soup) {
menuItems.push({
main: entry.daily_soup,
side: ''
});
}
// Create a structured request with system instructions
const requestData = {
menuItems: menuItems,
menuType: 'daily' // Specify that this is a daily menu
};
console.log('Sending request data:', requestData);
// Send to the AI service with the structured data
const aiResponse = await fetch('/ai-request', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
});
// Debugging for non-JSON responses
const contentType = aiResponse.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
const errorText = await aiResponse.text();
console.error('Non-JSON response received:', errorText);
throw new Error('Server returned non-JSON response. You might need to log in again or check server logs.');
}
const aiData = await aiResponse.json();
if (aiData.error) {
console.error('AI request failed:', aiData.error);
alert('AI-Übersetzung fehlgeschlagen: ' + aiData.error);
return;
}
// Process the result as before
let cleanedText = aiData.result
.trim()
.replace(/\n/g, '');
// Extract just the array part if needed
if (cleanedText.indexOf('[') >= 0) {
cleanedText = cleanedText.substring(cleanedText.indexOf('['));
if (!cleanedText.endsWith(']')) {
const lastBracket = cleanedText.lastIndexOf(']');
if (lastBracket > 0) {
cleanedText = cleanedText.substring(0, lastBracket + 1);
}
}
}
const parseJsObject = function(str) {
try {
return (new Function('return ' + str))();
} catch (e) {
console.error('Failed to parse:', e);
throw new Error('Invalid format in translation response');
}
};
try {
// Parse the translation data
const translations = parseJsObject(cleanedText);
console.log('Parsed translations:', translations);
// Create a single entry for the current day
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
// Clean quotes function to remove unwanted quotes
const cleanQuotes = (text) => {
if (typeof text !== 'string') return '';
// Remove starting and ending quotes if present
let cleaned = text.trim();
if ((cleaned.startsWith('"') && cleaned.endsWith('"')) ||
(cleaned.startsWith("'") && cleaned.endsWith("'"))) {
cleaned = cleaned.substring(1, cleaned.length - 1);
}
return cleaned;
};
const englishEntry = {
date: date,
week: week,
dayIndex: currentDayIndex,
dailyMain: '',
dailySide: '',
dailySoup: ''
};
let translationIndex = 0;
// Add daily dish translation
if (entry.daily_main && translations[translationIndex]) {
englishEntry.dailyMain = cleanQuotes(translations[translationIndex].main_course || '');
englishEntry.dailySide = cleanQuotes(translations[translationIndex].side_dish || '');
translationIndex++;
}
// Add soup translation
if (entry.daily_soup && translations[translationIndex]) {
englishEntry.dailySoup = cleanQuotes(translations[translationIndex].main_course || '');
translationIndex++;
}
console.log('Saving translation entry:', englishEntry);
// Save translation to database
const saveResponse = await fetch('/save-week-daily-en', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ week, entries: [englishEntry] })
});
if (!saveResponse.ok) {
const errorText = await saveResponse.text();
throw new Error(`Server response not OK: ${saveResponse.status} ${errorText}`);
}
const saveResult = await saveResponse.json();
alert('Englische Übersetzung wurde gespeichert.');
} catch (parseError) {
console.error('Error parsing or saving AI response:', parseError);
alert('Fehler beim Verarbeiten oder Speichern der KI-Antwort: ' + parseError.message);
}
} catch (error) {
console.error('Error sending AI request:', error);
alert('Fehler bei der KI-Anfrage: ' + error.message);
}
}
async function saveTranslationsToDatabase(translations, originalDishes = null) {
try {
// Get current week
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
let entries = [];
if (originalDishes === null) {
// Case 1: Called from sendAiTranslateRequest with full data
// Fetch the current week's daily dishes data
const response = await fetch(`/load-week-daily?week=${encodeURIComponent(week)}`);
const data = await response.json();
// Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index);
let translationIndex = 0;
// Map translations to database entries
data.forEach(entry => {
const englishEntry = {
date: entry.date,
week: week,
dayIndex: entry.day_index,
dailyMain: '',
dailySide: '',
dailySoup: ''
};
// Add daily dish translation
if (entry.daily_main && translations[translationIndex]) {
englishEntry.dailyMain = translations[translationIndex].main_course;
englishEntry.dailySide = translations[translationIndex].side_dish;
translationIndex++;
}
// Add soup translation
if (entry.daily_soup && translations[translationIndex]) {
englishEntry.dailySoup = translations[translationIndex].main_course;
translationIndex++;
}
entries.push(englishEntry);
});
} else {
// Case 2: Called from displayTranslation with form values
// Fetch the original data to get the dates
const response = await fetch(`/load-week-daily?week=${encodeURIComponent(week)}`);
const data = await response.json();
// Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index);
// Create entries with dates from original data
let translationIndex = 0;
data.forEach(entry => {
const englishEntry = {
date: entry.date,
week: week,
dayIndex: entry.day_index,
dailyMain: '',
dailySide: '',
dailySoup: ''
};
// Add daily dish translation if original has a daily dish
if (entry.daily_main && translations[translationIndex]) {
englishEntry.dailyMain = translations[translationIndex].main_course;
englishEntry.dailySide = translations[translationIndex].side_dish;
translationIndex++;
}
// Add soup translation if original has a soup
if (entry.daily_soup && translations[translationIndex]) {
englishEntry.dailySoup = translations[translationIndex].main_course;
translationIndex++;
}
entries.push(englishEntry);
});
}
// Save translations to database using the daily dish endpoint
const saveResponse = await fetch('/save-week-daily-en', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ week, entries })
});
const saveResult = await saveResponse.json();
return { success: true, message: 'Englische Übersetzungen wurden gespeichert.' };
} catch (error) {
console.error('Error saving translations to database:', error);
return { success: false, message: 'Fehler beim Speichern der Übersetzungen: ' + error.message };
}
}
function displayTranslation(translationText, originalDishes = []) {
try {
console.log('Original text:', translationText);
let cleanedText = translationText
.trim()
.replace(/\n/g, ''); // Remove any line breaks
// Extract just the array part if needed
if (cleanedText.indexOf('[') >= 0) {
cleanedText = cleanedText.substring(cleanedText.indexOf('['));
if (!cleanedText.endsWith(']')) {
const lastBracket = cleanedText.lastIndexOf(']');
if (lastBracket > 0) {
cleanedText = cleanedText.substring(0, lastBracket + 1);
}
}
}
console.log('Extracted JSON-like text:', cleanedText);
const parseJsObject = function(str) {
try {
// Safely evaluate the string as a JavaScript expression
return (new Function('return ' + str))();
} catch (e) {
console.error('Failed to parse:', e);
throw new Error('Invalid format in translation response');
}
};
// Parse the translation data
const translations = parseJsObject(cleanedText);
console.log('Parsed translations:', translations);
// Create modal elements
const modal = document.createElement('div');
modal.classList.add('modal');
const modalContent = document.createElement('div');
modalContent.classList.add('modal-content');
const title = document.createElement('h2');
title.textContent = 'Übersetzung der Gerichte';
title.style.color = '#a81411';
title.style.marginTop = '0';
modalContent.appendChild(title);
// Create form for editing translations
const form = document.createElement('form');
form.classList.add('translation-form');
// Add input fields for each translation
translations.forEach((item, index) => {
const dishContainer = document.createElement('div');
dishContainer.classList.add('dish-container');
// Deutsche Bezeichnung für das aktuelle Gericht
const originalDish = originalDishes[index] || { main: '', side: '' };
// Determine if this is a soup (soups have no side dish in original)
const isSoup = originalDish.side === '' && originalDish.main.toLowerCase().includes('suppe');
// Gericht-Header mit deutschem Original
const dishHeader = document.createElement('div');
dishHeader.style.fontWeight = 'bold';
dishHeader.style.marginBottom = '10px';
dishHeader.style.borderBottom = '1px solid #ccc';
dishHeader.style.paddingBottom = '5px';
dishHeader.style.color = '#a81411';
dishHeader.textContent = `${originalDish.main} ${originalDish.side}`;
const mainCourseInput = document.createElement('input');
mainCourseInput.type = 'text';
mainCourseInput.value = item.main_course;
mainCourseInput.style.padding = '8px';
mainCourseInput.style.marginBottom = '10px';
mainCourseInput.style.width = '100%';
mainCourseInput.style.boxSizing = 'border-box';
mainCourseInput.placeholder = isSoup ? 'Suppe' : 'Hauptgericht';
dishContainer.appendChild(dishHeader);
dishContainer.appendChild(mainCourseInput);
// Only add side dish input for regular dishes, not for soups
if (!isSoup) {
const sideDishInput = document.createElement('input');
sideDishInput.type = 'text';
sideDishInput.value = item.side_dish;
sideDishInput.style.padding = '8px';
sideDishInput.style.width = '100%';
sideDishInput.style.boxSizing = 'border-box';
sideDishInput.placeholder = 'Beilage';
dishContainer.appendChild(sideDishInput);
} else {
// Add a hidden input for soups to maintain the pair structure when collecting values
const hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.value = '';
dishContainer.appendChild(hiddenInput);
}
form.appendChild(dishContainer);
});
// Rest of the function remains unchanged
modalContent.appendChild(form);
// Add buttons
const buttonContainer = document.createElement('div');
buttonContainer.style.display = 'flex';
buttonContainer.style.justifyContent = 'first';
buttonContainer.style.marginTop = '20px';
buttonContainer.style.alignItems = 'center';
buttonContainer.style.gap = '10px';
const generateBtn = document.createElement('button');
generateBtn.textContent = 'PDF generieren';
generateBtn.style.padding = '8px 16px';
generateBtn.style.backgroundColor = '#1e88e5';
generateBtn.style.color = 'white';
generateBtn.style.border = 'none';
generateBtn.style.borderRadius = '4px';
generateBtn.style.cursor = 'pointer';
generateBtn.onclick = () => {
// Collect the current values from the text fields
const updatedTranslations = [];
const inputs = form.querySelectorAll('input:not([type="hidden"])');
const hiddenInputs = form.querySelectorAll('input[type="hidden"]');
let hiddenIndex = 0;
for (let i = 0; i < inputs.length; i++) {
const mainCourse = inputs[i].value;
let sideDish = '';
// If this is a soup (has hidden input), use empty side dish
if (hiddenInputs[hiddenIndex] &&
hiddenInputs[hiddenIndex].parentNode === inputs[i].parentNode) {
sideDish = '';
hiddenIndex++;
i++; // Skip the next input which would be the hidden one
} else {
// Otherwise get the next input as side dish
i++;
if (i < inputs.length) {
sideDish = inputs[i].value;
}
}
updatedTranslations.push({
main_course: mainCourse,
side_dish: sideDish
});
}
// Pass the updated translations to the generatePDF function
generatePDF('day', updatedTranslations);
};
const closeBtn = document.createElement('button');
closeBtn.textContent = 'Schließen';
closeBtn.style.padding = '8px 16px';
closeBtn.style.backgroundColor = '#a81411';
closeBtn.style.color = 'white';
closeBtn.style.border = 'none';
closeBtn.style.borderRadius = '4px';
closeBtn.style.cursor = 'pointer';
closeBtn.onclick = () => document.body.removeChild(modal);
const saveBtn = document.createElement('button');
saveBtn.textContent = 'Übersetzungen speichern';
saveBtn.style.padding = '8px 16px';
saveBtn.style.backgroundColor = '#1e88e5';
saveBtn.style.color = 'white';
saveBtn.style.border = 'none';
saveBtn.style.borderRadius = '4px';
saveBtn.style.cursor = 'pointer';
saveBtn.onclick = async () => {
// Get all translated texts from form fields using the same logic as the PDF button
const updatedTranslations = [];
const inputs = form.querySelectorAll('input:not([type="hidden"])');
const hiddenInputs = form.querySelectorAll('input[type="hidden"]');
let hiddenIndex = 0;
for (let i = 0; i < inputs.length; i++) {
const mainCourse = inputs[i].value;
let sideDish = '';
// If this is a soup (has hidden input), use empty side dish
if (hiddenInputs[hiddenIndex] &&
hiddenInputs[hiddenIndex].parentNode === inputs[i].parentNode) {
sideDish = '';
hiddenIndex++;
i++; // Skip the next input which would be the hidden one
} else {
// Otherwise get the next input as side dish
i++;
if (i < inputs.length) {
sideDish = inputs[i].value;
}
}
updatedTranslations.push({
main_course: mainCourse,
side_dish: sideDish
});
}
// Save the translations to the database
const saveResult = await saveTranslationsToDatabase(updatedTranslations, originalDishes);
if (saveResult.success) {
alert('Übersetzungen wurden in der Datenbank gespeichert!');
} else {
alert('Fehler beim Speichern: ' + saveResult.message);
}
};
const disclaimer = document.createElement('p');
disclaimer.textContent = 'Hinweis: KI generierter Inhalt kann Fehler enthalten. Bitte überprüfen Sie die Übersetzungen sorgfältig.';
disclaimer.style.margin = '0'
disclaimer.style.fontWeight = 'bold';
buttonContainer.appendChild(generateBtn);
buttonContainer.appendChild(saveBtn);
buttonContainer.appendChild(closeBtn);
buttonContainer.appendChild(disclaimer);
modalContent.appendChild(buttonContainer);
modal.appendChild(modalContent);
document.body.appendChild(modal);
} catch (error) {
console.error('Error parsing translation JSON:', error);
alert('Fehler beim Verarbeiten der Übersetzung. Das Format ist ungültig.');
}
}
async function displayEnglishTranslations() {
try {
// Get current week to load data
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
// First, fetch the current week's German daily dishes data for reference
const germanResponse = await fetch(`/load-week-daily?week=${encodeURIComponent(week)}`);
const germanData = await germanResponse.json();
// Sort the data by day index to ensure correct order
germanData.sort((a, b) => a.day_index - b.day_index);
// Create array of original dishes for reference
const originalDishes = [];
// If German data exists, extract dish information
if (germanData && germanData.length > 0) {
germanData.forEach(entry => {
// Add daily dish
if (entry.daily_main) {
originalDishes.push({
main: entry.daily_main,
side: entry.daily_side || ''
});
}
// Add daily soup
if (entry.daily_soup) {
originalDishes.push({
main: entry.daily_soup,
side: ''
});
}
});
} else {
// If no German data, create at least one empty placeholder
originalDishes.push({
main: 'Keine deutschen Einträge gefunden',
side: ''
});
}
// Now fetch English translations
const englishResponse = await fetch(`/load-week-daily-en?week=${encodeURIComponent(week)}`);
let englishData = [];
try {
englishData = await englishResponse.json();
} catch (e) {
console.log('No English translations found or error parsing response');
}
// Create formatted data for display
const formattedTranslations = [];
// Always create translation objects for each German dish, even if no English data exists
if (germanData && germanData.length > 0) {
germanData.forEach(entry => {
// Find matching English entry by date (may be undefined)
const englishEntry = englishData.find(en => en.date === entry.date);
// Add daily dish translation (empty strings if no match)
if (entry.daily_main) {
formattedTranslations.push({
main_course: englishEntry ? englishEntry.daily_main || '' : '',
side_dish: englishEntry ? englishEntry.daily_side || '' : ''
});
}
// Add soup translation (empty strings if no match)
if (entry.daily_soup) {
formattedTranslations.push({
main_course: englishEntry ? englishEntry.daily_soup || '' : '',
side_dish: ''
});
}
});
} else {
// If no German data, add empty translation entry
formattedTranslations.push({
main_course: '',
side_dish: ''
});
}
// Format as JSON string for the existing displayTranslation function
const translationText = JSON.stringify(formattedTranslations);
// Display the translations
displayTranslation(translationText, originalDishes);
} catch (error) {
console.error('Error loading English translations:', error);
// Show empty form even when there's an error
const emptyDish = [{ main: 'Fehler beim Laden der Daten', side: '' }];
const emptyTranslations = JSON.stringify([{ main_course: '', side_dish: '' }]);
displayTranslation(emptyTranslations, emptyDish);
}
}
function generatePDF(type) { function generatePDF(type) {
saveWeek(); saveWeek();
const currentDate = new Date(currentWeek); const currentDate = new Date(currentWeek);
+273 -43
View File
@@ -272,52 +272,52 @@ async function sendAiTranslateRequest() {
// Sort the data by day index to ensure correct order // Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index); data.sort((a, b) => a.day_index - b.day_index);
// Format the data as described in the prompt // Construct menu items array
let promptText = ''; const menuItems = [];
// Store original dishes for reference
const originalDishes = [];
data.forEach(entry => { data.forEach(entry => {
// Add meat dish // Add meat dish
if (entry.meat_main) { if (entry.meat_main) {
promptText += `${entry.meat_main}\n`; menuItems.push({
originalDishes.push({
main: entry.meat_main, main: entry.meat_main,
side: entry.meat_side || '' side: entry.meat_side || ''
}); });
if (entry.meat_side) {
promptText += `${entry.meat_side}\n\n`;
} else {
promptText += '\n';
}
} }
// Add vegetarian dish // Add vegetarian dish
if (entry.veggi_main) { if (entry.veggi_main) {
promptText += `${entry.veggi_main}\n`; menuItems.push({
originalDishes.push({
main: entry.veggi_main, main: entry.veggi_main,
side: entry.veggi_side || '' side: entry.veggi_side || ''
}); });
if (entry.veggi_side) {
promptText += `${entry.veggi_side}\n\n`;
} else {
promptText += '\n';
}
} }
}); });
// Send to the AI service // Create a structured request with menu type
const requestData = {
menuItems: menuItems,
menuType: 'weekly' // Specify that this is a weekly menu
};
console.log('Sending request data:', requestData);
// Send to the AI service with the structured data
const aiResponse = await fetch('/ai-request', { const aiResponse = await fetch('/ai-request', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ prompt: promptText }) body: JSON.stringify(requestData)
}); });
// Check for non-JSON responses
const contentType = aiResponse.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
const errorText = await aiResponse.text();
console.error('Non-JSON response received:', errorText);
throw new Error('Server returned non-JSON response. You might need to log in again or check server logs.');
}
const aiData = await aiResponse.json(); const aiData = await aiResponse.json();
if (aiData.error) { if (aiData.error) {
console.error('AI request failed:', aiData.error); console.error('AI request failed:', aiData.error);
@@ -325,18 +325,153 @@ async function sendAiTranslateRequest() {
return; return;
} }
// Show the results to the user // Process the result as before
console.log('AI response:', aiData.result); let cleanedText = aiData.result
console.log('Original dishes:', originalDishes); .trim()
.replace(/\n/g, '');
// Extract just the array part if needed
if (cleanedText.indexOf('[') >= 0) {
cleanedText = cleanedText.substring(cleanedText.indexOf('['));
if (!cleanedText.endsWith(']')) {
const lastBracket = cleanedText.lastIndexOf(']');
if (lastBracket > 0) {
cleanedText = cleanedText.substring(0, lastBracket + 1);
}
}
}
const parseJsObject = function(str) {
try {
return (new Function('return ' + str))();
} catch (e) {
console.error('Failed to parse:', e);
throw new Error('Invalid format in translation response');
}
};
// Parse the translation data
const translations = parseJsObject(cleanedText);
// Save translations to database using the new function
const saveResult = await saveTranslationsToDatabase(translations);
if (saveResult.success) {
alert(saveResult.message);
} else {
alert('Fehler beim Speichern: ' + saveResult.message);
}
// Create a modal to display the translation with original dishes
displayTranslation(aiData.result, originalDishes);
} catch (error) { } catch (error) {
console.error('Error sending AI request:', error); console.error('Error sending AI request:', error);
alert('Fehler bei der KI-Anfrage: ' + error.message); alert('Fehler bei der KI-Anfrage: ' + error.message);
} }
} }
async function saveTranslationsToDatabase(translations, originalDishes = null) {
try {
// Get current week
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
let entries = [];
if (originalDishes === null) {
// Case 1: Called from sendAiTranslateRequest with full data
// Fetch the current week's menu data
const response = await fetch(`/load-week?week=${encodeURIComponent(week)}`);
const data = await response.json();
// Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index);
let translationIndex = 0;
// Map translations to database entries
data.forEach(entry => {
const englishEntry = {
date: entry.date,
meatMain: '',
meatSide: '',
veggiMain: '',
veggiSide: ''
};
// Add meat dish translation
if (entry.meat_main && translations[translationIndex]) {
englishEntry.meatMain = translations[translationIndex].main_course;
englishEntry.meatSide = translations[translationIndex].side_dish;
translationIndex++;
}
// Add vegetarian dish translation
if (entry.veggi_main && translations[translationIndex]) {
englishEntry.veggiMain = translations[translationIndex].main_course;
englishEntry.veggiSide = translations[translationIndex].side_dish;
translationIndex++;
}
entries.push(englishEntry);
});
} else {
// Case 2: Called from displayTranslation with form values
// Fetch the original data to get the dates
const response = await fetch(`/load-week?week=${encodeURIComponent(week)}`);
const data = await response.json();
// Sort the data by day index to ensure correct order
data.sort((a, b) => a.day_index - b.day_index);
// Create entries with dates from original data
let translationIndex = 0;
data.forEach(entry => {
const englishEntry = {
date: entry.date,
meatMain: '',
meatSide: '',
veggiMain: '',
veggiSide: ''
};
// Add meat dish translation if original has meat dish
if (entry.meat_main && translations[translationIndex]) {
englishEntry.meatMain = translations[translationIndex].main_course;
englishEntry.meatSide = translations[translationIndex].side_dish;
translationIndex++;
}
// Add vegetarian dish translation if original has veggie dish
if (entry.veggi_main && translations[translationIndex]) {
englishEntry.veggiMain = translations[translationIndex].main_course;
englishEntry.veggiSide = translations[translationIndex].side_dish;
translationIndex++;
}
entries.push(englishEntry);
});
}
// Save translations to database
const saveResponse = await fetch('/save-week-en', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ week, entries })
});
const saveResult = await saveResponse.json();
return { success: true, message: 'Englische Übersetzungen wurden gespeichert.' };
} catch (error) {
console.error('Error saving translations to database:', error);
return { success: false, message: 'Fehler beim Speichern der Übersetzungen: ' + error.message };
}
}
function sendTestTranslateRequest() { function sendTestTranslateRequest() {
const testResponse = `[{'main_course':'Turkey schnitzel with pepper sauce','side_dish':'served with spaghetti'},{'main_course':'Lentil curry with coconut milk','side_dish':'served with rice'},{'main_course':'White cabbage stew with potatoes and ground beef','side_dish':'served with a side salad and homemade bread'},{'main_course':'Sweet potato gnocchi with cheese sauce and arugula','side_dish':'served with a side salad'},{'main_course':'Ramsons bratwurst','side_dish':'accompanied by steakhouse fries'},{'main_course':'"Poached eggs" in mustard sauce','side_dish':'served with boiled potatoes and a side salad'},{'main_course':'Chicken breast fillet in herb sauce','side_dish':'with fried potatoes and a side salad'},{'main_course':'Vegetable fritter with dip','side_dish':'served with couscous'},{'main_course':'Halibut fillet in lemon herb sauce','side_dish':'served with boiled potatoes and a side salad'},{'main_course':'Vegetable rösti with dip','side_dish':'served with potato salad'}]`; const testResponse = `[{'main_course':'Turkey schnitzel with pepper sauce','side_dish':'served with spaghetti'},{'main_course':'Lentil curry with coconut milk','side_dish':'served with rice'},{'main_course':'White cabbage stew with potatoes and ground beef','side_dish':'served with a side salad and homemade bread'},{'main_course':'Sweet potato gnocchi with cheese sauce and arugula','side_dish':'served with a side salad'},{'main_course':'Ramsons bratwurst','side_dish':'accompanied by steakhouse fries'},{'main_course':'"Poached eggs" in mustard sauce','side_dish':'served with boiled potatoes and a side salad'},{'main_course':'Chicken breast fillet in herb sauce','side_dish':'with fried potatoes and a side salad'},{'main_course':'Vegetable fritter with dip','side_dish':'served with couscous'},{'main_course':'Halibut fillet in lemon herb sauce','side_dish':'served with boiled potatoes and a side salad'},{'main_course':'Vegetable rösti with dip','side_dish':'served with potato salad'}]`;
@@ -435,6 +570,7 @@ function displayTranslation(translationText, originalDishes = []) {
mainCourseInput.style.marginBottom = '10px'; mainCourseInput.style.marginBottom = '10px';
mainCourseInput.style.width = '100%'; mainCourseInput.style.width = '100%';
mainCourseInput.style.boxSizing = 'border-box'; mainCourseInput.style.boxSizing = 'border-box';
mainCourseInput.placeholder = 'Hauptgericht';
const sideDishInput = document.createElement('input'); const sideDishInput = document.createElement('input');
sideDishInput.type = 'text'; sideDishInput.type = 'text';
@@ -442,6 +578,7 @@ function displayTranslation(translationText, originalDishes = []) {
sideDishInput.style.padding = '8px'; sideDishInput.style.padding = '8px';
sideDishInput.style.width = '100%'; sideDishInput.style.width = '100%';
sideDishInput.style.boxSizing = 'border-box'; sideDishInput.style.boxSizing = 'border-box';
sideDishInput.placeholder = 'Beilage';
dishContainer.appendChild(dishHeader); dishContainer.appendChild(dishHeader);
dishContainer.appendChild(mainCourseInput); dishContainer.appendChild(mainCourseInput);
@@ -496,26 +633,36 @@ function displayTranslation(translationText, originalDishes = []) {
closeBtn.style.cursor = 'pointer'; closeBtn.style.cursor = 'pointer';
closeBtn.onclick = () => document.body.removeChild(modal); closeBtn.onclick = () => document.body.removeChild(modal);
const copyBtn = document.createElement('button'); const saveBtn = document.createElement('button');
copyBtn.textContent = 'Übersetzungen kopieren'; saveBtn.textContent = 'Übersetzungen speichern';
copyBtn.style.padding = '8px 16px'; saveBtn.style.padding = '8px 16px';
copyBtn.style.backgroundColor = '#1e88e5'; saveBtn.style.backgroundColor = '#1e88e5';
copyBtn.style.color = 'white'; saveBtn.style.color = 'white';
copyBtn.style.border = 'none'; saveBtn.style.border = 'none';
copyBtn.style.borderRadius = '4px'; saveBtn.style.borderRadius = '4px';
copyBtn.style.cursor = 'pointer'; saveBtn.style.cursor = 'pointer';
copyBtn.onclick = () => { saveBtn.onclick = async () => {
// Get all translated texts // Get all translated texts from form fields
const updatedTranslations = [];
const inputs = form.querySelectorAll('input'); const inputs = form.querySelectorAll('input');
let copyText = '';
for (let i = 0; i < inputs.length; i += 2) { for (let i = 0; i < inputs.length; i += 2) {
copyText += `${inputs[i].value}\n${inputs[i + 1].value}\n\n`; const mainCourse = inputs[i].value;
const sideDish = inputs[i + 1].value;
updatedTranslations.push({
main_course: mainCourse,
side_dish: sideDish
});
} }
navigator.clipboard.writeText(copyText) // Save the translations to the database
.then(() => alert('Übersetzungen wurden in die Zwischenablage kopiert!')) const saveResult = await saveTranslationsToDatabase(updatedTranslations, originalDishes);
.catch(err => console.error('Fehler beim Kopieren:', err));
if (saveResult.success) {
alert('Übersetzungen wurden in der Datenbank gespeichert!');
} else {
alert('Fehler beim Speichern: ' + saveResult.message);
}
}; };
const disclaimer = document.createElement('p'); const disclaimer = document.createElement('p');
@@ -524,7 +671,7 @@ function displayTranslation(translationText, originalDishes = []) {
disclaimer.style.fontWeight = 'bold'; disclaimer.style.fontWeight = 'bold';
buttonContainer.appendChild(generateBtn); buttonContainer.appendChild(generateBtn);
buttonContainer.appendChild(copyBtn); buttonContainer.appendChild(saveBtn);
buttonContainer.appendChild(closeBtn); buttonContainer.appendChild(closeBtn);
buttonContainer.appendChild(disclaimer); buttonContainer.appendChild(disclaimer);
modalContent.appendChild(buttonContainer); modalContent.appendChild(buttonContainer);
@@ -538,6 +685,89 @@ function displayTranslation(translationText, originalDishes = []) {
} }
} }
async function displayEnglishTranslations() {
try {
// Get current week to load data
const weekNumber = getWeekNumber(currentWeek);
const year = currentWeek.getFullYear();
const week = `KW${weekNumber} ${year}`;
// First, fetch the current week's German menu data for reference
const germanResponse = await fetch(`/load-week?week=${encodeURIComponent(week)}`);
const germanData = await germanResponse.json();
// Sort the data by day index to ensure correct order
germanData.sort((a, b) => a.day_index - b.day_index);
console.log("German data loaded:", germanData.length, "entries");
// Create array of original dishes for reference
const originalDishes = [];
germanData.forEach(entry => {
// Add meat dish
if (entry.meat_main) {
originalDishes.push({
main: entry.meat_main,
side: entry.meat_side || ''
});
}
// Add vegetarian dish
if (entry.veggi_main) {
originalDishes.push({
main: entry.veggi_main,
side: entry.veggi_side || ''
});
}
});
console.log("Original dishes:", originalDishes.length);
// Now fetch English translations
const englishResponse = await fetch(`/load-week-en?week=${encodeURIComponent(week)}`);
const englishData = await englishResponse.json();
console.log("English data loaded:", englishData.length, "entries");
// Create formatted data for display - IMPORTANT: clear the array first
const formattedTranslations = [];
// Create translation objects for each German dish
germanData.forEach(entry => {
// Find matching English entry by date
const englishEntry = englishData.find(en => en.date === entry.date);
// Add meat dish translation (empty strings if no match)
if (entry.meat_main) {
formattedTranslations.push({
main_course: englishEntry ? englishEntry.meat_main || '' : '',
side_dish: englishEntry ? englishEntry.meat_side || '' : ''
});
}
// Add vegetarian dish translation (empty strings if no match)
if (entry.veggi_main) {
formattedTranslations.push({
main_course: englishEntry ? englishEntry.veggi_main || '' : '',
side_dish: englishEntry ? englishEntry.veggi_side || '' : ''
});
}
});
console.log("Formatted translations:", formattedTranslations.length);
// Format as JSON string for the existing displayTranslation function
const translationText = JSON.stringify(formattedTranslations);
// Pass the data to displayTranslation with the original dishes for reference
displayTranslation(translationText, originalDishes);
} catch (error) {
console.error('Error loading English translations:', error);
alert('Fehler beim Laden der englischen Übersetzungen: ' + error.message);
}
}
// Initialize the display when page loads // Initialize the display when page loads
updateWeekDisplay(); updateWeekDisplay();
updateDayDisplay(); updateDayDisplay();