Spaces:
Sleeping
Sleeping
Create server/server.js
Browse files- server/server.js +35 -0
server/server.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import express from 'express';
|
| 2 |
+
import cors from 'cors';
|
| 3 |
+
import { GoogleGenAI } from "@google/genai";
|
| 4 |
+
|
| 5 |
+
const app = express();
|
| 6 |
+
app.use(cors());
|
| 7 |
+
app.use(express.json());
|
| 8 |
+
|
| 9 |
+
const PORT = process.env.PORT || 7860;
|
| 10 |
+
|
| 11 |
+
app.post('/api/translate', async (req, res) => {
|
| 12 |
+
const { inputCode, outputLanguage } = req.body;
|
| 13 |
+
if (!inputCode || !outputLanguage) return res.status(400).json({ error: 'Missing input' });
|
| 14 |
+
|
| 15 |
+
try {
|
| 16 |
+
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
|
| 17 |
+
const prompt = `Translate code to ${outputLanguage} only, no markdown:\n${inputCode}`;
|
| 18 |
+
|
| 19 |
+
const stream = await ai.models.generateContentStream({
|
| 20 |
+
model: 'gemini-3-flash-preview',
|
| 21 |
+
contents: prompt,
|
| 22 |
+
config: { systemInstruction: "Only output raw code, no explanations." }
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
let full = '';
|
| 26 |
+
for await (const chunk of stream) full += chunk.text || '';
|
| 27 |
+
const displayCode = full.replace(/^```\w*\n?/, '').replace(/```$/, '');
|
| 28 |
+
res.json({ code: displayCode });
|
| 29 |
+
} catch (e) {
|
| 30 |
+
console.error(e);
|
| 31 |
+
res.status(500).json({ error: 'Generation failed' });
|
| 32 |
+
}
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
|