Git Product home page Git Product logo

google-translate's Introduction

Google Translate API

A Node.JS library to consume Google Translate for free.

GitHub release Dependencies Known Vulnerabilities license

Feature Highlights

  • Automatically detect source language
  • Automatic spelling corrections
  • Automatic language correction
  • Fast and reliable

Table of Contents

Installation

# Stable version, from npm repository
npm install --save @iamtraction/google-translate

# Latest version, from GitHub repository
npm install --save iamtraction/google-translate

Usage

// If you've installed from npm, do:
const translate = require('@iamtraction/google-translate');

// If you've installed from GitHub, do:
const translate = require('google-translate');

Method: translate(text, options)

translate(text, options).then(console.log).catch(console.error);
Parameter Type Optional Default Description
text String No - The text you want to translate.
options Object - - The options for translating.
options.from String Yes 'auto' The language name/ISO 639-1 code to translate from. If none is given, it will auto detect the source language.
options.to String Yes 'en' The language name/ISO 639-1 code to translate to. If none is given, it will translate to English.
options.raw Boolean Yes false If true, it will return the raw output that was received from Google Translate.

Returns: Promise<Object>

Response Object:

Key Type Description
text String The translated text.
from Object -
from.language Object -
from.language.didYouMean Boolean Whether or not the API suggest a correction in the source language.
from.language.iso String The ISO 639-1 code of the language that the API has recognized in the text.
from.text Object -
from.text.autoCorrected Boolean Whether or not the API has auto corrected the original text.
from.text.value String The auto corrected text or the text with suggested corrections. Only returned if from.text.autoCorrected or from.text.didYouMean is true.
from.text.didYouMean Boolean Wherether or not the API has suggested corrections to the text
raw String The raw response from Google Translate servers. Only returned if options.raw is true in the request options.

Examples

From automatic language detection to English:

translate('Tu es incroyable!', { to: 'en' }).then(res => {
  console.log(res.text); // OUTPUT: You are amazing!
}).catch(err => {
  console.error(err);
});

From English to French, with a typo:

translate('Thank you', { from: 'en', to: 'fr' }).then(res => {
  console.log(res.text); // OUTPUT: Je vous remercie
  console.log(res.from.autoCorrected); // OUTPUT: true
  console.log(res.from.text.value); // OUTPUT: [Thank] you
  console.log(res.from.text.didYouMean); // OUTPUT: false
}).catch(err => {
  console.error(err);
});

Sometimes Google Translate won't auto correct:

translate('Thank you', { from: 'en', to: 'fr' }).then(res => {
  console.log(res.text); // OUTPUT: ''
  console.log(res.from.autoCorrected); // OUTPUT: false
  console.log(res.from.text.value); // OUTPUT: [Thank] you
  console.log(res.from.text.didYouMean); // OUTPUT: true
}).catch(err => {
  console.error(err);
});

Extras

If you liked this project, please give it a ⭐ in GitHub.

Credits to matheuss for writing the original version of this library. I rewrote this, with improvements and without using many external libraries, as his library was not actively developed and had vulnerabilities.

google-translate's People

Contributors

adizbek avatar androz2091 avatar iamtraction avatar jqlu avatar tomsun28 avatar zeriodev avatar zubb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-translate's Issues

TKK generated

Hey.

Did you manage to figure out how TKK is generated?

var code = res.body.match(/TKK='.*?';/g);

TKK= not found in HTML https://translate.google.com

tkk

Where does TKK come from?

Maybe this: tkk:'434303.3040823967'

Dialogflow

hey
i am working on dialogflow and i am not be able to connect the API to dialogflow. i am working on inline editor. is there a way to use your API in inline editor?
best regards

error 429 after few testing

I am getting this error after doing a few tests

{ name : HTTPError , statusCode :429, statusMessage : Too Many Requests }

When I try to translate "says goooo" and "Naguará me moría", I get TypeError

Hi there,

When I try to translate "says goooo" and "Naguará me moría", I get TypeError.

The error details is below:
"TypeError: Cannot read property 'forEach' of null\n at translate (/app/node_modules/@iamtraction/google-translate/src/index.js:108:17)\n at runMicrotasks ()\n at processTicksAndRejections (internal/process/task_queues.js:97:5)"

I am able to reproduce the error every time I try to translate "says goooo" and "Naguará me moría"

As I look further into the investigate, I found that the same thing happens on Google Translate as well:
Google Translate when on the "DETECT LANGUAGE" mode, it is unable to recognize "says goooo" therefore, it return the result as blank.

Now, I just wondered why we have encounter this issue before. Did Google Translate has recently updated?

Regards,

SyntaxError: Unexpected token < in JSON at position 0

I used a simple code to translate strings using @iamtraction/google-translate

    const translate = require('@iamtraction/google-translate');
    
    module.exports = function({ string, from, to }) {
    
    	return new Promise(resolve => { 
    
    		run();
    
    		async function run() {
    		    try {
    		        const res = await translate(string, { from, to });
    				return resolve(res.text);
    		    } catch(err) {
    		        console.log(err);
    		        run();
    		    }
    		}
    
    	});
    
    }

and I used the above function as:

    const bigTranslation = await googleTranslator({ string: 'It looks like we’ll have to stand', from: 'en', to: 'es' });
    
    return console.log(bigTranslation);

It worked perfectly till hours ago but now I get this error:

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at consumeEnd (C:\inetpub\wwwroot\Server\node_modules\undici\lib\api\readable.js:237:20)
at BodyReadable. (C:\inetpub\wwwroot\Server\node_modules\undici\lib\api\readable.js:219:7)
at BodyReadable.emit (node:events:513:28)
at BodyReadable.emit (C:\inetpub\wwwroot\Server\node_modules\undici\lib\api\readable.js:66:18)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Why This is happening ?

HTTPError 302 after regular translation

After a few successful translates start to fail with warnings:
node index.js { HTTPError at translate (C:\Users\User\Desktop\node_test\node_modules\@k3rn31p4nic\google-translate-api\src\index.js:143:19) at process._tickCallback (internal/process/next_tick.js:68:7) name: 'HTTPError', statusCode: 302, statusMessage: 'Found' }

index.js:

translate(articleRU, { from: 'ru', to: 'bg' }).then(res => { console.log(res.text); }).catch(err => { console.error(err); });

Forbidden StatusCode: 403

 https://translate.google.com/translate_a/single?client=gtx&sl=en&tl=ru&hl=ru&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=1&ssel=0&tsel=0&kc=7&q=menka&tk=86352.86352
info: Microsoft.AspNetCore.NodeServices[0]
      { HTTPError
          at translate (C:\Projects\service\node_modules\@k3rn31p4nic\google-translate-api\src\index.js:145:19)
          at process._tickCallback (internal/process/next_tick.js:68:7)
        name: 'HTTPError',
        statusCode: 403,
        statusMessage: 'Forbidden' }

Never getting didYouMean true

Following this:

translate('Thndak you', { from: 'en', to: 'fr' }).then(res => {
  console.log(res.text); // OUTPUT: ''
  console.log(res.from.autoCorrected); // OUTPUT: false
  console.log(res.from.text.value); // OUTPUT: [Thank] you
  console.log(res.from.text.didYouMean); // OUTPUT: true
}).catch(err => {
  console.error(err);
});

didYouMean always returns false while res.text returns Je vous remercie.
so basically a mix of two examples in the Readme

please make it support chinese.

it doesnt support chinese please make it support chinese
output:
{
"text": "%E4%BD%A0%E5%A5%BD",
"res": "%y4% start%o%br%brother%bad"
}

RequestError: The `body`, `json` and `form` options are mutually exclusive

hallo, thanks for this project.

i use it to translate chinese to english, a exception happen when the translate content is big.

The exception is:
Error: RequestError: The body, json and form options are mutually exclusive
Error: The body, json and form options are mutually exclusive

The translate content is:

我们用sureness来管理restful api认证鉴权

面对 restful api 的认证鉴权,基于 rbac (用户-角色-资源)主要关注于对 restful api 的安全保护
无特定框架依赖(本质就是过滤器处拦截判断,已有springboot,quarkus,javalin,ktor等demo)
支持动态修改权限配置(动态修改哪些api需要被认证,可以被谁访问)
支持主流http容器 servletjax-rs
支持多种认证策略, jwt, basic auth, digest auth ... 可扩展自定义支持的认证方式
基于改进的字典匹配树拥有的高性能
良好的扩展接口, demo和文档
sureness的低配置,易扩展,不耦合其他框架,能使开发者对自己的项目多场景快速安全的进行保护

i guess the exception may happen in this code:

        // If request URL is greater than 2048 characters, use POST method.
        if (url.length > 2048) {
            delete data.q;
            requestOptions = [
                `${baseUrl}?${querystring.stringify(data)}`,
                {
                    method: "POST",
                    form: true,
                    body: {
                        q: text
                    }
                }
            ];
        }
```
the post method access google api may be can not use form when body is json.

Hope to help! 

statusCode: 429 statusMessage: 'Too Many Requests'

Hi, when I make a request, I get the status code 429 with too many request.
Is there a limitation on the API call? if yes, would you tell me what they are? so I will be aware of them. thanks a lot.

Bug in the return of the translation

Hello @iamtraction! I created a translation command for my bot, but when the bot returns the translation, it comes with commas (,) in place of spaces. I'm not sure, but I imagine it is a package bug. Please fix this error. Thanks!

HTTP Error

hey i was trying to make a translate command for my discord bot but i'm facing HTTPSError i have a simple code like this
const arLang = await translate(Message, { to: 'ar' });
where Message is a message from a author and then it will send the translation to the discord channel and there is a catch block for err which gives HTTPError so IDK what should i do if you want i can provide you whole code too

note: 1st i thought i get this err cuz m trying to get 10 translation so i removed 9 of them but still the err was there

Booelan

Did you mean Boolean in the Readme?

Not translate properly every request. Maximum time its showing this error

{HTTPError
at translate (/rbd/pnpm-volume/d3e2a241-36ab-414f-9781-4e47668ac65e/node_modules/.registry.npmjs.org/@k3rn31p4nic/google-translate-api/1.0.5/node_modules/@k3rn31p4nic/google-translate-api/src/index.js:143:19)

at process._tickCallback (internal/process/next_tick.js:68:7)

name: 'HTTPError',

statusCode: 403,

statusMessage: 'Forbidden' }

Support Languages

Add a list of supported languages with their short form to your readme.md to make it easier to developers to use ☺️

Like English - en

BAD_REQUEST

Error
at /Users/asd/node_modules/google-translate-api/index.js:105:17
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 'BAD_REQUEST'
}

Failed to compile under node.js 16.14.0

ERROR Failed to compile with 2 errors 14:58:07

These dependencies were not found:

  • dns in ./src/utils/text-translate.js
  • http2 in ./src/utils/text-translate.js

node.js 16.14.0

When translate long text. The version 2.0.0 give SyntaxError: Unexpected token '<', \"<html lang\"... is not valid JSON

Hi there,

The version 2.0.0 errors out when trying to translate long text. The error is the following:
"SyntaxError: Unexpected token '<', "<html lang"... is not valid JSON"

The length of the text varies. On some English texts, it can translate up to 1380 characters but another error out at about 1200 characters. The error also happens in another language. For example: Chinese (zh-CN) errors out at 400 characters.
(If you need me to give you the text I used to test this. I will be more than happy to. Because posting it here will be really unattractively long.)

Note: I've tried the same texts with the previous version (1.1.2) and it works just fine. So I guess the error has not got anything to do with the Google Translation Service.

Many thanks :D

[HTTP Error] Is there a maximum amout of translations?

After some translations in a for loop i get an error [HTTP Error].
Is there a maximum amount of translations available for a specific amount of time?

const translate = require('@iamtraction/google-translate');

for (const keywordToTranslate of keyWordsList) { await translate(keywordToTranslate, { from: 'de', to: 'en' }).then(res => { keyWordsListEN.push(res.text); }).catch(err => { console.error(err); }); }

connect ECONNREFUSED 127.0.0.1:443 calling translate()

I'm using your library in straight way, very similar to the README but I receive a error trying to translate a simple text.

Installed with npm install @iamtraction/google-translate
this is my code:

const translate = require('@iamtraction/google-translate');

module.exports = {
    translateText: async () => {
        return await translate("translate this please", { from: 'en', to: 'it' });
    },
};

this is the result I obtain:

[2021-01-23T20:49:04.204Z] error RequestError: connect ECONNREFUSED 127.0.0.1:443
    at ClientRequest.<anonymous> (/Users/lpelosi/git/bghub-backend/node_modules/@iamtraction/google-translate/node_modules/got/dist/source/core/index.js:953:111)
    at Object.onceWrapper (events.js:422:26)
    at ClientRequest.emit (events.js:327:22)
    at ClientRequest.origin.emit (/Users/lpelosi/git/bghub-backend/node_modules/@iamtraction/google-translate/node_modules/@szmarczak/http-timer/dist/source/index.js:39:20)
    at TLSSocket.socketErrorListener (_http_client.js:426:9)
    at TLSSocket.emit (events.js:315:20)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)

Additional info:
npm version: 6.14.6
node version: v12.18.4

Do you have any suggestion? Thanks!

Could not run the application after installing, throwing an error mentioned below

Error: Unable to resolve module querystring from /Users/steve/project/personal-project/Demo_Test/node_modules/@iamtraction/google-translate/src/index.js: querystring could not be found within the project or in these directories: node_modules
../../../node_modules

1 | const querystring = require("querystring");
| ^
2 | const { request } = require("undici");
3 |
4 | const languages = require("./languages");

Link broken

Hi, bro! The dependencies link on readme.md is broken.
image

HTTPError

It was working so well, but now shows an error when translating:
Error [HTTPError] at translate (C:\...\node_modules\@k3rn31p4nic\google-translate-api\src\index.js:143:25) at processTicksAndRejections (internal/process/task_queues.js:97:5) { name: 'HTTPError', statusCode: undefined, statusMessage: undefined }

Version 2.0.0 error: SyntaxError Unexpected token '<', \"<html lang\

Hi there,

The new version (2.0.0) errors out when trying to translate the following to zh-CN:
"@เบิร์ด..originol @ยายมีกะพรลี่จัง @kittikorn Intra @อุ๋มอิ๋ม ทำงานตามยอดที่เรากำหนดนะครับถ้าQcบอกว่าตรวจไม่ทันหรือคัดงาน PSI แล้วพวกเค้าไม่เอา คัดคัดบอกได้แต่ไปถึงหน้างานเค้าแล้วบอกไม่ได้ ไม่ใช่ปัญหาของเรานะครับ ถ้าเค้าเบรคเพราะตรวจงานไม่ทันเอาลงกลุ่มจีนได้เลย"

Here is the error:
"SyntaxError: Unexpected token '<', "<html lang"... is not valid JSON\n at JSON.parse ()\n at consumeEnd (/app/node_modules/undici/lib/api/readable.js:237:20)\n at BodyReadable. (/app/node_modules/undici/lib/api/readable.js:219:7)\n at BodyReadable.emit (node:events:513:28)\n at BodyReadable.emit (/app/node_modules/undici/lib/api/readable.js:66:18)\n at endReadableNT (node:internal/streams/readable:1359:12)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"

I've tried it on the previous version (1.1.2) and it works. So I guess it only happens in the version 2.0.0

When you get a chance, would you be able to look into it? Thanks a lot :D

Regards,
Tee Uttamavanit

HTTPError

Something has changed...
It was working ok but now, the simplest example is failing with HTTPError...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.