Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 141 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,144 @@
/venv/
.idea
db.sqlite3


### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

6 changes: 3 additions & 3 deletions EasyTrans/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'trans'
'trans.apps.TransConfig'
]

MIDDLEWARE = [
Expand Down Expand Up @@ -120,6 +120,6 @@

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ]
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ]
6 changes: 3 additions & 3 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
<head>
<meta charset="utf-8" http-equiv="Access-Control-Allow-Origin">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>EasyTrans</title>
<title>QuickTrans</title>
<link rel="shortcut icon" type="image/x-icon" href="{% static 'images/title.ico' %}"/>
<link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<div class="layui-logo" style="font-size: xx-large;font-family: Arial;">EasyTrans</div>
<div class="layui-logo" style="font-size: xx-large;font-family: Arial;">QuickTrans</div>
<!-- 头部区域(可配合layui已有的水平导航) -->
<ul class="layui-nav layui-layout-left">
<li class="layui-nav-item"><a href="#">本站公告</a></li>
Expand Down Expand Up @@ -222,7 +222,7 @@
layui.use(['layer', 'form'], function () {
var layer = layui.layer
, form = layui.form;
layer.msg('Welcome to EasyTrans!');//进入主页面的显示
layer.msg('Welcome to QuickTrans!');//进入主页面的显示
});
//上传文件到后台,包括上传成功后的预览,翻译,删除,翻译完成后可以进行查看以及下载。
var demoListView = $('#test-upload-demoList');
Expand Down
4 changes: 4 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"] # python3
#return ["Hello World"] # python2
Binary file added trans/media/1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file removed trans/output_file/translated_test1.docx
Binary file not shown.
76 changes: 35 additions & 41 deletions trans/translate_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@
import urllib.request
import urllib.parse
import json
import requests # pip intasll requests
import requests # pip intasll requests
import execjs # 安装指令:pip install PyExecJS
import random
import hashlib

from googletrans import Translator


class Py4Js():
Expand Down Expand Up @@ -66,94 +67,87 @@ def __init__(self):
return a
}
""")

def getTk(self, text):
return self.ctx.call("TL", text)


# 有道翻译方法,不支持一次翻译一大段文字
def youdao_translate(content):
'''实现有道翻译的接口'''
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom=https://www.baidu.com/link'
data = {
'from':'AUTO',
'to':'AUTO',
'smartresult':'dict',
'client':'fanyideskweb',
'salt':'1500092479607',
'sign':'d9f9a3aa0a7b34241b3fe30505e5d436',
'doctype':'json',
'version':'2.1',
'keyfrom':'fanyi.web',
'action':'FY_BY_CL1CKBUTTON',
'typoResult':'true'}
data['i'] = content.replace('\n','')
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '1500092479607',
'sign': 'd9f9a3aa0a7b34241b3fe30505e5d436',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CL1CKBUTTON',
'typoResult': 'true'}
data['i'] = content.replace('\n', '')
data = urllib.parse.urlencode(data).encode('utf-8')
wy = urllib.request.urlopen(url,data)
wy = urllib.request.urlopen(url, data)
html = wy.read().decode('utf-8')
ta = json.loads(html)
res = ta['translateResult'][0][0]['tgt']
return res


# 谷歌翻译方法
def google_translate(content):
'''实现谷歌的翻译'''

content = content.replace('\n','')
print(content)
js = Py4Js()
tk = js.getTk(content)
if len(content) > 4891:
return '输入请不要超过4891个字符!'
param = {'tk': tk, 'q': content}
result = requests.get("""http://translate.google.cn/translate_a/single?client=t&sl=en
&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss
&dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1&srcrom=0&ssel=0&tsel=0&kc=2""", params=param)
#返回的结果为Json,解析为一个嵌套列表
trans = result.json()[0]
res = ''
for i in range(len(trans)):
line = trans[i][0]
if line != None:
res += trans[i][0]
content = content.replace('\n', '')
trans = Translator(service_urls=["translate.google.cn"])
res = trans.translate(content, dest='zh-cn').text

return res


def is_Chinese(content): #判断输入的内容是否是中文
def is_Chinese(content): # 判断输入的内容是否是中文
for ch in content:
if '\u4e00' <= ch <= '\u9fff':
return True
else:
return False


# 必应翻译方法已废弃
def bing_translate(content): # 尽量保证翻译内容既有中文也有英文的情况,判断没考虑此情况。
def bing_translate(content): # 尽量保证翻译内容既有中文也有英文的情况,判断没考虑此情况。
if len(content) > 4891:
return '输入请不要超过4891个字符!'
url = 'https://www.bing.com/ttranslatev3?isVertical=1&&IG=0AF741D4794D421EB417BC51A62B9934&IID=translator.5026.4'
if is_Chinese(content):
res = requests.post(url, data={'text':content.replace('\n',''), 'from': 'zh-CHS', 'to': "en", 'doctype': 'json'}).json()['translationResponse']
res = requests.post(url, data={'text': content.replace('\n', ''), 'from': 'zh-CHS', 'to': "en",
'doctype': 'json'}).json()['translationResponse']
else:
res = requests.post(url, data={'text':content.replace('\n',''), 'from': 'en', 'to': "zh-CHS", 'doctype': 'json'}).json()['translationResponse']
res = requests.post(url, data={'text': content.replace('\n', ''), 'from': 'en', 'to': "zh-CHS",
'doctype': 'json'}).json()['translationResponse']
return res


# 百度翻译方法
def baidu_translate(content):
print(content)
if len(content) > 4891:
return '输入请不要超过4891个字符!'
salt = str(random.randint(0, 50))
# 申请网站 http://api.fanyi.baidu.com/api/trans
appid = '20191210000364718' # 这里写你自己申请的
secretKey = 'e83BXpQFTnXrTy62O9MO'# 这里写你自己申请的
sign = appid + content + salt + secretKey
appid = '20200826000551910' # 这里写你自己申请的
secretKey = 'J7yIrmp6HSJ8qiHCzkY7' # 这里写你自己申请的
sign = appid + content + salt + 'medicine' + secretKey
sign = hashlib.md5(sign.encode(encoding='UTF-8')).hexdigest()
head = {'q': f'{content}',
'from': 'en',
'to': 'zh',
'appid': f'{appid }',
'domain': 'medicine',
'appid': f'{appid}',
'salt': f'{salt}',
'sign': f'{sign}'}
j = requests.get('http://api.fanyi.baidu.com/api/trans/vip/translate', head)
j = requests.get('http://api.fanyi.baidu.com/api/trans/vip/fieldtranslate', head)
print(j.json())
res = j.json()['trans_result'][0]['dst']
print(res)
Expand Down
17 changes: 17 additions & 0 deletions uwsgi_params
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;

uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REQUEST_SCHEME $scheme;
uwsgi_param HTTPS $https if_not_empty;

uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;