Spaces:
Sleeping
Sleeping
// wechat-miniprogram-translator/server/server.js | |
const express = require('express'); | |
const fetch = require('node-fetch'); | |
const app = express(); | |
const port = 3000; | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
// CORS for development (allow requests from any origin) | |
app.use((req, res, next) => { | |
res.header('Access-Control-Allow-Origin', '*'); | |
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); | |
next(); | |
}); | |
// ASR (Speech-to-Text) Endpoint - Placeholder | |
app.post('/asr', (req, res) => { | |
// In a real application, you would receive the audio file here (e.g., via multipart/form-data) | |
// and send it to a real ASR service (e.g., Tencent Cloud, Baidu AI, Google Speech-to-Text). | |
// For this prototype, we'll simulate a response. | |
console.log('Received ASR request. Simulating response...'); | |
const simulatedText = '这是模拟的语音识别结果。'; // You can change this for testing | |
res.json({ transcript: simulatedText }); | |
}); | |
// Translation Endpoint - Proxy for Google Translate API | |
app.post('/translate', async (req, res) => { | |
const { text, sourceLang, targetLang } = req.body; | |
if (!text || !sourceLang || !targetLang) { | |
return res.status(400).json({ error: 'Missing text, sourceLang, or targetLang' }); | |
} | |
const source = sourceLang.split('-')[0]; | |
const target = targetLang.split('-')[0]; | |
if (source === target) { | |
return res.json({ translatedText: text }); | |
} | |
const apiUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${source}&tl=${target}&dt=t&q=${encodeURIComponent(text)}`; | |
try { | |
const response = await fetch(apiUrl); | |
const data = await response.json(); | |
if (data && data[0] && data[0][0] && data[0][0][0]) { | |
const translatedText = data[0].map(segment => segment[0]).join(''); | |
res.json({ translatedText }); | |
} else { | |
console.error('Translation API returned unexpected data:', data); | |
res.status(500).json({ error: 'Translation failed: Unexpected API response' }); | |
} | |
} catch (error) { | |
console.error('Error calling Google Translate API:', error); | |
res.status(500).json({ error: 'Translation failed: Network error or API issue' }); | |
} | |
}); | |
app.listen(port, () => { | |
console.log(`Backend server listening at http://localhost:${port}`); | |
console.log("Remember to start this server before running the Mini Program!"); | |
}); | |