|
分享源码
界面截图: |
- |
是否带模块: |
- |
备注说明: |
- |
变量名 | 类 型 | 静态 | 数组 | 备 注 | 计次 | 整数型 | | | 端口 | 整数型 | | | 端口状态 | 逻辑型 | | |
端口 = 17813 如果真 (端口检测 (端口, “127.0.0.1”) = 假)执行 (4, 取运行目录 () + “/build/deepl.exe”, , , 1 )计次循环首 (15, 计次 )端口状态 = 端口检测 (端口, “127.0.0.1”)如果真 (端口状态 = 真)跳出循环 ()程序_延时 (1000, )计次循环尾 ()如果真 (端口状态 = 假)信息框 (“Deepl初始化失败”, 0, , )返回 (假)返回 (真)|
翻译 | 字节集 | | |
query | 字节集 | | | | from | 文本型 | | | | to | 文本型 | | | |
变量名 | 类 型 | 静态 | 数组 | 备 注 | zyjs | zyJsonDocument | | | url | 文本型 | | | 响应数据 | 字节集 | | |
zyjs. 创建 (, , , )zyjs. 置文本W (编码_Ansi到Unicode (“query”, ), query )zyjs. 置文本 (“from_lang”, from )zyjs. 置文本 (“to_lang”, to )url = “http://127.0.0.1:17813/”网页_访问S (url, 1, zyjs. 到文本UTF8 (, , , ), , , , , , , , , , , , , , 响应数据, , , , )zyjs. 解析W (编码_Utf8到Unicode (响应数据 ), , , )如果真 (zyjs. 取逻辑 (“error”)) 返回 (zyjs. 到文本W (, , , )) 返回 (zyjs.取文本W (编码_Ansi到Unicode (“response.result.texts[0].text”, )))
[Python] 纯文本查看 复制代码 from http.server import BaseHTTPRequestHandler, HTTPServer
from requests.exceptions import HTTPError
import requests
import random
import socket
import json
import time
def initData(source_lang, target_lang):
return {
"jsonrpc": "2.0",
"method": "LMT_handle_texts",
"params": {
"splitting": "newlines",
"lang": {
"source_lang_user_selected": source_lang,
"target_lang": target_lang
}
}
}
def getICount(translate_text):
return translate_text.count('i')
def getRandomNumber():
rand = random.randint(100000, 999999)
return rand * 1000
def getTimeStamp(iCount):
ts = int(time.time() * 1000)
if iCount != 0:
iCount += 1
return ts - (ts % iCount) + iCount
else:
return ts
def PostData(url, data):
headers = {"Content-Type": "application/json"}
try:
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
return response.json()
except HTTPError as e:
if response.status_code == 429:
return {"ErrorInfo": "Deepl拒绝请求码(429):你已达到请求上限,请稍后再试."}
else:
return {"ErrorInfo": str(e)}
except Exception as e:
return {"ErrorInfo": str(e)}
def translate(query, from_lang, to_lang):
targetLanguage = to_lang.upper()
sourceLanguage = from_lang.upper()
if not targetLanguage:
raise ValueError("不支持该语种")
source_lang = sourceLanguage or 'ZH'
target_lang = targetLanguage or 'EN'
translate_text = query or ''
if translate_text != '':
url = 'https://www2.deepl.com/jsonrpc'
id = getRandomNumber()
post_data = initData(source_lang, target_lang)
text = {
"text": translate_text,
"requestAlternatives": 3
}
post_data["id"] = id
post_data["params"]["texts"] = [text]
post_data["params"]["timestamp"] = getTimeStamp(
getICount(translate_text))
post_str = json.dumps(post_data)
if (id + 5) % 29 == 0 or (id + 3) % 13 == 0:
post_str = post_str.replace('"method":"', '"method" : "')
else:
post_str = post_str.replace('"method":"', '"method": "')
try:
response = PostData(url, post_str)
print("response",response)
if "error" in response:
return {"error": True,"response": response}
else:
return {"error": False,"response": response}
except Exception as e:
raise ValueError("请求错误 - " + str(e))
class MyRequestHandler(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
# 将接收到的POST内容解析为JSON
json_data = json.loads(post_data)
# 将JSON中的所有值转换为大写
for key in json_data:
print("read",key,json_data[key])
response = json.dumps(translate(json_data['query'], json_data['from_lang'], json_data['to_lang']))
self._set_response()
self.wfile.write(response.encode('utf-8'))
port = 17813
def run(server_class=HTTPServer, handler_class=MyRequestHandler):
server_address = ('127.0.0.1', port)
httpd = server_class(server_address, handler_class)
print(f'server port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
def is_port_in_use(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(("localhost", port))
return False
except OSError:
return True
if is_port_in_use(port):
print(f"端口 {port} 已被占用,取消运行。")
else:
run() # python38 -m nuitka --standalone --remove-output --mingw64 --onefile deepl.py
|
|