Last active
May 27, 2023 19:06
-
-
Save BoyanXu/72d763d2a38c5186e2a794a2eb133fd4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import os, json, http.client, sys | |
from PyQt6.QtWidgets import QApplication, QMessageBox, QAbstractButton | |
from PyQt6.QtGui import QIcon, QPixmap, QClipboard | |
from PyQt6.QtCore import Qt | |
from pyperclip import paste, copy | |
from urllib.request import urlopen, Request | |
def deepl_api(text): | |
if not text.replace("\n", "").replace("\r", ""): | |
QMessageBox.warning(None, "Warning", '剪贴板为空,请选择文本') | |
exit(1) | |
try: | |
conn = http.client.HTTPConnection("127.0.0.1:1188") | |
payload = json.dumps({"text": text, "target_lang": "ZH"}) | |
conn.request("POST", "/translate", payload) | |
res = conn.getresponse().read() | |
return json.loads(res).get("data") | |
except: | |
QMessageBox.critical(None, "Error", '翻译出错,请稍后再试') | |
exit(1) | |
def display_results(translate_results): | |
msg = QMessageBox() | |
msg.setWindowTitle("DeepL") | |
msg.setText(translate_results) | |
pixmap = QPixmap("/usr/share/pixmaps/deepl_icon.png") | |
# pixmap.loadFromData(data) | |
msg.setWindowIcon(QIcon(pixmap)) | |
# Add a 'Copy' button | |
copy_button = msg.addButton('Copy', QMessageBox.ButtonRole.ActionRole) | |
# Add an 'OK' button | |
ok_button = msg.addButton(QMessageBox.StandardButton.Ok) | |
# Handle button clicks | |
def on_button_clicked(button): | |
if button == copy_button: | |
copy(translate_results) | |
msg.buttonClicked.connect(on_button_clicked) | |
msg.exec() | |
# msg.close() | |
if __name__ == "__main__": | |
app = QApplication(sys.argv) | |
text = paste() # 获取剪贴板 | |
translate_results = deepl_api(text) # 调用翻译接口 | |
display_results(translate_results) # 显示翻译结果 | |
app.quit() | |
sys.exit(0) |
Author
BoyanXu
commented
May 27, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment