sn-translator/sn_translator/api.py

35 lines
1.1 KiB
Python
Raw Permalink Normal View History

import urllib
import requests
import brotli
API_URL = "https://libretranslate.com/translate"
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
def translate(text, source, target):
form_data = {
"q": text,
"source": source,
"target": target,
"format": "text",
"api_key": ""
}
referer = f"https://libretranslate.com/?source={source}&target={target}&q={urllib.parse.quote(text)}"
headers = {
# Only ORIGIN header is required to pass authorization.
# To be sure, we also include all other headers
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "de-DE,de;q=0.9,ru-DE;q=0.8,ru;q=0.7,en-US;q=0.6,en;q=0.5",
"origin": "https://libretranslate.com",
"referer": referer,
"user-agent": USER_AGENT
}
r = requests.post(API_URL, data=form_data, headers=headers)
r.raise_for_status()
body = r.json()
translation = body['translatedText']
return translation