Spaces:
Sleeping
Sleeping
| import express from 'express'; | |
| import cors from 'cors'; | |
| import { GoogleGenAI } from '@google/genai'; | |
| import path from 'path'; | |
| import { fileURLToPath } from 'url'; | |
| // Fix __dirname in ES module | |
| const __filename = fileURLToPath(import.meta.url); | |
| const __dirname = path.dirname(__filename); | |
| const app = express(); | |
| app.use(cors()); | |
| app.use(express.json()); | |
| // Serve Vite frontend build | |
| app.use(express.static(path.join(__dirname, '../dist'))); | |
| app.post('/api/translate', async (req, res) => { | |
| const { inputCode, outputLanguage } = req.body; | |
| if (!inputCode || !outputLanguage) return res.status(400).json({ error: 'Missing input' }); | |
| try { | |
| const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); | |
| const prompt = `Translate code to ${outputLanguage} only, no markdown:\n${inputCode}`; | |
| const stream = await ai.models.generateContentStream({ | |
| model: 'gemini-3-flash-preview', | |
| contents: prompt, | |
| config: { systemInstruction: "Only output raw code, no explanations." } | |
| }); | |
| let full = ''; | |
| for await (const chunk of stream) full += chunk.text || ''; | |
| const displayCode = full.replace(/^```\w*\n?/, '').replace(/```$/, ''); | |
| res.json({ code: displayCode }); | |
| } catch (e) { | |
| console.error(e); | |
| res.status(500).json({ error: 'Generation failed' }); | |
| } | |
| }); | |
| // Serve index.html for all other routes | |
| app.get('*', (req, res) => { | |
| res.sendFile(path.join(__dirname, '../dist/index.html')); | |
| }); | |
| const PORT = process.env.PORT || 7860; | |
| app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); | |