Merge pull request #41 from pierotofy/detect

Add /detect API
This commit is contained in:
Piero Toffanin 2021-02-10 11:05:48 -05:00 committed by GitHub
commit ce0aced443
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 88 additions and 0 deletions

View file

@ -60,6 +60,9 @@ git clone https://github.com/uav4geo/LibreTranslate
cd LibreTranslate
pip install -e .
libretranslate [args]
# Or
python main.py [args]
```
Then open a web browser to http://localhost:5000

View file

@ -0,0 +1 @@
from .main import main

View file

@ -258,6 +258,86 @@ def create_app(char_limit=-1, req_limit=-1, batch_limit=-1, ga_id=None, debug=Fa
except Exception as e:
abort(500, description="Cannot translate text: %s" % str(e))
@app.route("/detect", methods=['POST'])
def detect():
"""
Detect the language of a single text
---
tags:
- translate
parameters:
- in: formData
name: q
schema:
type: string
example: Hello world!
required: true
description: Text to detect
responses:
200:
description: Detections
schema:
id: detections
type: array
items:
type: object
properties:
confidence:
type: number
format: float
minimum: 0
maximum: 1
description: Confidence value
example: 0.6
language:
type: string
description: Language code
example: en
400:
description: Invalid request
schema:
id: error-response
type: object
properties:
error:
type: string
description: Error message
500:
description: Detection error
schema:
id: error-response
type: object
properties:
error:
type: string
description: Error message
429:
description: Slow down
schema:
id: error-slow-down
type: object
properties:
error:
type: string
description: Reason for slow down
"""
if request.is_json:
json = request.get_json()
q = json.get('q')
else:
q = request.values.get("q")
if not q:
abort(400, description="Invalid request: missing q parameter")
candidate_langs = list(filter(lambda l: l.lang in language_map, detect_langs(q)))
candidate_langs.sort(key=lambda l: l.prob, reverse=True)
return jsonify([{
'confidence': l.prob,
'language': l.lang
} for l in candidate_langs])
@app.route("/frontend/settings")
def frontend_settings():
"""

4
main.py Normal file
View file

@ -0,0 +1,4 @@
from app import main
if __name__ == "__main__":
main()