Skip to content

Commit

Permalink
feat: 支持命令行翻译 lfy -t "test"
Browse files Browse the repository at this point in the history
  • Loading branch information
yuhldr committed Sep 7, 2024
1 parent bed73fa commit 1844760
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 23 deletions.
54 changes: 34 additions & 20 deletions lfy.in
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
#!@PYTHON@

# lt
import argparse
import gettext
import locale
import os
import subprocess
import sys

import gi

gi.require_version("Adw", "1")
gi.require_version('Gio', '2.0')
gi.require_version('Gtk', '4.0')
gi.require_version('Gdk', '4.0')

APP_ID = '@APP_ID@'
VERSION = '@VERSION@'

Expand All @@ -22,7 +32,8 @@ if not os.path.exists(PKGDATA_DIR):
SCHEMAS_DIR = os.path.abspath(f"{THIS_DIR}/../share/")
PKGDATA_DIR = os.path.abspath(f"{SCHEMAS_DIR}/{APP_ID}/")
LOCALE_DIR = os.path.abspath(f"{SCHEMAS_DIR}/locale/")
subprocess.run(["glib-compile-schemas", f"{SCHEMAS_DIR}/glib-2.0/schemas"], check=True)
subprocess.run(
["glib-compile-schemas", f"{SCHEMAS_DIR}/glib-2.0/schemas"], check=True)

os.environ["XDG_DATA_DIRS"] = f'{SCHEMAS_DIR}:' + \
os.environ.get("XDG_DATA_DIRS", "")
Expand All @@ -32,28 +43,12 @@ if not os.path.exists(PKGDATA_DIR):
sys.path.append(PYTHON_DIR)


import gettext
import locale

import gi

# gi.require_version("Adw", "1.4")
gi.require_version("Adw", "1")
gi.require_version('Gio', '2.0')
# gi.require_version('Gtk', '4.12')
gi.require_version('Gtk', '4.0')

from gi.repository import Gio # pylint: disable=c0413


def set_internationalization():
"""Sets application internationalization."""
try:
locale.bindtextdomain(APP_ID, LOCALE_DIR)
locale.textdomain(APP_ID)
except AttributeError as e:
# Python built without gettext support does not have
# bindtextdomain() and textdomain().
print(f"Some gettext translations will not work. Error:\n{e}")

gettext.bindtextdomain(APP_ID, LOCALE_DIR)
Expand All @@ -62,8 +57,11 @@ def set_internationalization():

def set_resources():
"""Sets application ressource file."""
from gi.repository import Gio # pylint: disable=c0415

# pylint: disable=w0212
Gio.Resource._register(Gio.resource_load(os.path.join(PKGDATA_DIR, f'{APP_ID}.gresource')))
Gio.Resource._register(Gio.resource_load(
os.path.join(PKGDATA_DIR, f'{APP_ID}.gresource')))


def run_application():
Expand All @@ -83,9 +81,25 @@ def main():
_type_: _description_
"""
set_internationalization()

parser = argparse.ArgumentParser(description="translate")

parser.add_argument('-t', type=str, help='翻译后面的文字')
parser.add_argument('-c', action='store_true', help='翻译剪贴板')

args = parser.parse_args()

if args.t:
from lfy.code import req_text # pylint: disable=c0415
return req_text(args.t)

# if args.c:
# from lfy.code import req_clip
# return req_clip()

set_resources()
return run_application()
return sys.exit(run_application())


if __name__ == '__main__':
sys.exit(main())
main()
50 changes: 50 additions & 0 deletions lfy/code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import os
import traceback
from gettext import gettext as _

from gi.repository import Gdk

from lfy.api import create_server, get_lang, server_key2i
from lfy.settings import Settings


def req_text(s):
"""子线程翻译
Args:
s (str): _description_
server (Server): _description_
"""
print(s)
setting = Settings.get()

# 设置代理地址和端口号
proxy_address = setting.vpn_addr_port
if len(proxy_address) > 0:
# 设置环境变量
os.environ['http_proxy'] = proxy_address
os.environ['https_proxy'] = proxy_address
tran_server = create_server(setting.server_selected_key)

try:

i = server_key2i(setting.server_selected_key)

gl = get_lang(i, setting.lang_selected_n)
print(tran_server.name, gl.get_name())

_ok, text = tran_server.translate_text(s, gl.key)
print(text)

except Exception as e: # pylint: disable=W0718
error_msg = _("something error:")
error_msg2 = f"{str(e)}\n\n{traceback.format_exc()}"
text = f"{error_msg}{tran_server.name}\n\n{error_msg2}"

def req_clip():
print("req_clip")
def on_active_copy(cb2, res):
req_text(cb2.read_text_finish(res))

cb = Gdk.Display().get_default().get_clipboard()
cb.read_text_async(None, on_active_copy)
11 changes: 8 additions & 3 deletions lfy/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def set_paned_position(self, p):
"""设置或恢复,原文字和翻译的比例
Args:
p (_type_): 设置的位置
p (int): 设置的位置
"""
if self.paned_position > 0:
p = self.paned_position
Expand All @@ -153,7 +153,7 @@ def down_paned_position(self):
self.set_paned_position(height)

def save_settings(self, _a):
"""_summary_
"""保存设置
Args:
_a (TranslateWindow): _description_
Expand Down Expand Up @@ -196,14 +196,19 @@ def _set_tv_copy(self, _a):
self.is_tv_copy = True

def update_ocr(self, path):
"""执行ocr文本识别
Args:
path (str): _description_
"""
threading.Thread(target=self.request_text, daemon=True,
args=(path, self.ocr_server, None,)).start()

def update(self, text, reload=False, del_wrapping=True):
"""翻译
Args:
text (_type_): _description_
text (str): _description_
reload (bool, optional): _description_. Defaults to False.
"""
buffer_from = self.tv_from.get_buffer()
Expand Down

0 comments on commit 1844760

Please sign in to comment.