Code Monkey home page Code Monkey logo

google-translate-server's Introduction

google-translate-server

Important updates

3/1/2021:

Since around December 1st 2020, Google translate started using a newer API version. the older API discussed here still works, BUT:

  1. new TKK values are no longer available when loading the site.
  2. old TKK values still work, but who knows for how long (or when the old API will be removed completely).

Fortunately, I kept historical TKK values, so the service is working again (for now), using previously stored values. However, I would no longer not recommend this solution for any purpose.

Below are some TKKs:

444444.1050258596

445678.1618007056

445767.3058494238

444000.1270171236

445111.1710346305

1/1/2021:

Google has recently changed the translate API, so the solution suggested here does no longer work. I may provide an alternative solution in the future, but no ETA, sorry

[End of updates]


NodeJS proxy for Google Translate & TTS services.

supplying a simple API to get you through Google's blocking of the public API for free. see APIs below

Build Status

IMPORTANT: as it is deployed to a free Heroku server, it has limited dynos quota per month. if you need to make extensive use, please don't overload this server and deploy your own one... I started reaching my monthly quota in the last few months, so by the end of the month no one could use it..

Setup

Make sure you have npm properly installed.

  1. git clone [email protected]:guyrotem/google-translate-server.git
  2. npm install
  3. type cp dotEnv .env in the root of the project, to create your private environment vars
  4. install and configure Postgres on your computer (or skip it and disable Postgres. see below) => Install Postgres => create a local database: "psql -c 'create database google_translate_server;' -U postgres" => configure .env with the correct local credentials: username/password/port (defaults are postgres/1234/5432) => make sure PostgreSQL is running in the background.
  5. npm start

You may also disable Postgres: "sed -i -e 's/ENABLE_PSQL=true/ENABLE_PSQL=false/' .env"

You may also work in test mode, where translation system is mocked by the data contained in data.json file. npm run simulation In this mode, no requests will be sent to Google, but it uses the same "production" code to extract the TKK and send queries (useful for IT tests). It currently only supports the queries "dog" and "cat", in French, Spanish, German and Hebrew, but you may modify the data file for more :).

¡¿ Why do I need a proxy ?!

Can't I just call the API used by Google Translate? Well, sure, just open the networking panel of the Dev tools and see where the requests go. You would notice that the API requires around a dozen parameters, most of which you will quickly understand or walk around them easily. ...except for "tk", which has some random-looking values: e.g.: "258417.372466". Try to fake it with random values, and you will get HTTP status 403 (Forbidden). It turns out that "tk" is a hash value based on your query (the string you wish to translate) and some private key (called TKK), which is embedded in your DOM when you load the Google translate page. This private key changes every hour (but it seems that old keys can be used for quite a long time before they actually expire). For more info on the hash function, see tk-hash.js.

As a conclusion, in order to use Google's API directly, you would have to:

  1. get your hands on some private key (by loading Google Translate website) => tkk
  2. calc: tk := googleHashFunction(query, tkk)
  3. call the AJAX API with (query, tk, targetLang, sourceLang, ...) and some more irrelevant fields
  4. parse the result to get the data you wished for (which is not as straight forward as you'd might expect)

The API result is made of arrays of arrays (like a JSON that was stripped out of its labels), so you are left to figure out what every field means. Moreover, there are at least 4 different result formats (depending on the target language, complexity of the query, etc.) so you must learn to adapt.

This proxy API does all that for you!

APIs

/api/translate > /api/languages > /api/tts

/api/translate

translate a query into multiple languages simultaneously.

INPUT:

for multiple languages, use POST with the following JSON body:

{
	query: String,
	sourceLang: String,	//	2 or 3 letters, _usually_ the ISO2 language code, small case
	targetLangs: String[],	//	USE targetLangs (array) to translate to multiple target languages in the same call
}

NOTE: maximal supported query length is currently around 850 characters. it will be fixed soon. Longer queries should be sent to Google as form-data

for a single target language, you may use GET with the following query string:

{
	query: String,
	sourceLang: String,	//	2 or 3 letters, _usually_ the ISO2 language code, small case
	targetLang: String,	//      USE targetLang (string) to translate to a single target langauge
}

you may use sourceLang: "auto" to let Google choose for you

OUTPUT

[
 {
	extract: {
		translation: String,
		actualQuery: String, //	best match for query (should be the same as the query, unless there was a typo)
		resultType: Int, //	index of Google's response format
		transliteration: String, //	transliteration of the word in latin alphabet (partially available)
		synonyms: Array[String]	 //	full-query alternative suggestions (only available for short queries)
	},
	originalResponse: String  //	the original response returned from Google's API as a string
 },
 { ... }
]

EXAMPLE: https://google-translate-proxy.herokuapp.com/api/translate?query=where%20are%20my%20sunglasses&targetLang=de&sourceLang=en

/api/languages

INPUT: [no input arguments]

OUTPUT an array of all available languages, with names and their appropriate codes:

[
	{
		"name": "Spanish",
		"code": "es"
	},
...
]

EXAMPLE: https://google-translate-proxy.herokuapp.com/api/languages

/api/tts

INPUT: GET (as query string)

{
	query: String,
	language: String,	//	2 or 3 letters, _usually_ the ISO2 language code, small case
	speed?: Decimal		//	optional, in range [0.2, 1]
}

OUTPUT mpeg audio

EXAMPLE: https://google-translate-proxy.herokuapp.com/api/tts?query=perro&language=es&speed=0.24

Sample client using this API

See google-translate-client project for a working example of a FE project using this API (translating into multiple languages simultanously!)

IMPORTANT NOTICE

Google provides an Enterprise API for translating large amounts of text. It is actually not so expensive. If you need to use it for anything beyond personal usage, please create an enterprise account. (This is presumably why a friendlier API is not supplied by Google).

google-translate-server's People

Contributors

guyrotem 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

Watchers

 avatar  avatar  avatar  avatar

google-translate-server's Issues

Setup on share host with Nodejs

my share host has nodejs
https://blog.hawkhost.com/2018/09/14/introducing-nodejs-applications/

and I setup it
http://prntscr.com/ohar4h
http://prntscr.com/oharlm

this one work https://google-tts.stevephuc.dev/api/languages
but then try https://google-tts.stevephuc.dev/api/tts?query=perro&language=es&speed=0.24
{"error":"Server is still waking up, waiting to get a key from Gooogle. Please try again in a few seconds. it happens often on the 1st attempt after an idle period"}

what should I do

Update 1: may be there are not process.env.port in my host , I ask host support for it.

CORS issues

Could you please add an Access-Control-Allow-Origin header to your API, specifically the tts endpoint?
I guess I could make a PR if you are willing to merge it.

tanks

Good night thanks for sharing the code, I'm doing an angular version5 based on your code: Tesla369 will receive an image, it will turn into audio, then mp3. the part of turning into text already be ready. Follow the link for the project:

Firebase:
system-monkey.firebaseapp.com

Github
https://github.com/DevJoseWeb/x

It stopped working for me

[email protected] start /home/google-translate-server
node server.js

loading values from .env file:
{ PORT: '9333',
CLIENT_BASE_DOMAIN: 'http://localhost:5000',
DATABASE_URL: 'postgres:///google_translate_server',
ENABLE_PSQL: 'false' }
Topology initialized with:
{ externalApis:
{ googleTranslateApi: 'https://translate.google.com/translate_a/single',
googleTtsApi: 'https://translate.google.com/translate_tts',
googleTranslateWebpage: 'https://translate.google.com/' } }
Pre-loaeded last TKK: null
events.js:183
throw er; // Unhandled 'error' event
^

Error: listen EADDRINUSE :::9333
at Object._errnoException (util.js:1024:11)
at _exceptionWithHostPort (util.js:1046:20)
at Server.setupListenHandle [as _listen2] (net.js:1351:14)
at listenInCluster (net.js:1392:12)
at Server.listen (net.js:1476:7)
at Function.listen (/home/google-translate-server/node_modules/express/lib/application.js:617:24)
at Object.startServer (/home/google-translate-server/scripts/run-server.js:22:6)
at setProductionTopology.then (/home/google-translate-server/server.js:8:10)
at _fulfilled (/home/google-translate-server/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/home/google-translate-server/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/home/google-translate-server/node_modules/q/q.js:796:13)
at /home/google-translate-server/node_modules/q/q.js:604:44
at runSingle (/home/google-translate-server/node_modules/q/q.js:137:13)
at flush (/home/google-translate-server/node_modules/q/q.js:125:13)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node server.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2018-10-16T05_55_46_877Z-debug.log

How to deploy on Openshift getting below error


Starting the Java application using /opt/run-java/run-java.sh ...
ERROR: Neither $JAVA_MAIN_CLASS nor $JAVA_APP_JAR is set and 0 JARs found in /deployments (1 expected)
exec java -javaagent:/opt/jolokia/jolokia.jar=config=/opt/jolokia/etc/jolokia.properties -Xms256m -Xmx256m -XX:+UseParallelGC -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40 -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:ParallelGCThreads=1 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -XX:CICompilerCount=2 -XX:+ExitOnOutOfMemoryError -cp . -jar
Error: -jar requires jar file specification
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include:
    -d32	  use a 32-bit data model if available
    -d64	  use a 64-bit data model if available
    -server	  to select the "server" VM
                  The default VM is server,
                  because you are running on a server-class machine.


    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A : separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose:[class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  Warning: this feature is deprecated and will be removed
                  in a future release.
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -no-jre-restrict-search
                  Warning: this feature is deprecated and will be removed
                  in a future release.
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions with specified granularity
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions with specified granularity
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                  see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
See http://www.oracle.com/technetwork/java/javase/documentation/index.html  for more details.

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.