Imamverdi Behbudlu
feat(config): set default models to gemini-3.5-flash, gpt-4o, claude-opus-4.8 and add model customization guide
3e6fbaf
Raw History Blame Contribute Delete
20.5 kB
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import dns from 'dns';
dns.setDefaultResultOrder('ipv4first');
// Load environment variables from .env or .env.local
dotenv.config({ path: '.env.local' });
dotenv.config();
const app = express();
const PORT = process.env.PORT || 7860;
const FORMBRICKS_BASE_URL = process.env.FORMBRICKS_URL || 'https://app.formbricks.com';
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// -------------------------------------------------------------
// Live API Service Calls (Node Native Fetch)
// -------------------------------------------------------------
async function translateDeepL(texts, targetLang, apiKey) {
if (!apiKey) throw new Error("DeepL API açarı daxil edilməyib.");
// Normalize DeepL target language codes (BR -> PT-BR for Brazilian Portuguese, not Breton)
let deeplTarget = (targetLang || '').toUpperCase();
if (deeplTarget === 'BR') deeplTarget = 'PT-BR';
if (deeplTarget === 'PT') deeplTarget = 'PT-PT';
const isFreeKey = apiKey.endsWith(':fx');
const url = isFreeKey
? 'https://api-free.deepl.com/v2/translate'
: 'https://api.deepl.com/v2/translate';
const response = await fetchWithRetry(url, {
method: 'POST',
headers: {
'Authorization': `DeepL-Auth-Key ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: texts,
target_lang: deeplTarget,
tag_handling: 'html'
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`DeepL API Xətası: ${response.status} - ${errorText}`);
}
const data = await response.json();
return data.translations.map(t => t.text);
}
// Helper for retrying requests on Rate Limits (429), Overloads (529), or Service Unavailable (503)
async function fetchWithRetry(url, options, maxRetries = 4, initialDelay = 1500) {
let delay = initialDelay;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if ([429, 529, 503].includes(response.status) && attempt < maxRetries) {
console.warn(`API overloaded/rate-limited (${response.status}). Cəhd ${attempt}/${maxRetries}. ${Math.round(delay/1000)}s sonra təkrar cəhd edilir...`);
await new Promise(res => setTimeout(res, delay));
delay = Math.min(delay * 1.5, 3500);
continue;
}
return response;
} catch (err) {
if (attempt < maxRetries) {
await new Promise(res => setTimeout(res, delay));
delay = Math.min(delay * 1.5, 3500);
continue;
}
throw err;
}
}
}
async function reviewGemini(original, translation, targetLangName, apiKey, fullContext, contentType = "General JSON Content") {
if (!apiKey) throw new Error("Gemini API açarı daxil edilməyib.");
const apiModel = process.env.VITE_GEMINI_MODEL || 'gemini-3.5-flash';
const url = `https://generativelanguage.googleapis.com/v1beta/models/${apiModel}:generateContent?key=${apiKey}`;
const prompt = `You are a native speaker of ${targetLangName}. Review this ${contentType} segment translation.
=== FULL CONTENT CONTEXT (For your understanding) ===
${fullContext || "N/A"}
=== END FULL CONTEXT ===
TARGET SEGMENT TO REVIEW:
Original English: "${original}"
DeepL Translation: "${translation}"
Review the translation for natural flow, domain accuracy (${contentType}), correct variables (like {{$username}}, {{name}}, {count}), and native style.
If the translation is already perfect and natural, reply with exactly: "APPROVED".
Otherwise, reply with your improved translation and a 1-sentence explanation of the correction. Keep HTML tags intact.`;
const response = await fetchWithRetry(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }]
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Gemini API Xətası: ${response.status} - ${errorText}`);
}
const data = await response.json();
return data.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || "Rəy əldə edilə bilmədi.";
}
async function reviewOpenAI(original, translation, targetLangName, apiKey, fullContext, contentType = "General JSON Content") {
if (!apiKey) throw new Error("OpenAI API açarı daxil edilməyib.");
const response = await fetchWithRetry('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: process.env.VITE_OPENAI_MODEL || 'gpt-4o',
messages: [
{ role: 'system', content: `You are an expert native reviewer and localizer for ${targetLangName} specializing in ${contentType}.` },
{ role: 'user', content: `Review this translated segment:
=== FULL CONTENT CONTEXT (For reference) ===
${fullContext || "N/A"}
=== END CONTEXT ===
TARGET SEGMENT:
Original: "${original}"
DeepL Translation: "${translation}"
Verify if it sounds natural, local, and maintains correct HTML formatting and template variables.
If it is perfect, output "APPROVED".
Otherwise, provide your improved translation and 1 brief suggestion.` }
],
temperature: 0.3
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`OpenAI API Xətası: ${response.status} - ${errorText}`);
}
const data = await response.json();
return data.choices?.[0]?.message?.content?.trim() || "Rəy əldə edilə bilmədi.";
}
function safeParseJson(rawText) {
if (!rawText) return null;
let cleaned = rawText.replace(/^```json\s*/i, '').replace(/```$/g, '').trim();
// Try direct parse first
try {
return JSON.parse(cleaned);
} catch (e0) {}
const jsonStart = cleaned.indexOf('{');
if (jsonStart === -1) return null;
let jsonEnd = cleaned.lastIndexOf('}');
if (jsonEnd === -1 || jsonEnd <= jsonStart) {
// If closing } is missing (truncated output), auto-close quotes/curly braces
cleaned = cleaned + '"}';
jsonEnd = cleaned.lastIndexOf('}');
}
let jsonStr = cleaned.substring(jsonStart, jsonEnd + 1);
// 1. Try standard JSON parse
try {
return JSON.parse(jsonStr);
} catch (e1) {
// 2. Try fixing raw control characters/newlines inside string literals
try {
const fixedStr = jsonStr.replace(/[\r\n]+/g, " ");
return JSON.parse(fixedStr);
} catch (e2) {
// 3. Robust Regex Extraction Fallback for fields (even if output was truncated!)
const finalTransMatch = jsonStr.match(/"final_translation"\s*:\s*"([\s\S]*?)"\s*,\s*"agent_notes"/i)
|| jsonStr.match(/"final_translation"\s*:\s*"([\s\S]*?)"\s*[\},]/i)
|| jsonStr.match(/"final_translation"\s*:\s*"([\s\S]*)/i);
const agentNotesMatch = jsonStr.match(/"agent_notes"\s*:\s*"([\s\S]*?)"\s*[\},]/i);
const conflictMatch = jsonStr.match(/"discrepancy_percentage"\s*:\s*(\d+)/i);
if (finalTransMatch && finalTransMatch[1]) {
let cleanTrans = finalTransMatch[1]
.replace(/\\"/g, '"')
.replace(/"\s*,\s*"agent_notes"[\s\S]*/i, '')
.replace(/"\s*\}$/, '')
.trim();
return {
final_translation: cleanTrans,
agent_notes: agentNotesMatch ? agentNotesMatch[1] : "Claude tərəfindən sintez edildi.",
discrepancy_percentage: conflictMatch ? parseInt(conflictMatch[1]) : 0
};
}
}
}
return null;
}
async function synthesizeClaude(original, deeplText, geminiReview, openaiReview, targetLangName, apiKey, fullContext, contentType = "General JSON Content", maxRetries = 4) {
if (!apiKey) throw new Error("Claude API açarı daxil edilməyib.");
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetchWithRetry('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
body: JSON.stringify({
model: process.env.VITE_CLAUDE_MODEL || 'claude-opus-4.8',
max_tokens: 4096,
system: `You are an expert copywriter and synthesis engine. Your job is to output a final native translation for a ${contentType} segment in ${targetLangName} by evaluating raw translation and reviewer feedback.
You MUST output ONLY a valid raw JSON object. Do NOT wrap in markdown codeblocks (no \`\`\`json), do NOT write any introductory or closing text.
Required JSON Structure:
{
"final_translation": "your final native translation here",
"agent_notes": "a brief Azerbaijani explanation of why you made this choice or why reviews were useful",
"discrepancy_percentage": 0-100
}`,
messages: [
{ role: 'user', content: `Synthesize into valid JSON for target language: ${targetLangName}.
=== FULL CONTENT CONTEXT (For reference only) ===
${fullContext || "N/A"}
=== END CONTEXT ===
TARGET SEGMENT TO SYNTHESIZE:
Original English: "${original}"
DeepL Translation: "${deeplText}"
Gemini Feedback: "${geminiReview}"
OpenAI Feedback: "${openaiReview}"
Ensure all HTML tags, styles, and template variables (like {{$username}}, {{name}}, {count}) are 100% preserved. Respond ONLY with the raw JSON object.` }
]
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Claude API Xətası: ${response.status} - ${errorText}`);
}
const data = await response.json();
const rawText = data.content?.[0]?.text?.trim() || "";
// Safe robust JSON Parsing
const parsed = safeParseJson(rawText);
if (parsed && typeof parsed.final_translation === 'string') {
return {
final_translation: parsed.final_translation,
agent_notes: parsed.agent_notes || "Claude tərəfindən müvəffəqiyyətlə sintez edildi.",
discrepancy_percentage: typeof parsed.discrepancy_percentage === 'number' ? parsed.discrepancy_percentage : 0,
hasError: false
};
}
console.warn("Claude raw output parsing failed:", rawText);
throw new Error(`Claude cavabında etibarlı JSON obyekti tapılmadı.`);
} catch (err) {
console.warn(`Claude Sintez Cəhdi ${attempt}/${maxRetries} xətası: ${err.message}`);
lastError = err;
if (attempt < maxRetries) {
await new Promise(r => setTimeout(r, 1000 * attempt));
}
}
}
// If retries failed, return warning status so user can trigger manual retry
return {
final_translation: deeplText,
agent_notes: `⚠️ Claude Sintez Xətası (${lastError ? lastError.message : "JSON alına bilmədi"}). [Yenidən Sına] düyməsinə klikləyin.`,
discrepancy_percentage: 0,
hasError: true
};
}
// -------------------------------------------------------------
// POST Route for Segment Translation
// -------------------------------------------------------------
app.post('/api/translate-segment', async (req, res) => {
const { segment, targetLang, targetLangName, fullContext, contentType, apiKeys } = req.body;
const originalText = segment.original;
const resolvedKeys = {
deepl: apiKeys?.deepl || process.env.VITE_DEEPL_KEY || process.env.DEEPL_API_KEY,
gemini: apiKeys?.gemini || process.env.VITE_GEMINI_KEY || process.env.GEMINI_API_KEY,
openai: apiKeys?.openai || process.env.VITE_OPENAI_KEY || process.env.OPENAI_API_KEY,
claude: apiKeys?.claude || process.env.VITE_CLAUDE_KEY || process.env.CLAUDE_API_KEY
};
try {
if (!resolvedKeys.deepl) {
return res.status(400).json({ success: false, error: "DeepL API açarı daxil edilməyib." });
}
if (!resolvedKeys.claude) {
return res.status(400).json({ success: false, error: "Claude API açarı daxil edilməyib." });
}
// 1. Initial translation (DeepL)
const deeplText = (await translateDeepL([originalText], targetLang, resolvedKeys.deepl))[0];
// 2. Parallel peer review (Gemini / OpenAI)
const [geminiReview, openaiReview] = await Promise.all([
resolvedKeys.gemini ? reviewGemini(originalText, deeplText, targetLangName, resolvedKeys.gemini, fullContext, contentType) : Promise.resolve("BYPASSED"),
resolvedKeys.openai ? reviewOpenAI(originalText, deeplText, targetLangName, resolvedKeys.openai, fullContext, contentType) : Promise.resolve("BYPASSED")
]);
// 3. Synthesis (Claude with 4 Retries)
const claudeResult = await synthesizeClaude(
originalText,
deeplText,
geminiReview,
openaiReview,
targetLangName,
resolvedKeys.claude,
fullContext,
contentType,
4
);
res.json({
success: true,
deepl: deeplText,
gemini: geminiReview,
openai: openaiReview,
claude: claudeResult
});
} catch (error) {
console.error("Server API translation error:", error);
res.status(500).json({ success: false, error: error.message || "Tərcümə zamanı server xətası." });
}
});
// -------------------------------------------------------------
// POST Route for Granular Single-Step Retries
// -------------------------------------------------------------
app.post('/api/retry-step', async (req, res) => {
const { step, originalText, deeplText, geminiReview, openaiReview, targetLang, targetLangName, fullContext, contentType, apiKeys } = req.body;
const resolvedKeys = {
deepl: apiKeys?.deepl || process.env.VITE_DEEPL_KEY || process.env.DEEPL_API_KEY,
gemini: apiKeys?.gemini || process.env.VITE_GEMINI_KEY || process.env.GEMINI_API_KEY,
openai: apiKeys?.openai || process.env.VITE_OPENAI_KEY || process.env.OPENAI_API_KEY,
claude: apiKeys?.claude || process.env.VITE_CLAUDE_KEY || process.env.CLAUDE_API_KEY
};
try {
if (step === 'deepl') {
const newDeepl = (await translateDeepL([originalText], targetLang, resolvedKeys.deepl))[0];
return res.json({ success: true, deepl: newDeepl });
} else if (step === 'gemini') {
const newGemini = await reviewGemini(originalText, deeplText, targetLangName, resolvedKeys.gemini, fullContext, contentType);
return res.json({ success: true, gemini: newGemini });
} else if (step === 'openai') {
const newOpenAI = await reviewOpenAI(originalText, deeplText, targetLangName, resolvedKeys.openai, fullContext, contentType);
return res.json({ success: true, openai: newOpenAI });
} else if (step === 'claude') {
const newClaude = await synthesizeClaude(originalText, deeplText, geminiReview, openaiReview, targetLangName, resolvedKeys.claude, fullContext, contentType, 4);
return res.json({ success: true, claude: newClaude });
} else {
return res.status(400).json({ success: false, error: "Nəzərdə tutulmayan addım tipi." });
}
} catch (err) {
console.error(`Retry step ${step} error:`, err);
return res.status(500).json({ success: false, error: err.message });
}
});
// -------------------------------------------------------------
// Central Storage API for Multi-Browser Task Synchronization
// -------------------------------------------------------------
const TASKS_FILE_PATH = path.join(process.cwd(), 'data_tasks.json');
app.get('/api/tasks', (req, res) => {
try {
if (fs.existsSync(TASKS_FILE_PATH)) {
const data = fs.readFileSync(TASKS_FILE_PATH, 'utf8');
return res.json(JSON.parse(data));
}
return res.json(null);
} catch (err) {
console.error("Error reading tasks file:", err);
return res.status(500).json({ error: "Failed to read tasks" });
}
});
app.post('/api/tasks', (req, res) => {
try {
const { tasks } = req.body;
if (Array.isArray(tasks)) {
fs.writeFileSync(TASKS_FILE_PATH, JSON.stringify(tasks, null, 2), 'utf8');
return res.json({ success: true, count: tasks.length });
}
return res.status(400).json({ error: "Invalid tasks format" });
} catch (err) {
console.error("Error saving tasks file:", err);
return res.status(500).json({ error: "Failed to save tasks" });
}
});
// -------------------------------------------------------------
// Formbricks API Proxy
// -------------------------------------------------------------
app.get('/api/formbricks/survey/:id', async (req, res) => {
try {
const surveyId = req.params.id;
const apiKey = process.env.Formbricks_API;
if (!apiKey) {
return res.status(400).json({ error: "Formbricks API key is missing in .env.local" });
}
const response = await fetch(`${FORMBRICKS_BASE_URL}/api/v1/management/surveys/${surveyId}`, {
method: 'GET',
headers: {
'x-api-key': apiKey,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errText = await response.text();
return res.status(response.status).json({ error: `Formbricks fetch failed: ${response.status}`, details: errText });
}
const data = await response.json();
return res.json(data);
} catch (err) {
console.error("Error fetching formbricks survey:", err);
return res.status(500).json({ error: "Failed to fetch survey from Formbricks" });
}
});
app.put('/api/formbricks/survey/:id', async (req, res) => {
try {
const surveyId = req.params.id;
const surveyData = req.body;
const apiKey = process.env.Formbricks_API;
if (!apiKey) {
return res.status(400).json({ error: "Formbricks API key is missing in .env.local" });
}
// Clean payload to comply with Formbricks Zod validation
if (surveyData && typeof surveyData === 'object') {
if (surveyData.blocks && surveyData.questions) {
delete surveyData.questions; // Formbricks forbids sending both questions and blocks
}
// Collect all active language codes if present
const activeCodes = (surveyData.languages || [])
.filter(l => l.enabled !== false)
.map(l => l.language?.code || l.code)
.filter(Boolean);
// Recursive helper to fill empty/missing language entries with default fallback
const fillMissingLangs = (obj) => {
if (!obj || typeof obj !== 'object') return;
if (typeof obj.default === 'string') {
for (const code of activeCodes) {
if (!obj[code] || (typeof obj[code] === 'string' && !obj[code].trim())) {
obj[code] = obj.default;
}
}
}
for (const k in obj) {
if (typeof obj[k] === 'object') {
fillMissingLangs(obj[k]);
}
}
};
if (activeCodes.length > 0) {
fillMissingLangs(surveyData);
}
delete surveyData.createdAt;
delete surveyData.updatedAt;
delete surveyData.createdBy;
delete surveyData.segment;
delete surveyData.triggers;
delete surveyData.followUps;
delete surveyData.languages; // Read-only metadata that fails Zod date validation
}
const response = await fetch(`${FORMBRICKS_BASE_URL}/api/v1/management/surveys/${surveyId}`, {
method: 'PUT',
headers: {
'x-api-key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(surveyData)
});
if (!response.ok) {
const errText = await response.text();
return res.status(response.status).json({ error: `Formbricks update failed: ${response.status}`, details: errText });
}
const text = await response.text();
const data = text ? JSON.parse(text) : { success: true };
return res.json(data);
} catch (err) {
console.error("Error updating formbricks survey:", err);
return res.status(500).json({ error: "Failed to update survey in Formbricks" });
}
});
// Serve frontend build in production / Hugging Face Spaces
const __dirname = path.resolve();
if (fs.existsSync(path.join(__dirname, 'dist'))) {
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api')) return next();
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
}
app.listen(PORT, () => {
console.log(`Backend server secure proxy is running on port ${PORT}`);
});