API HACK
API hack for week 6
from urllib.parse import quote as url_encode
import requests
API_KEY = "2fca282dccmshc5e25cf9e56b999p12a8d0jsnb430f003e7e3"
NOT_PROVIDED = ""
class ApiError(Exception):
pass
class NotConfidentError(ApiError):
pass
class TranslateNotProvidedError(ApiError):
pass
class ExceedsMonthlyUsage(ApiError):
pass
class MatiTranslator:
def __init__(self, API_KEY):
self.headers = {
"content-type": "application/x-www-form-urlencoded",
"X-RapidAPI-Key": API_KEY,
"X-RapidAPI-Host": "google-translate1.p.rapidapi.com"
}
def make_request(self, method, *args, **kwargs):
r = requests.request(method, *args, **kwargs)
# code for exceeding month usage
if r.status_code == 429:
raise ExceedsMonthlyUsage(f"Response: {r.text}")
# print(r.status_code)
# print(r.text)
return r
def detect_language(self, text):
url = "https://google-translate1.p.rapidapi.com/language/translate/v2/detect"
payload = {
"q": url_encode(text),
}
r = self.make_request("POST", url, data=payload, headers=self.headers).json()
data = r["data"]["detections"][0][0]
return (data["language"], data["confidence"])
def translate(self, text, language="", to=""):
if to is NOT_PROVIDED:
raise TranslateNotProvidedError("add a language that that you want to translate to")
if language is NOT_PROVIDED:
language, confidence = self.detect_language(text)
if confidence < 0.5:
raise NotConfidentError(f"{confidence*100=}%")
url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
payload = {
"source": language,
"q": text,
"target": to,
}
r = self.make_request("POST", url, data=payload, headers=self.headers).json()
return r["data"]["translations"][0]["translatedText"]
if __name__ == "__main__":
int1 = input("Enter the language you want to translate. >>")
int2 = input("Enter the language you want to translate to. >>")
text = input("Enter your text. >>")
translator = MatiTranslator(API_KEY)
print("Translated from: ",int1)
print("Translated to: ",int2)
print("---")
print("Input: ",text)
print(
"Translation: ",
translator.translate(text, language=int1, to=int2)
)