| import express from "express"; |
|
|
| const app = express(); |
| app.use(express.json()); |
| app.use(express.static("public")); |
|
|
| const ENV_API_KEY = process.env.OPENAI_API_KEY ?? null; |
|
|
| const SUPPORTED_LANGUAGES = { |
| en: "English", pl: "Polish", de: "German", fr: "French", |
| es: "Spanish", it: "Italian", ja: "Japanese", zh: "Chinese", |
| uk: "Ukrainian", ru: "Russian", |
| }; |
|
|
| app.post("/session", async (req, res) => { |
| const targetLanguage = req.body.targetLanguage ?? "en"; |
| const inputLanguage = req.body.inputLanguage ?? null; |
|
|
| |
| const apiKey = ENV_API_KEY ?? req.body.apiKey ?? null; |
|
|
| if (!apiKey || !apiKey.startsWith("sk-")) { |
| return res.status(401).json({ error: "Brak lub nieprawidłowy klucz API OpenAI." }); |
| } |
|
|
| if (!SUPPORTED_LANGUAGES[targetLanguage]) { |
| return res.status(400).json({ error: `Nieobsługiwany język: ${targetLanguage}` }); |
| } |
|
|
| try { |
| const session = { |
| model: "gpt-realtime-translate", |
| audio: { output: { language: targetLanguage } }, |
| }; |
|
|
| if (inputLanguage && SUPPORTED_LANGUAGES[inputLanguage]) { |
| session.audio.input = { language: inputLanguage }; |
| } |
|
|
| const response = await fetch( |
| "https://api.openai.com/v1/realtime/translations/client_secrets", |
| { |
| method: "POST", |
| headers: { |
| Authorization: `Bearer ${apiKey}`, |
| "Content-Type": "application/json", |
| }, |
| body: JSON.stringify({ session }), |
| } |
| ); |
|
|
| if (!response.ok) { |
| const err = await response.text(); |
| console.error("OpenAI error:", err); |
| return res.status(response.status).json({ error: "Błąd OpenAI API", details: err }); |
| } |
|
|
| res.json(await response.json()); |
| } catch (err) { |
| console.error("Fetch error:", err); |
| res.status(500).json({ error: "Błąd serwera", details: err.message }); |
| } |
| }); |
|
|
| const PORT = process.env.PORT ?? 7860; |
| app.listen(PORT, "0.0.0.0", () => { |
| console.log(`Serwer działa na porcie ${PORT}`); |
| if (!ENV_API_KEY) { |
| console.log("INFO: OPENAI_API_KEY nie ustawiony — użytkownicy podają klucz przez UI."); |
| } |
| }); |
|
|