Returns the translation of the given string in the desired output language. Google Translate is a paid service, license without billing raises HTTP401Authentication.
(self, string, input="en", output="fr", **kwargs)
| 1069 | return results |
| 1070 | |
| 1071 | def translate(self, string, input="en", output="fr", **kwargs): |
| 1072 | """ Returns the translation of the given string in the desired output language. |
| 1073 | Google Translate is a paid service, license without billing raises HTTP401Authentication. |
| 1074 | """ |
| 1075 | url = URL("https://www.googleapis.com/language/translate/v2?", method=GET, query={ |
| 1076 | "key": self.license or GOOGLE_LICENSE, |
| 1077 | "q": string, # 1000 characters maximum |
| 1078 | "source": input, |
| 1079 | "target": output |
| 1080 | }) |
| 1081 | kwargs.setdefault("cached", False) |
| 1082 | kwargs.setdefault("unicode", True) |
| 1083 | kwargs.setdefault("throttle", self.throttle) |
| 1084 | try: |
| 1085 | data = url.download(**kwargs) |
| 1086 | except HTTP403Forbidden: |
| 1087 | raise HTTP401Authentication, "Google translate API is a paid service" |
| 1088 | data = json.loads(data) |
| 1089 | data = data.get("data", {}).get("translations", [{}])[0].get("translatedText", "") |
| 1090 | data = decode_entities(data) |
| 1091 | return u(data) |
| 1092 | |
| 1093 | def identify(self, string, **kwargs): |
| 1094 | """ Returns a (language, confidence)-tuple for the given string. |