這是一個簡單的語音翻譯 Web App,支援:
- 繁體中文語音輸入(Web Speech API)
- 自動轉換為簡體中文
- 使用 Google Translate API 翻譯成英文
- 支援 HTTPS (Web Speech API 運作必需)
程式碼 (app_lite.py)
import http.server
import json
import urllib.request
import urllib.parse
import ssl
import os
# 簡單的繁簡轉換字典 (常用字)
TRAD_TO_SIMP = {
'繁': '繁', '體': '体', '簡': '简', '中': '中', '文': '文', '語': '语', '音': '音', '轉': '转', '寫': '写',
'發': '发', '現': '现', '開': '开', '關': '关', '電': '电', '腦': '脑', '機': '机', '會': '会', '過': '过',
'時': '时', '間': '间', '對': '对', '錯': '错', '點': '点', '說': '说', '話': '话', '聽': '听', '看': '看',
'學': '学', '習': '习', '國': '国', '家': '家', '這': '这', '那': '那', '麼': '么', '樣': '样', '後': '后',
'為': '为', '於': '于', '與': '与', '應': '应', '歸': '归', '義': '义', '樂': '乐', '氣': '气',
}
def convert_to_simp(text):
return "".join(TRAD_TO_SIMP.get(c, c) for c in text)
def translate_to_en(text):
try:
url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=zh-TW&tl=en&dt=t&q=" + urllib.parse.quote(text)
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req) as response:
data = json.loads(response.read().decode('utf-8'))
return "".join([item[0] for item in data[0]])
except Exception as e:
return f"Translation error: {str(e)}"
class SimpleHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'templates', 'index.html')
with open(file_path, 'rb') as f:
self.wfile.write(f.read())
except Exception as e:
self.wfile.write(f"Error loading template: {str(e)}".encode('utf-8'))
else:
self.send_error(404)
def do_POST(self):
if self.path == '/process':
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))
text = data.get('text', '')
mode = data.get('mode', 'trad')
if mode == 'simp':
result = convert_to_simp(text)
elif mode == 'en':
result = translate_to_en(text)
else:
result = text
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'result': result}).encode('utf-8'))
if __name__ == '__main__':
base_dir = os.path.dirname(os.path.abspath(__file__))
cert_file = os.path.join(base_dir, 'cert.pem')
key_file = os.path.join(base_dir, 'key.pem')
httpd = http.server.HTTPServer(('0.0.0.0', 5000), SimpleHandler)
# 配置 SSL
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile=cert_file, keyfile=key_file)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
print("SSL Server started at https://localhost:5000")
httpd.serve_forever()
前端模板 (templates/index.html)
檔案路徑:speech-translator/templates/index.html
Google 風格語音翻譯器
Heathcliff 翻譯
服務已綁定至 0.0.0.0:5000
如何執行
- 確保已產生自簽章憑證
cert.pem和key.pem。 - 執行:
python3 app_lite.py - 瀏覽:
https://localhost:5000(或透過 frp proxy 存取)
發佈留言