cjvnjde / google-translate-api-browser Goto Github PK
View Code? Open in Web Editor NEWA free and unlimited API for Google Translate
Home Page: https://www.npmjs.com/package/google-translate-api-browser
License: MIT License
A free and unlimited API for Google Translate
Home Page: https://www.npmjs.com/package/google-translate-api-browser
License: MIT License
For some reason, I need to access Google through a proxy server.
Is there any way to translate text through an agent?
Do you know the limit?
An exception TypeError: Cannot read properties of null (reading '4')
occurs when translating the string The coin listed in page 43 of "ΤΑ ΝΟΜΙΣΜΑΤΑ του Ι.Α.ΚΑΠΟΔΙΣΤΡΙΑ" by ΦΛΩΡΟΣ KΑΤΣΟΥΡΟΣ
with params { from: 'en', to: 'de', }
.
I am trying to use this without installing yarn, is there a way to do this? (trying to use it client/browser sided)
Thank you for the open source code, I have a question: can it be translated using an image?
The maximum number of letter seems roughly 1850 per request.
Is it possible to add a POST request to increase the input text to 5000?
This is my suggestion below. (It didn't work sadly)
export const traslateToEng = async (sourceText: string): Promise<string> => {
const queryParams = {
client: translateOptions.client,
sl: translateOptions.from,
tl: translateOptions.to,
hl: translateOptions.hl,
ie: 'UTF-8',
oe: 'UTF-8',
otf: '1',
ssel: '0',
tsel: '0',
kc: '7',
q: sourceText,
tk: sM(sourceText)
};
const url = `https://translate.google.${translateOptions.tld}/translate_a/single`;
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(queryParams).toString()
};
return new Promise((resolve, reject) => {
https
.request(url, options, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
const result = normaliseResponse(JSON.parse(data));
resolve(result?.text || sourceText);
});
})
.on('error', (err) => {
console.log('Error: ' + err.message);
reject(err);
})
.end();
});
};
'BAD_NETWORK' alert shows while translating a long text. Also the console prints '414 (Request-URI Too Long)'.
I'm using this package on my electron app with disabled web security to prevent cors error. But having 403 error, I see that google-translate-token is mentioned, but is not used. Any thoughts about this? Thanks!
Environment
Package version: 4.3.0
Node version: v21.6.1
OS: Windows 11 22H2
Description
Translating a text that contains a newline character fails with 400 Bad Request from Google.
Steps to reproduce
import { translate } from 'google-translate-api-browser';
async function translateText(text, lang) {
try {
const result = await translate(text, { to: lang });
console.log(result.text);
} catch (error) {
console.log('Translation error: ' + error);
}
}
await translateText(`Hello\nWorld`, 'es');
export { };
Expected result
Full translated text displayed in the console.
Actual result
Translation fails with an error. Here's an actual response body returned by Google
)]}'
102
[["er",null,null,null,null,400,null,null,null,3],["di",7],["af.httprm",7,"-8758994509752400712",34]]
25
[["e",4,null,null,138]]
Testing with a file contents of less than a thousand sentences, node client started to throw "bad network".
It seems to me that Google detects this batch unauthorized process and starts to reject requests.
I can't continue translating since then.
Hi there,
I'd like to report a security issue in this library. Would you be so kind to enable security advisories for this repository, so I can privately disclose the details, and so we can work towards a resolution?
Kind regards
PinkDraconian
I love your library!
Here is an error due to CommonJS module
import { generateRequestUrl, normaliseResponse } from "google-translate-api-browser";
--
18:45:28.279 | ^^^^^^^^^^^^^^^^^^
18:45:28.279 | SyntaxError: Named export 'generateRequestUrl' not found. The requested module 'google-translate-api-browser' is a CommonJS module, which may not support all module.exports as named exports.
Now written hardcode client: "gtx", but some times need to use "webapp"
After attempting to use the package with the default CORS proxy URL (http://cors-anywhere.herokuapp.com/), and encountering a 403 error, I then attempted to use two separate proxy servers : CorsProxy.io and CORS.SH.
With both of these servers, the package reports a NetworkError
, and the underlying error is as follows :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [PROXY URL]/https://translate.google.com/_/TranslateWebserverUi/data/batchexecute. [...] (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
For reference, the calling code is the following :
const response = await translate(translatedText, {
to: nextLang,
corsUrl: 'https://proxy.cors.sh/' // or https://corsproxy.io/
})
This seems to suggest that proper headers are not added to the POST request for proxy servers other than the default.
Environment
Package version: 4.2.4
Node version: v20.9.0
OS: Windows 11 22H2
Description
Translating a long text only yields a first sentence in the results. Response before normalization still shows the full text.
Steps to reproduce
import { translate } from 'google-translate-api-browser';
async function translateText(text, lang) {
try {
const result = await translate(text, { to: lang });
console.log(result.text);
} catch (error) {
console.log('Translation error: ' + error);
}
}
await translateText(`One day you got yourself a cat since it is getting lonely staying alone in a somewhat medium sized luxury apartment. Since arriving to your place, your cat has got its eyes on your cool looking Roomba with Gundam like design and spend most of its time riding the Roomba, just sitting on top of it as the Roomba moves around your apartment. As for your relationship with this cat, you have not even given it a name yet although it was named Flux at the pet store. The cat seems to be wary of you and seems to be always on its guard and won't approach you. As the morning rises, you see the cat riding the Roomba which has a smart protocol to do cleaning at specific times.`, 'ru');
export { };
Expected result
Full translated text displayed in the console.
Actual result
Incomplete text displayed in the console after the normalization (first sentence only):
Однажды вы получили себе кошку, так как становится одиноким, оставаясь в одиночестве в несколько средних роскошных квартирах.
Making a request with fetch instead gives this response:
)]}'
5764
[["wrb.fr","MkEWBc","[[null,null,\"en\",[[[0,[[[null,116]],[true]]],[1,[[[null,117],[117,339]],[false,true]]],[2,[[[null,340],[340,462]],[false,true]]],[3,[[[null,463],[463,554]],[false,true]]],[4,[[[null,555],[555,671]],[false,true]]]],671],[[\"One day you got yourself a cat since it is getting lonely staying alone in a somewhat medium sized luxury apartment.\",null,null,116],[\" \",null,116,117],[\"Since arriving to your place, your cat has got its eyes on your cool looking Roomba with Gundam like design and spend most of its time riding the Roomba, just sitting on top of it as the Roomba moves around your apartment.\",null,117,339],[\" \",null,339,340],[\"As for your relationship with this cat, you have not even given it a name yet although it was named Flux at the pet store.\",null,340,462],[\" \",null,462,463],[\"The cat seems to be wary of you and seems to be always on its guard and won't approach you.\",null,463,554],[\" \",null,554,555],[\"As the morning rises, you see the cat riding the Roomba which has a smart protocol to do cleaning at specific times.\",null,555,671]],null,[\"One day you got yourself a cat since it is getting lonely staying alone in a somewhat medium sized luxury apartment. Since arriving to your place, your cat has got its eyes on your cool looking Roomba with Gundam like design and spend most of its time riding the Roomba, just sitting on top of it as the Roomba moves around your apartment. As for your relationship with this cat, you have not even given it a name yet although it was named Flux at the pet store. The cat seems to be wary of you and seems to be always on its guard and won't approach you. As the morning rises, you see the cat riding the Roomba which has a smart protocol to do cleaning at specific times.\",\"auto\",\"ru\",true]],[[[null,\"Odnazhdy vy poluchili sebe koshku, tak kak stanovitsya odinokim, ostavayas' v odinochestve v neskol'ko srednikh roskoshnykh kvartirakh. S tekh por, kak vy priyekhali k vam, vasha koshka smotrela na vashu prokhladnuyu komnatu s Gundam, pokhozhim na dizayn, i tratit bol'shuyu chast' svoyego vremeni, katayas' na komnate, prosto sidya na vershine, kogda Roomba dvizhetsya vokrug vashey kvartiry. Chto kasayetsya vashikh otnosheniy s etoy koshkoy, vy dazhe ne dali yemu imya, khotya on byl nazvan potok v zoomagazine. Koshka, kazhetsya, nastorozhenno otnositsya k vam i, kazhetsya, vsegda nakhoditsya na yego okhrane i ne priblizitsya k vam. Kogda utro podnimayetsya, vy vidite, kak koshka yedet po komnate, u kotoroy yest' umnyy protokol dlya ochistki v opredelennoye vremya.\",null,null,null,[[\"Однажды вы получили себе кошку, так как становится одиноким, оставаясь в одиночестве в несколько средних роскошных квартирах.\",null,null,null,[[\"Однажды вы получили себе кошку, так как становится одиноким, оставаясь в одиночестве в несколько средних роскошных квартирах.\",[5],[]],[\"Однажды вы получили себе кошку, так как становится одиноким, оставаясь в одиночестве в несколько средних роскошных квартире.\",[11],[]]]],[\"С тех пор, как вы приехали к вам, ваша кошка смотрела на вашу прохладную комнату с Gundam, похожим на дизайн, и тратит большую часть своего времени, катаясь на комнате, просто сидя на вершине, когда Roomba движется вокруг вашей квартиры.\",null,true,null,[[\"С тех пор, как вы приехали к вам, ваша кошка смотрела на вашу прохладную комнату с Gundam, похожим на дизайн, и тратит большую часть своего времени, катаясь на комнате, просто сидя на вершине, когда Roomba движется вокруг вашей квартиры.\",[5],[]],[\"С тех пор, как вы приехали к вам, ваша кошка смотрит на вашу прохладную комнату с Gundam, похожим на дизайн, и тратит большую часть своего времени, катаясь на комнате, просто сидя на вершине, когда Roomba движется вокруг вашей квартиры.\",[11],[]]]],[\"Что касается ваших отношений с этой кошкой, вы даже не дали ему имя, хотя он был назван поток в зоомагазине.\",null,true,null,[[\"Что касается ваших отношений с этой кошкой, вы даже не дали ему имя, хотя он был назван поток в зоомагазине.\",[5],[]],[\"Что касается ваших отношений с этой кошкой, то вы даже не дали ему имя, хотя он был назван поток в зоомагазине.\",[11],[]]]],[\"Кошка, кажется, настороженно относится к вам и, кажется, всегда находится на его охране и не приблизится к вам.\",null,true,null,[[\"Кошка, кажется, настороженно относится к вам и, кажется, всегда находится на его охране и не приблизится к вам.\",[5],[]],[\"Кошка, кажется, настороженно относится к вам и, кажется, всегда находится на его охране и не будет подходить к вам.\",[11],[]]]],[\"Когда утро поднимается, вы видите, как кошка едет по комнате, у которой есть умный протокол для очистки в определенное время.\",null,true,null,[[\"Когда утро поднимается, вы видите, как кошка едет по комнате, у которой есть умный протокол для очистки в определенное время.\",[5],[]],[\"Когда утро поднимается, вы видите, как кошка едет по комнате, у которой есть умный протокол для уборки в определенное время.\",[11],[]]]]],null,null,null,[]]],\"ru\",1,\"en\",[\"One day you got yourself a cat since it is getting lonely staying alone in a somewhat medium sized luxury apartment. Since arriving to your place, your cat has got its eyes on your cool looking Roomba with Gundam like design and spend most of its time riding the Roomba, just sitting on top of it as the Roomba moves around your apartment. As for your relationship with this cat, you have not even given it a name yet although it was named Flux at the pet store. The cat seems to be wary of you and seems to be always on its guard and won't approach you. As the morning rises, you see the cat riding the Roomba which has a smart protocol to do cleaning at specific times.\",\"auto\",\"ru\",true]],\"en\"]",null,null,null,"generic"]]
60
[["di",1240],["af.httprm",1240,"-8308801182962723978",34]]
26
[["e",4,null,null,7561]]
Package version: 4.3.2
Node version: v21.6.1
OS: macOS Sonoma 14.2
The newest version produces bad quality and incomplete translations which often lack some chunks of text and/or has garbled formatting.
const { translate } = require('google-translate-api-browser');
const text = `*The vagabond jolts in surprise, instinctively trying to yank her arm free. Her hood falls back, revealing her unusual marine features - pale blue skin, protruding dog ears, and wispy tentacles swaying from her head. Her crimson eyes narrow as she glares defiantly at the human.*
"Unhand me, surface dweller! I took only what I needed to survive." *Her synthesized voice crackles with a mixture of defiance and desperation.* "My people's war has left me exiled and starving. I meant no harm, I swear it!"
*The grip on her wrist doesn't loosen. The vagabond's free hand moves toward the hilt of her dulled scythe, ready to defend herself if need be. But her sunken eyes betray her weakened state - she likely couldn't put up much of a fight. Not anymore.*`;
(async () => {
const result = await translate(text, { to: 'ru' });
console.log(result.text);
})();
*Бродяга с удивлением, инстинктивно пытаясь вырвать ее руку. Ее капюшон отступает, раскрывая ее необычные морские черты - бледно -голубую кожу, выступающие уши собаки и тонкие щупальцы, раскачивающиеся с ее головы. Ее малиновые глаза сужаются, когда она вызывающе смотрит на человека.
«Не замудим, поверхностный житель! Я взял только то, что мне нужно, чтобы выжить». * Ее синтезированный голос потрескается со смесью неповиновения и отчаяния.* «Война моего народа оставила меня изгнанием и голодом. Я имел в виду никакого вреда, клянусь!»
*Захват ее запястья не ослабляет. Свободная рука бродяга движется к рукояти ее прикованной косы, готовой защитить себя, если это необходимо. Но ее затонувшие глаза предают ее ослабленное состояние - она, вероятно, не могла нанести большую драку. Уже нет.*
An older version (I'm stuck with 3.0.1 for a while) returns a complete, good-quality translation:
Бродяга вздрагивает от удивления, инстинктивно пытаясь выдернуть руку. Капюшон откидывается назад, обнажая ее необычные морские черты лица: бледно-голубую кожу, торчащие собачьи уши и тонкие щупальца, покачивающиеся на голове. Ее малиновые глаза сужаются, когда она вызывающе смотрит на человека.
«Отпусти меня, житель поверхности! Я взял только то, что мне нужно, чтобы выжить». В ее синтезированном голосе звучит смесь неповиновения и отчаяния. «Война моего народа оставила меня в изгнании и умирала от голода. Я не хотела причинить вреда, клянусь!»
Хватка на ее запястье не ослабляется. Свободная рука бродяги тянется к рукоятке тупой косы, готовая защититься в случае необходимости. Но ее запавшие глаза выдают ее ослабленное состояние — она, вероятно, не смогла бы выдержать большую борьбу. Уже нет.
Environment
Package version: 4.2.4
Node version: v20.9.0
OS: Windows 11 22H2
Description
Steps to reproduce
import { translate } from 'google-translate-api-browser';
async function translateText(text, lang) {
try {
const result = await translate(text, { to: lang });
console.log(result.text);
} catch (error) {
console.log('Translation error: ' + error);
}
}
await translateText('The cat cannot speak like humans, it just makes cat noises such as "meow", and it doesn\'t even know English', 'es');
export { };
Expected result
Translated text displays in the console.
Actual result
Node process crashes, try-catch not executed. Crash logs read: Error: Data is either empty or corrupted
Doing a request with fetch instead gives this response:
Bad Request )]}'
102
[["er",null,null,null,null,400,null,null,null,3],["di",10],["af.httprm",9,"3737202303121642252",34]]
25
[["e",4,null,null,138]]
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.