mirror of
https://github.com/Matewoo/pdf-writer.git
synced 2026-11-18 18:42:50 +01:00
add ai translate to english
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
"express": "^4.21.2",
|
||||
"express-session": "^1.18.1",
|
||||
"ldap-authentication": "^3.3.4",
|
||||
"openai": "^4.86.1",
|
||||
"ws": "^8.18.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,12 +8,17 @@ const fs = require('fs');
|
||||
const ldap = require('ldap-authentication');
|
||||
const session = require('express-session');
|
||||
const { exec } = require('child_process');
|
||||
const OpenAI = require('openai');
|
||||
require('dotenv').config();
|
||||
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const wss = new WebSocket.Server({ server });
|
||||
|
||||
const openai = new OpenAI({
|
||||
apiKey: process.env.OPENAI_API_KEY
|
||||
});
|
||||
|
||||
// Session-Konfiguration
|
||||
app.use(session({
|
||||
secret: process.env.SESSION_SECRET || 'telc-speiseplan-secret',
|
||||
@@ -326,6 +331,27 @@ app.post('/generate-pdf', requireLogin, (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/ai-request', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { prompt } = req.body;
|
||||
|
||||
const completion = await openai.chat.completions.create({
|
||||
model: "gpt-4o-mini",
|
||||
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, aber dennoch in ZWEI getrennten Zeilen stehen. Gib das Ergebnis in folgendem JSON-Format zurück: [{'main_course': '<Hauptgericht in natürlicher Formulierung>', 'side_dish': '<Beilage in natürlicher Formulierung>'}]." },
|
||||
{ role: "user", content: prompt }
|
||||
]
|
||||
});
|
||||
|
||||
const messageContent = completion.choices[0].message.content;
|
||||
|
||||
res.json({ result: messageContent });
|
||||
} catch (error) {
|
||||
console.error('OpenAI API error:', error);
|
||||
res.status(500).json({ error: 'Error processing AI request' });
|
||||
}
|
||||
});
|
||||
|
||||
// Ungeschützte API-Routen für die digitalSignage
|
||||
app.get('/load-week', (req, res) => {
|
||||
const { week } = req.query;
|
||||
|
||||
@@ -55,6 +55,7 @@
|
||||
<div class="bottom-controls">
|
||||
<button onclick="saveWeek()">Woche speichern</button>
|
||||
<button onclick="generatePDF('week')">PDF generieren</button>
|
||||
<button onclick="sendAiTranslateRequest()" class="admin-only">KI Übersetzung</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -253,6 +253,202 @@ function generatePDF(type) {
|
||||
});
|
||||
}
|
||||
|
||||
async function sendAiTranslateRequest() {
|
||||
try {
|
||||
// Get current week to load data
|
||||
const weekNumber = getWeekNumber(currentWeek);
|
||||
const year = currentWeek.getFullYear();
|
||||
const week = `KW${weekNumber} ${year}`;
|
||||
|
||||
// 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);
|
||||
|
||||
// Format the data as described in the prompt
|
||||
let promptText = '';
|
||||
|
||||
data.forEach(entry => {
|
||||
// Add meat dish
|
||||
if (entry.meat_main) {
|
||||
promptText += `${entry.meat_main}\n`;
|
||||
if (entry.meat_side) {
|
||||
promptText += `${entry.meat_side}\n\n`;
|
||||
} else {
|
||||
promptText += '\n';
|
||||
}
|
||||
}
|
||||
|
||||
// Add vegetarian dish
|
||||
if (entry.veggi_main) {
|
||||
promptText += `${entry.veggi_main}\n`;
|
||||
if (entry.veggi_side) {
|
||||
promptText += `${entry.veggi_side}\n\n`;
|
||||
} else {
|
||||
promptText += '\n';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Send to the AI service
|
||||
const aiResponse = await fetch('/ai-request', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ prompt: promptText })
|
||||
});
|
||||
|
||||
const aiData = await aiResponse.json();
|
||||
if (aiData.error) {
|
||||
console.error('AI request failed:', aiData.error);
|
||||
alert('AI-Übersetzung fehlgeschlagen: ' + aiData.error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show the results to the user
|
||||
console.log('AI response:', aiData.result);
|
||||
|
||||
// Create a modal to display the translation
|
||||
displayTranslation(aiData.result);
|
||||
} catch (error) {
|
||||
console.error('Error sending AI request:', error);
|
||||
alert('Fehler bei der KI-Anfrage: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function displayTranslation(translationText) {
|
||||
try {
|
||||
// Clean up the JSON string by removing markdown code block formatting
|
||||
let cleanedText = translationText;
|
||||
|
||||
// Remove ```json at the beginning
|
||||
cleanedText = cleanedText.replace('```json', '');
|
||||
|
||||
// Remove ``` at the end
|
||||
cleanedText = cleanedText.replace('```', '');
|
||||
|
||||
// Parse the cleaned JSON response
|
||||
const translations = JSON.parse(cleanedText);
|
||||
|
||||
// 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');
|
||||
|
||||
|
||||
const dishNumber = document.createElement('div');
|
||||
dishNumber.textContent = `Gericht ${index + 1}`;
|
||||
dishNumber.style.fontWeight = 'bold';
|
||||
dishNumber.style.marginBottom = '5px';
|
||||
|
||||
const mainCourseLabel = document.createElement('label');
|
||||
mainCourseLabel.textContent = 'Hauptgericht:';
|
||||
mainCourseLabel.style.marginBottom = '3px';
|
||||
mainCourseLabel.style.fontWeight = 'bold';
|
||||
|
||||
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';
|
||||
|
||||
const sideDishLabel = document.createElement('label');
|
||||
sideDishLabel.textContent = 'Beilage:';
|
||||
sideDishLabel.style.marginBottom = '3px';
|
||||
sideDishLabel.style.fontWeight = 'bold';
|
||||
|
||||
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';
|
||||
|
||||
dishContainer.appendChild(dishNumber);
|
||||
dishContainer.appendChild(mainCourseLabel);
|
||||
dishContainer.appendChild(mainCourseInput);
|
||||
dishContainer.appendChild(sideDishLabel);
|
||||
dishContainer.appendChild(sideDishInput);
|
||||
|
||||
form.appendChild(dishContainer);
|
||||
});
|
||||
|
||||
modalContent.appendChild(form);
|
||||
|
||||
// Add buttons
|
||||
const buttonContainer = document.createElement('div');
|
||||
buttonContainer.style.display = 'flex';
|
||||
buttonContainer.style.justifyContent = 'space-between';
|
||||
buttonContainer.style.marginTop = '20px';
|
||||
|
||||
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 copyBtn = document.createElement('button');
|
||||
copyBtn.textContent = 'Übersetzungen kopieren';
|
||||
copyBtn.style.padding = '8px 16px';
|
||||
copyBtn.style.backgroundColor = '#1e88e5';
|
||||
copyBtn.style.color = 'white';
|
||||
copyBtn.style.border = 'none';
|
||||
copyBtn.style.borderRadius = '4px';
|
||||
copyBtn.style.cursor = 'pointer';
|
||||
copyBtn.onclick = () => {
|
||||
// Get all translated texts
|
||||
const inputs = form.querySelectorAll('input');
|
||||
let copyText = '';
|
||||
|
||||
for (let i = 0; i < inputs.length; i += 2) {
|
||||
copyText += `${inputs[i].value}\n${inputs[i + 1].value}\n\n`;
|
||||
}
|
||||
|
||||
navigator.clipboard.writeText(copyText)
|
||||
.then(() => alert('Übersetzungen wurden in die Zwischenablage kopiert!'))
|
||||
.catch(err => console.error('Fehler beim Kopieren:', err));
|
||||
};
|
||||
|
||||
buttonContainer.appendChild(copyBtn);
|
||||
buttonContainer.appendChild(closeBtn);
|
||||
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.');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the display when page loads
|
||||
updateWeekDisplay();
|
||||
|
||||
@@ -197,6 +197,9 @@ button {
|
||||
.bottom-controls {
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.day-form {
|
||||
@@ -207,7 +210,47 @@ button {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Für Admin-Only Elemente */
|
||||
|
||||
.admin-only {
|
||||
display: none; /* Standardmäßig versteckt, wird via JS eingeblendet */
|
||||
display: none;
|
||||
}
|
||||
|
||||
.modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,0.7);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: #fff;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
max-width: 75%;
|
||||
max-height: 75%;
|
||||
overflow: auto;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.translation-form {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.dish-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid #ddd;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
background-color: #f9f9f9;
|
||||
width: 40%;
|
||||
}
|
||||
Reference in New Issue
Block a user