Spaces:
Sleeping
Sleeping
File size: 1,565 Bytes
d6ea636 56578dc 19f40c6 56578dc d6ea636 56578dc 1f53a2f d6ea636 56578dc d6ea636 56578dc 19f40c6 56578dc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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}`));
|