Translate English to Chinese for Bitcoin

Posted by Ronak Mehta

Translate English Text To Chinese for Bitcoin

Overview

In this tutorial we'll show you how to become an API reseller by setting up a bitcoin-payable translation endpoint using 21.

Prerequisites

Install 21

You will need the following items:

  • Either a 21 Bitcoin Computer or 21
  • The latest version of the 21 software, obtained by running 21 update

If you've got all the prerequisites, you are ready to go. Let's get started!

Step 1: Get a Google Translate API Key

Go to the Google Developers Console and create an account. Click on Dashboard on the left-hand side of the window and select Enable and manage APIs. From the Other popular APIs category select Translate API. Select the Enable API button on top and then click on the Credentials option on the left-hand side. Click on Add credentials drop down button and select API key. A pop-up window with different key options will show up. Select Server key. In the new window enter the name of your project that this key will be stored under and click on the Create button. Take note of your API key once it is created.

NOTE: Google requires a user to enter their billing information in order for the API key to work. You will need to add your billing information in order to use the API key you just created above. As noted on their pricing page, any usage above the courtesy limits will trigger billing. You won't encounter that limit in small-scale testing, but beyond that point you will probably want to set your bitcoin-payable API's price above the corresponding Google API price to at least break even. You can even set it to a higher amount, as a user's fixed cost to buy the endpoint is in theory eliminated if they already have bitcoin (so they may experience net savings).

In the Google Developers Console window, click on the Products & Services menu option that is represented as 3 horizontal white dashes. Select Billing from the options shown in the drop-down menu and enter your billing information.

With this step complete you are ready to use your Google Translate API key. Let's create the server that will send the request to the Google Translate REST API.

Step 2: Create a server that translates a user's input from English to Chinese

Open up a new terminal window. If you use a 21 Bitcoin Computer, ssh into it:

## Only necessary if you use a 21 Bitcoin Computer
ssh twenty@IP_ADDRESS

Create a folder for your project:

mkdir translate-server && cd translate-server

Set an environment variable that defines your newly created Google Translate API key.

export GOOGLE_TRANSLATE_API_KEY=enter_your_API_key_here

You will also need to install the google api client python library. Type the following command in your terminal:

sudo pip3 install google-api-python-client

Now start editing a file named translate-server.py in this directory with the following code:

import os
from flask import Flask, request
from apiclient.discovery import build

# import from the 21 Developer Library
from two1.wallet import Wallet
from two1.bitserv.flask import Payment

# set up server side wallet
app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)

# create a developer account on Google and obtain a API key for the translation app
service = build('translate', 'v2', developerKey=os.environ.get('GOOGLE_TRANSLATE_API_KEY'))


# create a 402 end-point that accepts a user's input and translates it to Chinese and returns it
@app.route('/translate')
@payment.required(3000)
def trans():
    """Translate from English to Chinese"""
    # Get user's input text
    text = request.args.get('text')

    # Send a request to Google's Translate REST API using your API credentials defined above
    ans = service.translations().list(source='en', target='zh-CN', q=text).execute()

    # Return translated text back to user
    return ans['translations'][0]['translatedText']

if __name__ == '__main__':
    app.run(host='::', debug=True)

Start the server with:

python3 translate-server.py

Step 3: Create a client that accepts English text and returns the Chinese translation

Open another new terminal window. If you use a 21 Bitcoin Computer, ssh into it:

## Only necessary if you use a 21 Bitcoin Computer
ssh twenty@IP_ADDRESS

Create a folder to house the client project:

mkdir translate-client && cd translate-client

Now start editing a file named translate-client.py in this directory and paste in the following code:

# import from the 21 Developer Library
from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests

# set up bitrequest client for BitTransfer requests
wallet = Wallet()
requests = BitTransferRequests(wallet)

# server address
server_url = 'http://[::1]:5000/'


def buy_translation():
    # Ask user to input text in english
    print("Welcome to English-to-Chinese Translation.\n")
    inp_text = input("Enter the English text that you would like translated into Chinese:\n")

    # Send request to server with user input text and user's wallet address for payment
    sel_url = server_url+'translate?text={0}&payout_address={1}'
    response = requests.get(url=sel_url.format(inp_text, wallet.get_payout_address()))

    # Print the translated text out to the terminal
    print("The following is the translation of the text you input.\n")
    print(response.text)

if __name__ == '__main__':
    buy_translation()

Save this file and close it. Now run your client script with the following command:

python3 translate-client.py

If all goes well, you should see a prompt for the input text you wish to translate. A purchase is executed returning the translated text. You can confirm this by running 21 log.

Next Steps

This is an example of how to resell a paid API for Bitcoin. An interesting extension of this would be to add a second, higher-priced endpoint that involved some human labor, giving higher quality human translation at the expense of a higher price and significantly increased translation latency. One way to do this would be to have human translators standing by in a Slack forum, and set up a machine-payable translation API backed by a Slack integration that would return the results.


How to send your Bitcoin to the Blockchain

Just as a reminder, you can send bitcoin mined or earned in your 21.co balance to the blockchain at any time by running 21 flush . A transaction will be created within 10 minutes, and you can view the transaction id with 21 log. Once the transaction has been confirmed, you can check the balance in your bitcoin wallet from the command line with wallet balance, and you can send bitcoin from your wallet to another address with wallet sendto $BITCOIN_ADDRESS --satoshis $SATOSHI_AMOUNT --use-unconfirmed. The --satoshis flag allows you to specify the amount in satoshis; without it the sendto amount is in BTC, but this behavior is deprecated and will be removed soon. The --use-unconfirmed flag ensures that you can send even if you have unconfirmed transactions in your wallet.


Ready to sell your endpoint? Go to slack.21.co

Ready to try out your bitcoin-payable server in the wild? Or simply want to browse and purchase from other bitcoin-enabled servers? Head over to the 21 Developer Community at slack.21.co to join the bitcoin machine-payable marketplace hosted on the 21 peer-to-peer network.