mirror of
https://github.com/LibreTranslate/LibreTranslate.git
synced 2025-05-16 15:03:03 +00:00
Waitress support
This commit is contained in:
parent
7853ec0f0a
commit
094b650be5
4 changed files with 247 additions and 196 deletions
221
app/app.py
Normal file
221
app/app.py
Normal file
|
@ -0,0 +1,221 @@
|
|||
from app.init import boot
|
||||
from flask import Flask, render_template, jsonify, request, abort, send_from_directory
|
||||
from app.language import languages
|
||||
from flask_swagger import swagger
|
||||
from flask_swagger_ui import get_swaggerui_blueprint
|
||||
from flask_limiter.util import get_remote_address
|
||||
|
||||
|
||||
def create_app(char_limit=-1, req_limit=-1, google_analytics=None, debug=False):
|
||||
boot()
|
||||
app = Flask(__name__)
|
||||
|
||||
if debug:
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||
|
||||
if req_limit > 0:
|
||||
from flask_limiter import Limiter
|
||||
limiter = Limiter(
|
||||
app,
|
||||
key_func=get_remote_address,
|
||||
default_limits=["%s per minute" % req_limit]
|
||||
)
|
||||
|
||||
@app.errorhandler(400)
|
||||
def invalid_api(e):
|
||||
return jsonify({"error": str(e.description)}), 400
|
||||
|
||||
@app.errorhandler(500)
|
||||
def server_error(e):
|
||||
return jsonify({"error": str(e.description)}), 500
|
||||
|
||||
@app.errorhandler(429)
|
||||
def slow_down_error(e):
|
||||
return jsonify({"error": "Slowdown: " + str(e.description)}), 429
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template('index.html', gaId=google_analytics)
|
||||
|
||||
@app.route("/languages")
|
||||
def langs():
|
||||
"""
|
||||
Retrieve list of supported languages
|
||||
---
|
||||
tags:
|
||||
- translate
|
||||
responses:
|
||||
200:
|
||||
description: List of languages
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
description: Language code
|
||||
name:
|
||||
type: string
|
||||
description: Human-readable language name (in English)
|
||||
charLimit:
|
||||
type: string
|
||||
description: Character input limit for this language (-1 indicates no limit)
|
||||
429:
|
||||
description: Slow down
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Reason for slow down
|
||||
"""
|
||||
return jsonify([{'code': l.code, 'name': l.name, 'charLimit': char_limit } for l in languages])
|
||||
|
||||
# Add cors
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
response.headers.add('Access-Control-Allow-Origin','*')
|
||||
response.headers.add('Access-Control-Allow-Headers', "Authorization, Content-Type")
|
||||
response.headers.add('Access-Control-Expose-Headers', "Authorization")
|
||||
response.headers.add('Access-Control-Allow-Methods', "GET, POST")
|
||||
response.headers.add('Access-Control-Allow-Credentials', "true")
|
||||
response.headers.add('Access-Control-Max-Age', 60 * 60 * 24 * 20)
|
||||
return response
|
||||
|
||||
|
||||
@app.route("/translate", methods=['POST'])
|
||||
def translate():
|
||||
"""
|
||||
Translate text from a language to another
|
||||
---
|
||||
tags:
|
||||
- translate
|
||||
parameters:
|
||||
- in: formData
|
||||
name: q
|
||||
schema:
|
||||
type: string
|
||||
example: Hello world!
|
||||
required: true
|
||||
description: Text to translate
|
||||
- in: formData
|
||||
name: source
|
||||
schema:
|
||||
type: string
|
||||
example: en
|
||||
required: true
|
||||
description: Source language code
|
||||
- in: formData
|
||||
name: target
|
||||
schema:
|
||||
type: string
|
||||
example: es
|
||||
required: true
|
||||
description: Target language code
|
||||
responses:
|
||||
200:
|
||||
description: Translated text
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
translatedText:
|
||||
type: string
|
||||
description: Translated text
|
||||
400:
|
||||
description: Invalid request
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Error message
|
||||
500:
|
||||
description: Translation error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Error message
|
||||
429:
|
||||
description: Slow down
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Reason for slow down
|
||||
"""
|
||||
|
||||
if request.is_json:
|
||||
json = request.get_json()
|
||||
q = json.get('q')
|
||||
source_lang = json.get('source')
|
||||
target_lang = json.get('target')
|
||||
else:
|
||||
q = request.values.get("q")
|
||||
source_lang = request.values.get("source")
|
||||
target_lang = request.values.get("target")
|
||||
|
||||
if not q:
|
||||
abort(400, description="Invalid request: missing q parameter")
|
||||
if not source_lang:
|
||||
abort(400, description="Invalid request: missing source parameter")
|
||||
if not target_lang:
|
||||
abort(400, description="Invalid request: missing target parameter")
|
||||
|
||||
if char_limit != -1:
|
||||
q = q[:char_limit]
|
||||
|
||||
src_lang = next(iter([l for l in languages if l.code == source_lang]), None)
|
||||
tgt_lang = next(iter([l for l in languages if l.code == target_lang]), None)
|
||||
|
||||
if src_lang is None:
|
||||
abort(400, description="%s is not supported" % source_lang)
|
||||
if tgt_lang is None:
|
||||
abort(400, description="%s is not supported" % target_lang)
|
||||
|
||||
translator = src_lang.get_translation(tgt_lang)
|
||||
try:
|
||||
return jsonify({"translatedText": translator.translate(q) })
|
||||
except Exception as e:
|
||||
abort(500, description="Cannot translate text: %s" % str(e))
|
||||
|
||||
|
||||
swag = swagger(app)
|
||||
swag['info']['version'] = "1.0"
|
||||
swag['info']['title'] = "LibreTranslate"
|
||||
|
||||
@app.route("/spec")
|
||||
def spec():
|
||||
return jsonify(swag)
|
||||
|
||||
SWAGGER_URL = '/docs' # URL for exposing Swagger UI (without trailing '/')
|
||||
API_URL = 'http://petstore.swagger.io/v2/swagger.json' # Our API url (can of course be a local resource)
|
||||
|
||||
# Call factory function to create our blueprint
|
||||
swaggerui_blueprint = get_swaggerui_blueprint(
|
||||
SWAGGER_URL,
|
||||
"",
|
||||
config={ # Swagger UI config overrides
|
||||
'app_name': "LibreTranslate",
|
||||
"spec": swag
|
||||
}
|
||||
)
|
||||
|
||||
app.register_blueprint(swaggerui_blueprint)
|
||||
|
||||
return app
|
405
app/templates/index.html
Normal file
405
app/templates/index.html
Normal file
|
@ -0,0 +1,405 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>LibreTranslate - Free and Open Source Translation API</title>
|
||||
|
||||
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
|
||||
<!-- Compiled and minified CSS -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
|
||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.22.0/themes/prism.min.css" rel="stylesheet" />
|
||||
|
||||
<style type="text/css">
|
||||
textarea.materialize-textarea{height: 120px;}
|
||||
.code{
|
||||
font-size: 90%;
|
||||
border-radius: 4px;
|
||||
padding: 4px;
|
||||
border: 1px solid #9e9e9e;
|
||||
background: #fbfbfb;
|
||||
overflow: auto;
|
||||
font-family: monospace;
|
||||
min-height: 280px;
|
||||
width: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
.progress.translate{
|
||||
position: absolute;
|
||||
}
|
||||
.card.horizontal .card-stacked{
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
{% if gaId %}
|
||||
<!-- Global site tag (gtag.js) - Google Analytics -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id={{ gaId }}"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
|
||||
gtag('config', '{{ gaId }}');
|
||||
</script>
|
||||
{% endif %}
|
||||
</head>
|
||||
<body>
|
||||
<nav class="blue lighten-1" role="navigation">
|
||||
<div class="nav-wrapper container"><a id="logo-container" href="/" class="brand-logo"><i class="material-icons">translate</i> LibreTranslate</a>
|
||||
<ul class="right hide-on-med-and-down">
|
||||
<li><a href="/docs">API Docs</a></li>
|
||||
<li><a href="https://github.com/uav4geo/LibreTranslate">GitHub</a></li>
|
||||
</ul>
|
||||
|
||||
<ul id="nav-mobile" class="sidenav">
|
||||
<li><a href="/docs">API Docs</a></li>
|
||||
<li><a href="https://github.com/uav4geo/LibreTranslate">GitHub</a></li>
|
||||
</ul>
|
||||
<a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>
|
||||
</div>
|
||||
</nav>
|
||||
<div id="app">
|
||||
<div class="section no-pad-bot center" v-if="loading">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="preloader-wrapper active">
|
||||
<div class="spinner-layer spinner-blue-only">
|
||||
<div class="circle-clipper left">
|
||||
<div class="circle"></div>
|
||||
</div><div class="gap-patch">
|
||||
<div class="circle"></div>
|
||||
</div><div class="circle-clipper right">
|
||||
<div class="circle"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="error">
|
||||
<div class="section no-pad-bot">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col s12 m7">
|
||||
<div class="card horizontal">
|
||||
<div class="card-stacked">
|
||||
<div class="card-content">
|
||||
<i class="material-icons">warning</i><p> [[ error ]]</p>
|
||||
</div>
|
||||
<div class="card-action">
|
||||
<a href="#" @click="dismissError">Dismiss</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else>
|
||||
<div class="section no-pad-bot">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<h3 class="header center">Translation API</h3>
|
||||
<div class="card horizontal">
|
||||
<div class="card-stacked">
|
||||
<div class="card-content">
|
||||
<form class="col s12">
|
||||
<div class="row">
|
||||
<div class="input-field col s5">
|
||||
<select class="browser-default" v-model="sourceLang" ref="sourceLangDropdown"@change="handleInput">
|
||||
<template v-for="option in langs">
|
||||
<option :value="option.code">[[ option.name ]]</option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col s2 center">
|
||||
<a href="javascript:void(0)" @click="swapLangs" class="waves-effect waves-teal btn-flat btn-large"><i class="material-icons">swap_horiz</i></a>
|
||||
</div>
|
||||
<div class="input-field col s5">
|
||||
<select class="browser-default" v-model="targetLang" ref="targetLangDropdown" @change="handleInput">
|
||||
<template v-for="option in langs">
|
||||
<option :value="option.code">[[ option.name ]]</option>
|
||||
</template>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="input-field col s6">
|
||||
<textarea id="textarea1" class="materialize-textarea" v-model="inputText" @input="handleInput" ref="inputTextarea"></textarea>
|
||||
<label for="textarea1">Input Text</label>
|
||||
<div v-if="charactersLimit !== -1">
|
||||
<label>[[ inputText.length ]] / [[ charactersLimit ]]</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="input-field col s6">
|
||||
<div>
|
||||
<textarea id="textarea2" class="materialize-textarea" v-model="translatedText" ref="translatedTextarea"></textarea>
|
||||
<label for="textarea2"><div class="progress translate" v-if="loadingTranslation">
|
||||
<div class="indeterminate"></div>
|
||||
</div></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section no-pad-bot" id="index-banner">
|
||||
<div class="container">
|
||||
<div class="row center">
|
||||
<div class="col s12 m12">
|
||||
<div class="card horizontal">
|
||||
<div class="card-stacked">
|
||||
<div class="card-content">
|
||||
<div class="row center">
|
||||
<div class="col s12 m12 l6 left-align">
|
||||
<p>Request</p>
|
||||
<p>
|
||||
<pre class="code"><code class="language-javascript" v-html="$options.filters.highlight(requestCode)">
|
||||
</code></pre></p>
|
||||
</div>
|
||||
<div class="col s12 m12 l6 left-align">
|
||||
<p>Response</p>
|
||||
<pre class="code"><code class="language-javascript" v-html="$options.filters.highlight(output)">
|
||||
</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="page-footer blue darken-3">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col l6 s12">
|
||||
<h5 class="white-text">LibreTranslate</h5>
|
||||
<p class="grey-text text-lighten-4">Free and Open Source Translation API</p>
|
||||
<p class="grey-text text-lighten-4">
|
||||
Made with ❤ by <a class="grey-text text-lighten-3" href="https://uav4geo.com">UAV4GEO</a> and powered by <a class="grey-text text-lighten-3" href="https://github.com/argosopentech/argos-translate/">Argos Translate</a>
|
||||
</p>
|
||||
<p><a class="grey-text text-lighten-4" href="https://www.gnu.org/licenses/agpl-3.0.en.html">License: AGPLv3</a></p>
|
||||
</div>
|
||||
<div class="col l4 offset-l2 s12">
|
||||
<!-- <h5 class="white-text">Links</h5>
|
||||
<ul>
|
||||
<li><a class="grey-text text-lighten-3" href="#!">Link 1</a></li>
|
||||
<li><a class="grey-text text-lighten-3" href="#!">Link 2</a></li>
|
||||
<li><a class="grey-text text-lighten-3" href="#!">Link 3</a></li>
|
||||
<li><a class="grey-text text-lighten-3" href="#!">Link 4</a></li>
|
||||
</ul> -->
|
||||
<div class="container">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-copyright center">
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
|
||||
<script>
|
||||
window.Prism = window.Prism || {};
|
||||
window.Prism.manual = true;
|
||||
</script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.22.0/prism.min.js" ></script>
|
||||
|
||||
<script>
|
||||
// API host/endpoint
|
||||
var BaseUrl = window.location.protocol + "//" + window.location.host;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function(){
|
||||
var elems = document.querySelectorAll('.sidenav');
|
||||
var instances = M.Sidenav.init(elems);
|
||||
|
||||
var app = new Vue({
|
||||
el: '#app',
|
||||
delimiters: ['[[',']]'],
|
||||
data: {
|
||||
BaseUrl: BaseUrl,
|
||||
loading: true,
|
||||
error: "",
|
||||
langs: [],
|
||||
sourceLang: "",
|
||||
targetLang: "",
|
||||
|
||||
loadingTranslation: false,
|
||||
inputText: "",
|
||||
translatedText: "",
|
||||
output: "",
|
||||
charactersLimit: -1,
|
||||
},
|
||||
mounted: function(){
|
||||
var self = this;
|
||||
var request = new XMLHttpRequest();
|
||||
request.open('GET', BaseUrl + '/languages', true);
|
||||
|
||||
request.onload = function() {
|
||||
if (this.status >= 200 && this.status < 400) {
|
||||
// Success!
|
||||
self.langs = JSON.parse(this.response);
|
||||
if (self.langs.length === 0){
|
||||
self.loading = false;
|
||||
self.error = "No languages available. Did you install the models correctly?"
|
||||
return;
|
||||
}
|
||||
|
||||
self.sourceLang = self.langs[0].code;
|
||||
self.targetLang = self.langs[1].code;
|
||||
self.charactersLimit = self.langs[0].charLimit;
|
||||
// TODO: update this when switching languages
|
||||
|
||||
// Set Spanish
|
||||
for (var i = 1; i < self.langs.length; i++){
|
||||
if (self.langs[i].code === "es"){
|
||||
self.targetLang = "es";
|
||||
}
|
||||
}
|
||||
|
||||
self.loading = false;
|
||||
} else {
|
||||
self.error = "Cannot load /languages";
|
||||
self.loading = false;
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = function() {
|
||||
self.error = "Error while calling /languages";
|
||||
self.loading = false;
|
||||
};
|
||||
|
||||
request.send();
|
||||
},
|
||||
updated: function(){
|
||||
M.FormSelect.init(this.$refs.sourceLangDropdown);
|
||||
M.FormSelect.init(this.$refs.targetLangDropdown);
|
||||
if (this.inputText === ""){
|
||||
this.$refs.inputTextarea.style.height = 150 + "px";
|
||||
this.$refs.translatedTextarea.style.height = 150 + "px";
|
||||
}else{
|
||||
this.$refs.inputTextarea.style.height = Math.max(150, this.$refs.inputTextarea.scrollHeight) + "px";
|
||||
this.$refs.translatedTextarea.style.height = Math.max(150, this.$refs.translatedTextarea.scrollHeight) + "px";
|
||||
}
|
||||
|
||||
if (this.charactersLimit !== -1 && this.inputText.length >= this.charactersLimit){
|
||||
this.inputText = this.inputText.substring(0, this.charactersLimit);
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
requestCode: function(){
|
||||
return ['const res = await fetch("' + this.BaseUrl + '/translate", {',
|
||||
' method: "POST",',
|
||||
' body: JSON.stringify({',
|
||||
' q: "' + this.$options.filters.escape(this.inputText) + '",',
|
||||
' source: "' + this.$options.filters.escape(this.sourceLang) + '",',
|
||||
' target: "' + this.$options.filters.escape(this.targetLang) + '"',
|
||||
' }),',
|
||||
' headers: {',
|
||||
' "Content-Type": "application/json"',
|
||||
' });',
|
||||
'',
|
||||
'console.log(await res.json());'].join("\n");
|
||||
}
|
||||
},
|
||||
filters: {
|
||||
escape: function(v){
|
||||
return v.replace('"', '\\\"');
|
||||
},
|
||||
highlight: function(v){
|
||||
return Prism.highlight(v, Prism.languages.javascript, 'javascript');
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
abortPreviousTransRequest: function(){
|
||||
if (this.transRequest){
|
||||
this.transRequest.abort();
|
||||
this.transRequest = null;
|
||||
}
|
||||
},
|
||||
swapLangs: function(){
|
||||
var t = this.sourceLang;
|
||||
this.sourceLang = this.targetLang;
|
||||
this.targetLang = t;
|
||||
this.inputText = this.translatedText;
|
||||
this.translatedText = "";
|
||||
this.handleInput();
|
||||
},
|
||||
dismissError: function(){
|
||||
this.error = '';
|
||||
},
|
||||
handleInput: function(e){
|
||||
if (this.timeout) clearTimeout(this.timeout);
|
||||
this.timeout = null;
|
||||
|
||||
if (this.inputText === ""){
|
||||
this.translatedText = "";
|
||||
this.output = "";
|
||||
this.abortPreviousTransRequest();
|
||||
this.loadingTranslation = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var self = this;
|
||||
|
||||
self.loadingTranslation = true;
|
||||
this.timeout = setTimeout(function(){
|
||||
self.abortPreviousTransRequest();
|
||||
|
||||
var request = new XMLHttpRequest();
|
||||
self.transRequest = request;
|
||||
|
||||
var data = new FormData();
|
||||
data.append("q", self.inputText);
|
||||
data.append("source", self.sourceLang);
|
||||
data.append("target", self.targetLang);
|
||||
|
||||
request.open('POST', BaseUrl + '/translate', true);
|
||||
|
||||
request.onload = function() {
|
||||
try{
|
||||
var res = JSON.parse(this.response);
|
||||
// Success!
|
||||
if (res.translatedText !== undefined){
|
||||
self.translatedText = res.translatedText;
|
||||
self.loadingTranslation = false;
|
||||
self.output = JSON.stringify(res, null, 4);
|
||||
}else{
|
||||
throw new Error(res.error || "Unknown error");
|
||||
}
|
||||
}catch(e){
|
||||
self.error = e.message;
|
||||
self.loadingTranslation = false;
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = function() {
|
||||
self.error = "Error while calling /translate";
|
||||
self.loadingTranslation = false;
|
||||
};
|
||||
|
||||
request.send(data);
|
||||
}, 300);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
Loading…
Add table
Add a link
Reference in a new issue