Skip to content

Commit

Permalink
feat: Add translation support 添加基本翻译支持 (#68)
Browse files Browse the repository at this point in the history
* feat: Add initial translation support

* Added a translation test. It works well

* Added some translations

* Added more translations & Default to use en_US

* Test tips translation.

* Remove unused files

* feat: Detecting local using ip address

* Using wget instead

* Fix an error in json parsing

---------

Co-authored-by: 鱼香ROS <[email protected]>
  • Loading branch information
elysia-best and fishros authored Sep 4, 2024
1 parent d25178c commit dbc9e54
Show file tree
Hide file tree
Showing 6 changed files with 173 additions and 35 deletions.
4 changes: 2 additions & 2 deletions install
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
mkdir -p /tmp/fishinstall/tools
mkdir -p /tmp/fishinstall/tools/translation/assets
wget http://mirror.fishros.com/install/install.py -O /tmp/fishinstall/install.py 2>>/dev/null
source /etc/profile
# 强制解锁,太多用户遇到这个问题了,没办法,后续想个办法解决下
Expand All @@ -9,7 +9,7 @@ source /etc/profile
if [ $UID -eq 0 ];then
apt-get install sudo
fi
sudo apt install python3-distro python3-yaml -y
sudo apt install python3-distro python3-yaml -y
sudo python3 /tmp/fishinstall/install.py
sudo rm -rf /tmp/fishinstall/
sudo rm fishros
Expand Down
44 changes: 31 additions & 13 deletions install.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
# -*- coding: utf-8 -*-
import os
import importlib

url_prefix = 'http://mirror.fishros.com/install/'

base_url = url_prefix+'tools/base.py'

_suported_languages = ['zh_CN', 'en_US']
lang_url = url_prefix+'tools/translation/assets/{}.py'
_translator_files = ['translator']
translator_url = url_prefix+'tools/translation/{}.py'

INSTALL_ROS = 0 # 安装ROS相关
INSTALL_SOFTWARE = 1 # 安装软件
CONFIG_TOOL = 2 # 配置相关
Expand Down Expand Up @@ -56,10 +62,22 @@
def main():
# download base
os.system("wget {} -O /tmp/fishinstall/{} --no-check-certificate".format(base_url,base_url.replace(url_prefix,'')))

from tools.base import CmdTask,FileUtils,PrintUtils,ChooseTask,ChooseWithCategoriesTask
from tools.base import encoding_utf8,osversion,osarch
from tools.base import run_tool_file,download_tools
from tools.base import config_helper

# download translations
for files in _translator_files:
os.system("wget {} -O /tmp/fishinstall/{} --no-check-certificate".format(translator_url.format(files),translator_url.format(files).replace(url_prefix,'')))

for lang in _suported_languages:
os.system("wget {} -O /tmp/fishinstall/{} --no-check-certificate".format(lang_url.format(lang),lang_url.format(lang).replace(url_prefix,'')))

# Import translations
tr = importlib.import_module("tools.translation.translator").Linguist()

# PrintUtils.print_delay(f"检测到你的系统版本信息为{osversion.get_codename()},{osarch}",0.001)
# 使用量统计
CmdTask("wget https://fishros.org.cn/forum/topic/1733 -O /tmp/t1733 -q && rm -rf /tmp/t1733").run()
Expand All @@ -73,9 +91,9 @@ def main():
print('Finish! Please Try Again!')
print('Solutions: https://fishros.org.cn/forum/topic/24 ')
return False
PrintUtils.print_success("基础检查通过...")
PrintUtils.print_success(tr.tr("基础检查通过..."))

book = """
book = tr.tr("""
.-~~~~~~~~~-._ _.-~~~~~~~~~-.
__.' ~. .~ `.__
.'// 开卷有益 \./ 书山有路 \\ `.
Expand All @@ -84,29 +102,29 @@ def main():
.'//.-" `-. | .-' "-.\\`.
.'//______.============-.. \ | / ..-============.______\\`.
.'______________________________\|/______________________________`
----------------------------------------------------------------------"""
----------------------------------------------------------------------""")

tip = """===============================================================================
tip =tr.tr("""===============================================================================
======欢迎使用一键安装工具,人生苦短,三省吾身,省时省力省心!=======
======一键安装已开源,请放心使用:https://github.com/fishros/install =======
===============================================================================
"""
end_tip = """===============================================================================
""")
end_tip = tr.tr("""===============================================================================
如果觉得工具好用,请给个star,如果你想和小鱼一起编写工具,请关注微信公众号<鱼香ROS>,联系小鱼
更多工具教程,请访问鱼香ROS官方网站:http://fishros.com
"""
""")
PrintUtils.print_delay(tip,0.001)
PrintUtils.print_delay(book,0.001)


# download tools
choose_dic = {}
# for tool_id in tools.keys(): choose_dic[tool_id] = tools[tool_id]["tip"]
code,result = ChooseWithCategoriesTask(tool_categories, tips="---众多工具,等君来用---",categories=tools_type_map).run()
code,result = ChooseWithCategoriesTask(tool_categories, tips=tr.tr("---众多工具,等君来用---"),categories=tools_type_map).run()

if code==0: PrintUtils().print_success("是觉得没有合胃口的菜吗?那快联系的小鱼增加菜单吧~")
if code==0: PrintUtils().print_success(tr.tr("是觉得没有合胃口的菜吗?那快联系的小鱼增加菜单吧~"))
elif code==77:
code,result = ChooseTask(choose_dic, "请选择你要测试的程序:").run()
code,result = ChooseTask(choose_dic, tr.tr("请选择你要测试的程序:")).run()
if code<0 and code>=77: return False
# CmdTask("cp tools/* /tmp/fishinstall/tools/").run
print(tools[code]['tool'].replace(url_prefix,'').replace("/","."))
Expand All @@ -116,9 +134,9 @@ def main():
run_tool_file(tools[code]['tool'].replace(url_prefix,'').replace("/","."))

config_helper.gen_config_file()
PrintUtils.print_delay("欢迎加入机器人学习交流QQ群:438144612(入群口令:一键安装)",0.1)
PrintUtils.print_success("鱼香小铺正式开业,最低499可入手一台能建图会导航的移动机器人,淘宝搜店:鱼香ROS 或打开链接查看:https://item.taobao.com/item.htm?id=696573635888",0.001)
PrintUtils.print_success("如在使用过程中遇到问题,请打开:https://fishros.org.cn/forum 进行反馈",0.001)
PrintUtils.print_delay(tr.tr("欢迎加入机器人学习交流QQ群:438144612(入群口令:一键安装)"),0.1)
PrintUtils.print_success(tr.tr("鱼香小铺正式开业,最低499可入手一台能建图会导航的移动机器人,淘宝搜店:鱼香ROS 或打开链接查看:https://item.taobao.com/item.htm?id=696573635888"),0.001)
PrintUtils.print_success(tr.tr("如在使用过程中遇到问题,请打开:https://fishros.org.cn/forum 进行反馈"),0.001)

if __name__=='__main__':
main()
43 changes: 23 additions & 20 deletions tools/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sys
import time
import subprocess
import importlib
import locale
from queue import Queue
import threading
Expand All @@ -24,6 +25,8 @@
encoding = locale.getpreferredencoding()
encoding_utf8 = encoding.find("UTF")>-1

# Import translations
tr = importlib.import_module("tools.translation.translator").Linguist()

class ConfigHelper():
def __init__(self,record_file=None):
Expand Down Expand Up @@ -930,7 +933,7 @@ def getlogs(self):
logstr += log
return logstr


def command_thread(self,executable='/bin/sh'):
out,err = [],[]
self.sub = subprocess.Popen(self.command,
Expand Down Expand Up @@ -1017,17 +1020,17 @@ def __choose(data,tips,array):
# 0 quit
choose = -1
for key in dic:
PrintUtils.print_delay('[{}]:{}'.format(key,dic[key]),0.005)
PrintUtils.print_delay('[{}]:{}'.format(key,tr.tr(dic[key])),0.005)

choose = None
choose_item = config_helper.get_input_value()

while True:
if choose_item:
choose = str(choose_item['choose'])
print("为您从配置文件找到默认选项:",choose_item)
print(tr.tr("为您从配置文件找到默认选项:"),choose_item)
else:
choose = input("请输入[]内的数字以选择:")
choose = input(tr.tr("请输入[]内的数字以选择:"))
choose_item = None
# Input From Queue
if choose.isdecimal() :
Expand All @@ -1039,7 +1042,7 @@ def __choose(data,tips,array):
return choose,dic[choose]

def run(self):
PrintUtils.print_delay("RUN Choose Task:[请输入括号内的数字]")
PrintUtils.print_delay(tr.tr("RUN Choose Task:[请输入括号内的数字]"))
PrintUtils.print_delay(self.tips,0.001)
return ChooseTask.__choose(self.dic,self.tips,self.array)

Expand All @@ -1062,10 +1065,10 @@ def __choose(data,tips,array,categories):
tool_ids = [0]
# 打印不同类型工具的分类结果
for tool_type, tools_list in dic.items():
PrintUtils.print_delay("{}:".format(categories[tool_type]),0.005)
PrintUtils.print_delay("{}:".format(tr.tr(categories[tool_type])),0.005)
sortkeys = sorted(tools_list.keys())
for tool_id in sortkeys:
PrintUtils.print_delay(" [{}]:{}".format(tool_id,tools_list[tool_id]['tip']),0.005)
PrintUtils.print_delay(" [{}]:{}".format(tool_id,tr.tr(tools_list[tool_id]['tip'])),0.005)
tool_ids.append(tool_id)
print()
PrintUtils.print_delay("[0]:quit\n",0.005)
Expand All @@ -1076,9 +1079,9 @@ def __choose(data,tips,array,categories):
while True:
if choose_item:
choose_id = str(choose_item['choose'])
print("为您从配置文件找到默认选项:",choose_item)
print(tr.tr("为您从配置文件找到默认选项:"),choose_item)
else:
choose_id = input("请输入[]内的数字以选择:")
choose_id = input(tr.tr("请输入[]内的数字以选择:"))
choose_item = None
# Input From Queue
if choose_id.isdecimal() :
Expand All @@ -1090,7 +1093,7 @@ def __choose(data,tips,array,categories):
return choose_id,""

def run(self):
PrintUtils.print_delay("RUN Choose Task:[请输入括号内的数字]")
PrintUtils.print_delay(tr.tr("RUN Choose Task:[请输入括号内的数字]"))
PrintUtils.print_delay(self.tips,0.001)
return ChooseWithCategoriesTask.__choose(self.dic,self.tips,self.array,self.categories)

Expand Down Expand Up @@ -1140,7 +1143,7 @@ def getusers():
# TODO 使用ls再次获取用户名
users = users[1][0].split(" ")
if len(users[0])==0:
user = input("请手动输入你的用户名>>")
user = input(tr.tr("请手动输入你的用户名>>"))
users.clear()
users.append(user)
return users
Expand All @@ -1161,7 +1164,7 @@ def getusershome():

@staticmethod
def new(path,name=None,data=''):
PrintUtils.print_info("创建文件:{}".format(path+name))
PrintUtils.print_info(tr.tr("创建文件:{}").format(path+name))
if not os.path.exists(path):
CmdTask("sudo mkdir -p {}".format(path),3).run()
if name!=None:
Expand Down Expand Up @@ -1256,13 +1259,13 @@ def checkapt():
result = CmdTask('sudo apt update',100).run()
if result[0]!=0:
if FileUtils.check_result(result,['certificate','证书']):
PrintUtils.print_warn("检测到发生证书校验错误{},自动取消https校验,如有需要请手动删除:rm /etc/apt/apt.conf.d/99verify-peer.conf".format(result[2]))
PrintUtils.print_warn(tr.tr("检测到发生证书校验错误{},自动取消https校验,如有需要请手动删除:rm /etc/apt/apt.conf.d/99verify-peer.conf").format(result[2]))
CmdTask('touch /etc/apt/apt.conf.d/99verify-peer.conf').run()
CmdTask('echo "Acquire { https::Verify-Peer false }" > /etc/apt/apt.conf.d/99verify-peer.conf').run()
CmdTask("sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F42ED6FBAB17C654",10).run()
result = CmdTask('sudo apt update',100).run()
if result[0]!=0:
PrintUtils.print_warn("apt更新失败,后续程序可能会继续尝试...,{}".format(result[2]))
PrintUtils.print_warn(tr.tr("apt更新失败,后续程序可能会继续尝试...,{}").format(result[2]))
return False
return True

Expand All @@ -1272,15 +1275,15 @@ def getArch():
arc = result[1][0].strip("\n")
if arc=='armhf': arc = 'arm64'
if result[0]==0: return arc
PrintUtils.print_error("小鱼提示:自动获取系统架构失败...请手动选择")
PrintUtils.print_error(tr.tr("小鱼提示:自动获取系统架构失败...请手动选择"))
# @TODO 提供架构选项 amd64,i386,arm
return None

@staticmethod
def search_package(name,pattern,replace1="",replace2=""):
result = CmdTask("sudo apt search {} ".format(name),20).run()
if result[0]!=0:
PrintUtils.print_error("搜索不到任何{}相关的包".format(name))
PrintUtils.print_error(tr.tr("搜索不到任何{}相关的包").format(name))
return None
dic = {}
for line in result[1]:
Expand All @@ -1300,7 +1303,7 @@ def install_pkg(name,apt_tool="apt",auto_yes=True,os_command=False):
for key in dic.keys():
result = CmdTask("sudo {} install {} {}".format(apt_tool,dic[key],yes), 0, os_command=os_command).run()
if not result:
PrintUtils.print_warn("没有找到包:{}".format(name))
PrintUtils.print_warn(tr.tr("没有找到包:{}").format(name))
return result

@staticmethod
Expand All @@ -1318,8 +1321,8 @@ def install_pkg_check_dep(name):
while FileUtils.check_result(result,['未满足的依赖关系','unmet dependencies']):
# 尝试使用aptitude解决依赖问题
PrintUtils.print_warn("============================================================")
PrintUtils.print_delay("请注意我,检测你在安装过程中出现依赖问题,请在稍后选择解决方案(第一个解决方案不一定可以解决问题,如再遇到可以采用下一个解决方案),即可解决")
input("确认了解上述情况,请输入回车继续安装")
PrintUtils.print_delay(tr.tr("请注意我,检测你在安装过程中出现依赖问题,请在稍后选择解决方案(第一个解决方案不一定可以解决问题,如再遇到可以采用下一个解决方案),即可解决"))
input(tr.tr("确认了解上述情况,请输入回车继续安装"))
result = AptUtils.install_pkg(name,apt_tool="aptitude", os_command = True, auto_yes=False)
result = AptUtils.install_pkg(name,apt_tool="aptitude", os_command = False, auto_yes=True)

Expand Down Expand Up @@ -1384,7 +1387,7 @@ def __init__(self,name,tool_type):

def init(self):
# 初始化部分
PrintUtils.print_delay("欢迎使用{},本工具由作者{}提供".format(self.name,self.autor))
PrintUtils.print_delay(tr.tr("欢迎使用{},本工具由作者{}提供").format(self.name,self.autor))

def run(self):
# 运行该任务
Expand Down
Loading

0 comments on commit dbc9e54

Please sign in to comment.