1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
|
####################################################################
# BingTranslator.awk #
####################################################################
#
# Last Updated: 18 May 2016
BEGIN { provides("bing") }
function bingInit() {
HttpProtocol = "http://"
HttpHost = "www.bing.com"
HttpPort = 80
}
# Retrieve the Cookie needed.
function bingSetCookie( cookie, group, header, url) {
url = HttpPathPrefix "/translator"
header = "GET " url " HTTP/1.1\n" \
"Host: " HttpHost "\n" \
"Connection: close\n"
if (Option["user-agent"])
header = header "User-Agent: " Option["user-agent"] "\n"
cookie = NULLSTR
print header |& HttpService
while ((HttpService |& getline) > 0 && length($0) > 1) {
match($0, /Set-Cookie: ([^;]*);/, group)
if (group[1]) {
cookie = cookie (cookie ? "; " : NULLSTR) group[1]
}
l(sprintf("%4s bytes > %s", length($0), length($0) < 1024 ? $0 : "..."))
}
close(HttpService)
Cookie = cookie
}
function bingTTSUrl(text, tl,
####
country, gender, group,
header, content, isBody, tempfile) {
gender = "female"
country = NULLSTR
split(Option["narrator"], group, ",")
for (i in group) {
if (group[i] ~ /^(f(emale)?|w(oman)?)$/)
gender = "female"
else if (group[i] ~ /^m(ale|an)?$/)
gender = "male"
else
country = group[i]
}
# Automatic ISO country code
if (country) tl = tl "-" country
else if (tl == "ar") tl = tl "-EG" # FIXME: sometimes doesn't work. Why?
else if (tl == "da") tl = tl "-DK"
else if (tl == "de") tl = tl "-DE"
else if (tl == "en") tl = tl "-US"
else if (tl == "es") tl = tl "-ES"
else if (tl == "fi") tl = tl "-FI"
else if (tl == "fr") tl = tl "-FR"
else if (tl == "it") tl = tl "-IT"
else if (tl == "ja") tl = tl "-JP"
else if (tl == "ko") tl = tl "-KR"
else if (tl == "nl") tl = tl "-NL"
else if (tl == "nb") tl = tl "-NO" # Norwegian Bokmål
else if (tl == "pl") tl = tl "-PL"
else if (tl == "pt") tl = tl "-PT"
else if (tl == "ru") tl = tl "-RU"
else if (tl == "sv") tl = tl "-SE"
else if (tl == "yue") ;
else if (tl == "zh") tl = tl "-CN"
header = "GET " "/translator/api/language/Speak?" \
"locale=" tl "&text=" preprocess(text) \
"&gender=" gender "&media=audio/mp3" " HTTP/1.1\n" \
"Host: " HttpHost "\n" \
"Connection: close\n"
if (Option["user-agent"])
header = header "User-Agent: " Option["user-agent"] "\n"
if (Cookie)
header = header "Cookie: " Cookie "\n" # must!
content = NULLSTR; isBody = 0
print header |& HttpService
while ((HttpService |& getline) > 0) {
if (isBody)
content = content ? content "\n" $0 : $0
else if (length($0) <= 1)
isBody = 1
#l(sprintf("%4s bytes > %s", length($0), $0))
}
close(HttpService)
tempfile = getOutput("mktemp")
printf("%s", content) > tempfile
return tempfile
}
function bingWebTranslateUrl(uri, sl, tl, hl) {
return "http://www.microsofttranslator.com/bv.aspx?" \
"from=" sl "&to=" tl "&a=" uri
}
# Send an HTTP POST request and get response from Bing Translator.
function bingPost(text, sl, tl, hl,
####
content, contentLength, group,
header, isBody, reqBody, url) {
reqBody = "[{" parameterize("text") ":" parameterize(text, "\"") "}]"
contentLength = dump(reqBody, group)
url = HttpPathPrefix "/translator/api/Translate/TranslateArray?" \
"from=" sl "&to=" tl
header = "POST " url " HTTP/1.1\n" \
"Host: " HttpHost "\n" \
"Connection: close\n" \
"Content-Length: " contentLength "\n" \
"Content-Type: application/json\n" # must!
if (Option["user-agent"])
header = header "User-Agent: " Option["user-agent"] "\n"
if (Cookie)
header = header "Cookie: " Cookie "\n" # must!
content = NULLSTR; isBody = 0
print (header "\n" reqBody) |& HttpService
while ((HttpService |& getline) > 0) {
if (isBody)
content = content ? content "\n" $0 : $0
else if (length($0) <= 1)
isBody = 1
l(sprintf("%4s bytes > %s", length($0), $0))
}
close(HttpService)
return assert(content, "[ERROR] Null response.")
}
# Dictionary API (via HTTP GET).
function bingRequestUrl(text, sl, tl, hl) {
return HttpPathPrefix "/translator/api/Dictionary/Lookup?" \
"from=" sl "&to=" tl "&text=" preprocess(text)
}
# Get the translation of a string.
function bingTranslate(text, sl, tl, hl,
isVerbose, toSpeech, returnPlaylist, returnIl,
####
r,
content, tokens, ast,
_sl, _tl, _hl, il,
translation,
wShowOriginal, wShowTranslation, wShowLanguages,
group, temp) {
if (!getCode(tl)) {
# Check if target language is supported
w("[WARNING] Unknown target language code: " tl)
} else if (isRTL(tl)) {
# Check if target language is R-to-L
if (!FriBidi)
w("[WARNING] " getName(tl) " is a right-to-left language, but FriBidi is not found.")
}
_sl = getCode(sl); if (!_sl) _sl = sl
_tl = getCode(tl); if (!_tl) _tl = tl
_hl = getCode(hl); if (!_hl) _hl = hl
# Hot-patches for Bing's own translator language codes
# See: <https://msdn.microsoft.com/en-us/library/hh456380.aspx>
if (_sl == "auto") _sl = "-"
if (_sl == "bs") _sl = "bs-Latn" # 'bs' is not recognized as valid code
if (_sl == "zh-CN") _sl = "zh-CHS"
if (_sl == "zh-TW") _sl = "zh-CHT"
if (_tl == "bs") _tl = "bs-Latn"
if (_tl == "zh-CN") _tl = "zh-CHS"
if (_tl == "zh-TW") _tl = "zh-CHT"
bingSetCookie() # must!
content = bingPost(text, _sl, _tl, _hl)
tokenize(tokens, content)
parseJson(ast, tokens)
l(content, "content", 1, 1)
l(tokens, "tokens", 1, 0, 1)
l(ast, "ast")
if (!isarray(ast) || !anything(ast)) {
e("[ERROR] Oops! Something went wrong and I can't translate it for you :(")
ExitCode = 1
return
} else if (ast[0 SUBSEP "Message"]) {
e("[ERROR] " unparameterize(ast[0 SUBSEP "Message"]))
e("[ERROR] " unparameterize(ast[0 SUBSEP "Details" SUBSEP 0]))
ExitCode = 1
return
}
translation = unparameterize(ast[0 SUBSEP "items" SUBSEP 0 SUBSEP "text"])
returnIl[0] = il = unparameterize(ast[0 SUBSEP "from"])
if (Option["verbose"] < 0)
return getList(il)
# Generate output
if (!isVerbose) {
# Brief mode
r = translation
} else {
# Verbose mode
wShowOriginal = Option["show-original"]
wShowTranslation = Option["show-translation"]
wShowLanguages = Option["show-languages"]
wShowDictionary = Option["show-dictionary"]
if (wShowOriginal) {
# Display: original text
if (r) r = r RS RS
r = r m("-- display original text")
r = r prettify("original", s(text, il))
}
if (wShowTranslation) {
# Display: major translation
if (r) r = r RS RS
r = r m("-- display major translation")
r = r prettify("translation", s(translation, tl))
}
if (wShowLanguages) {
# Display: source language -> target language
if (r) r = r RS RS
r = r m("-- display source language -> target language")
temp = Option["fmt-languages"]
if (!temp) temp = "[ %s -> %t ]"
split(temp, group, /(%s|%S|%t|%T)/)
r = r prettify("languages", group[1])
if (temp ~ /%s/)
r = r prettify("languages-sl", getDisplay(il))
if (temp ~ /%S/)
r = r prettify("languages-sl", getName(il))
r = r prettify("languages", group[2])
if (temp ~ /%t/)
r = r prettify("languages-tl", getDisplay(tl))
if (temp ~ /%T/)
r = r prettify("languages-tl", getName(tl))
r = r prettify("languages", group[3])
}
if (wShowDictionary && false) { # FIXME!
# Dictionary API
# Note: source language must be identified
dicContent = getResponse(text, il, _tl, _hl)
tokenize(dicTokens, dicContent)
parseJson(dicAst, dicTokens) # FIXME: inefficient parser
if (anything(dicAst)) {
# Display: dictionary entries
if (r) r = r RS
r = r m("-- display dictionary entries")
# TODO
}
}
}
if (toSpeech) {
returnPlaylist[0]["text"] = translation
returnPlaylist[0]["tl"] = tl
}
return r
}
|