File size: 2,530 Bytes
b3b0b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 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!");
});