美文网首页语言·翻译
利用Translate ToolKit 2.5.0 API构建F

利用Translate ToolKit 2.5.0 API构建F

作者: 叫我懒猫 | 来源:发表于2020-04-02 15:01 被阅读0次

    Translate ToolKit 2.5.0 API 是一个用于翻译行业的文档转换工具。例如将json或者html等转换成PO文件以供翻译使用。这里使用Flask web框架来实现Translate ToolKit api的基本功能。

    这是前几天的一个笔试,要求三天内利用api实现一个webApp,我在半睡半醒的“弥留之际”(这一阵子实在精神不佳)完成了这个任务,(虽然笔试没有后续,依旧没有工作~ 好了不废话,进入正题。

    本文原文在我的开源中国博客:https://my.oschina.net/finchxu/blog/3217430

    项目在我的github https://github.com/finch-xu/f-tt 方便下载查看

    0. 环境:

    Python3环境下 pip install flask translate-toolkit uwsgi等

    1. 功能实现:

    这个api主要是一个转换器功能,和附带了一些工具类,这里简单实现了txt文件转po文件,json文件转po文件,po文件的综合数据统计 这三个功能。

    txt/json转po文件是分别调用txt2po/json2po,来看看API文档是怎么写的:

    官方文档

    这里打open文件,然后调用txt2po,他的内部原理包含了readlines方法还有其他的split判断方式。

    from translate.convert import txt2po, json2po, html2po
    
    @app.route('/convertfile/<path:filename>')
    def convert_file(filename):
        #给输出的文件设定po拓展名
        filenameOut = os.path.splitext(filename)[0] + '.po'
        #判断拓展名,来进行不同的转换操作
        key = os.path.splitext(filename)[-1][1:]
        if key == 'txt':
            aa = open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'rb+')
            bb = open(os.path.join(app.config['CONVERT_FOLDER'], filenameOut), 'wb+')
            txt2po.run_converter(aa,bb,template_file=None,duplicatestyle='msgctxt',encoding='utf-8',flavour='plain',no_segmentation=False)
            aa.close()
            bb.close()
            return redirect(url_for('manage_file'))
        if key == 'json':
            aa = open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'rb+')
            bb = open(os.path.join(app.config['CONVERT_FOLDER'], filenameOut), 'wb+')
            json2po.convertjson(aa, bb, template_file=None, pot=False, duplicatestyle='msgctxt',dialect='default', filter=None)
            aa.close()
            bb.close()
            return redirect(url_for('manage_file'))
        return redirect(url_for('manage_file'))
    

    Tools里这里实现一个count功能,统计文档的段落数,字符数,翻译完成度等信息。

    ![pocount实现](https://img.haomeiwen.com/i8965651/b1ba742801d5c88d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    

    这里调用的pocount.calcstats_old(),查看源码

    #查看源码
    def calcstats_old(filename):
        ...
        ...
        ...
        sourcewords = lambda elementlist: sum(wordcounts[id(unit)][0] for unit in elementlist)
        targetwords = lambda elementlist: sum(wordcounts[id(unit)][1] for unit in elementlist)
        stats = {}
        ...
        ...
        ...
        # words
        stats["translatedsourcewords"] = sourcewords(translated)
        stats["translatedtargetwords"] = targetwords(translated)
        stats["fuzzysourcewords"] = sourcewords(fuzzy)
        stats["untranslatedsourcewords"] = sourcewords(untranslated)
        stats["reviewsourcewords"] = sourcewords(review)
        stats["totalsourcewords"] = (stats["translatedsourcewords"] +
                                     stats["fuzzysourcewords"] +
                                     stats["untranslatedsourcewords"])
        return stats
    

    所以我们直接调用,然后返回给前端一个字典

    from translate.tools import pocount
    #统计功能
    @app.route('/count/<path:filename>')
    def count_file(filename):
        countfilename = os.path.join(app.config['CONVERT_FOLDER'],filename)
        state = pocount.calcstats_old(countfilename)
        return render_template("countinfo.html", state=state, filename=filename)
    

    前端拿到字典,提取出来需要的数据就好了

    <h2>PO文件内容统计信息</h2>
        <table border = 1>
                <tr>
                    <th>{{filename}}</th>
                    <th> Strings </th>
                    <th>Words (source)</th>
                    <th>Words (translation)</th>
                </tr>
            <tr>
                <td>Translated:  </td>
                <td> {{state["translated"]}}( {{state["translatedsourcewords"] * 100 / state["total"]}}%)</td>
                        <td>{{state["translatedsourcewords"]}}( {{state["translatedsourcewords"] * 100 / state["totalsourcewords"]}}%)</td>
                        <td>{{state["translatedtargetwords"]}}</td>
            </tr>
            <tr>
                <td>Fuzzy:</td>
                <td>{{state["fuzzy"]}}( {{state["fuzzy"] * 100 / state["total"]}}%)</td>
                        <td> {{ state["fuzzysourcewords"] }}( {{state["fuzzy"] * 100 / state["totalsourcewords"]}}%) </td>
                <td>n/a</td>
            </tr>
        ...
        ...
        ...
        </table>
    

    2. 这里再PYCharm调试启动,对了整体项目上传到了我的github https://github.com/finch-xu/f-tt

    这里需要注意项目暂时只写了上传utf8文件的实现,如果项目中上传gbk等其他编码文件就会遇到报错。如果有中文,请将文件转换为utf8的中文。(notepad++点一下即可转换,自行百度)

    #Windows10下调试,注入环境变量
    #这里用hello.py这个文件作为app启动文件
    set FLASK_APP=hello.py
    #设置debug网页显示
    set FLASK_DEBUG=1
    #启动
    Flask run
    

    这时候打开浏览器就会发现web了

    3. 部署到生产环境

    使用Nginx监听uWSGI来运行python web app。首先编写uwsgi.ini配置文件。把项目上传到ubuntu安装uwsgi和nginx后,这里要注意,如果ubuntu里同时有python2.7和python3,那么配置文件里要写成成python3,如果只有python3,那么默认写成python就好了,毕竟项目是Python3.7写的。

    这里设置本地622端口供nginx监听使用

    [uwsgi]
    socket = 127.0.0.1:622
    chdir = /home/ubuntu/f-tt/flaskr/
    wsgi-file = /home/ubuntu/f-tt/flaskr/hello.py
    callable = app
    processes = 1
    threads = 1
    logto = /home/ubuntu/uwsgilogs/%n.log
    #这里我的服务器上有python2和3,所以这里要写python3,如果你只有一个,那么就不需要写3或者2
    plugins = python3
    

    修改nginx配置文件

    sudo vim /etc/nginx/sites-available/default
    
    server {
        listen 5000;
    
        root /var/www/html;
    
        server_name ip或者你的域名;
    
        location / {
            include /etc/nginx/uwsgi_params;
            uwsgi_pass 127.0.0.1:622;
        }
    
    

    启动项目,如果遇到500系列报错,可以查看如下目录下的log,一般会提示权限不足(sudo解决之)或者重复启动之类的,或者Python项目本身的一些报错,总之log写的很清楚

    sudo uwsgi /home/ubuntu/f-tt/flaskr/uwsgi.ini -d /home/ubuntu/f-tt/flaskr/logs/log.log
    

    其他的文件上传下载和其他的功能参考我的GitHub内容即可。

    大功告成!

    本文原文在我的开源中国博客:https://my.oschina.net/finchxu/blog/3217430

    相关文章

      网友评论

        本文标题:利用Translate ToolKit 2.5.0 API构建F

        本文链接:https://www.haomeiwen.com/subject/iiexphtx.html