GithubHelp home page GithubHelp logo

text-translation-api-v3-python's Introduction

page_type name description urlFragment languages products
sample
Microsoft Translator Python samples (v3)
This repository includes Python code samples for Microsoft Translator.
translator-python-v3
python
azure
azure-cognitive-services
azure-translator

Translator API V3 - Python Samples

This repository includes Python code samples for Microsoft Translator. The samples are designed to run on Python 2.7.x and Python 3.x. Each sample corresponds to a Quickstart activity on doc.microsoft.com, including:

  • Translating text
  • Transliterating text
  • Identifying the language of source text
  • Getting alternate translations
  • Getting a complete list of supported languages
  • Determining sentence length

Get started with the Translator quickstart.

Prerequisites

Here's what you'll need before you use these samples:

Code samples

This repository includes a sample for each of the methods made available by the Microsoft Translator API v3. To use each of the samples, follow these instructions:

  • Create a new project in your favorite IDE or editor.

  • Copy the code from one of the samples into your project.

  • Set your subscription key, the Azure region of your resource and the Text Translation endpoint as environment variables TRANSLATOR_TEXT_SUBSCRIPTION_KEY TRANSLATOR_TEXT_REGION TRANSLATOR_TEXT_ENDPOINT

  • Run the program. For example: python Translate.py.

Resources

text-translation-api-v3-python's People

Contributors

chriswendt1 avatar erhopf avatar jann-skotdal avatar kellyaltom avatar shawn-jung avatar v-jaswel 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

text-translation-api-v3-python's Issues

Improvement in code sample - rename variable

Hello,

In some of the examples there is:

request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()

Would it be possible to rename request for response (for example):

response = requests.post(constructed_url, headers=headers, json=body)
response = response.json()

I'm just mentioning it because post() returns a requests.models.Response object.

Regards

Http connection pool error

Hi When i am trying to make a post request i am getting the below error

requests.exceptions.SSLError: HTTPSConnectionPool(host='api.cognitive.microsofttranslator.com', port=443): Max retries exceeded with url: /translate?api-version=3.0&to=de (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:748)'),))

I have tried adding proxy and set the verify = false but it didnot work .please help me with resolution

Error : the JSON object must be str, not 'bytes'

When I run the sample code with my subscription keys, I get the following error.

Error :

File "T.py", line 42, in
output = json.dumps(json.loads(result), indent=4, ensure_ascii=False)
File "/usr/lib/python3.5/json/init.py", line 312, in loads
s.class.name))
TypeError: the JSON object must be str, not 'bytes'

Requests module installed but not recognized

Maybe not a bug in this code, but is anyone having trouble with the requests module not being recognized in your IDE? I tried to create this sample in just a .py file too (so I know it's not my IDE), but same issue. When I check my python libraries with pip list, it shows requests 2.20.0 is indeed installed.

Simplified translate.py example without environment variables and JSON output, but as text

I can't understand the rationale behind the use of environment variables in the Translate.py file: https://github.com/MicrosoftTranslator/Text-Translation-API-V3-Python/blob/master/Translate.py

Why set the variables to values, and then check if they are available with their name (not value) in the os environment, only to be assigned to other variables? Why not do it directly? So instead of:

key_var_name = 'TRANSLATOR_TEXT_SUBSCRIPTION_KEY'
if not key_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(key_var_name))
subscription_key = os.environ[key_var_name]

just:

subscription_key = 'TRANSLATOR_TEXT_SUBSCRIPTION_KEY'

As a simple example? If you want to use environment variables, then have a associated .env file and import it, describe how to use it. To make it more beginner friendly. And have an option to just export it as a text, not JSON.

Problem with alignment information.

I have next code:

def translate(
        from_lang: str,
        to_lang: str,
        texts: List[str],
        include_alignment: bool = True
    ) -> List[JSONType]:
        constructed_url = "https://api.cognitive.microsofttranslator.com/translate"
        params = {
            "api-version": "3.0",
            "from": from_lang,
            "to": to_lang,
            "includeAlignment": include_alignment,
            "includeSentenceLength": True,
        }
        headers = {
            "Ocp-Apim-Subscription-Key": "*******",
            "Ocp-Apim-Subscription-Region": "GLOBAL",
            "Content-type": "application/json",
            "X-ClientTraceId": str(uuid.uuid4()),
        }
        body = [{"text": text} for text in texts]
        request = requests.post(
            constructed_url, params=params, headers=headers, json=body
        )
        resp = request.json()
        return resp
result = translate("de", "en", ["Artikelnummer des Kunden"])

and i have a result
{'translations': [{'text': "Customer's item number", 'to': 'en', 'alignment': {'proj': '0:12-11:14 0:12-16:21 14:16-0:9'}, 'sentLen': {'srcSentLen': [24], 'transSentLen': [22]}}]}
so if we look at result:
Original: Artikelnummer des Kunden
Translation: Customer's item number
we see that we have no alignment for the original word "Kunden".

"message": "Resource not found"

Examples not working for me. Can anyone confirm that?

I got always this error?

{
    "error": {
        "code": "404",
        "message": "Resource not found"
    }
}

translation API doesn't work in python2.7?

I am developing an web App that calls the Text Translation API. My whole project is developed in Python2.7 so I try to call the APIs in Python2.7. But I always get the failure result:

send: 'POST /translate?api-version=3.0&to=zh HTTP/1.1\r\nHost: api.cognitive.microsofttranslator.com\r\nAccept-Encoding: identity\r\nContent-Length: 19\r\nOcp-Apim-Subscription-Key: [my-sub-key]\r\nContent-type: application/json\r\nX-ClientTraceId: 7ade7c69-7100-4afb-8bb7-676d594637c4\r\n\r\n'
send: '[{"Text": "Hello"}]'
DEBUG:root:
reply: 'HTTP/1.1 404 Not Found\r\n'

My code is in https://github.com/yangpancn/alchemy/blob/master/ms_translator.py

could someone provide a demo code how to use the API in python2.7?
Thanks in advance!

Count of translated characters

There is a limit of 12M characters per month to the F0 pricing tier. I wanted to clarify what if I have given let's say 10M characters to the API, out of which only 1M characters need translation.
For eg. I want to have all characters in English, but only 1M characters are non-English, which means effectively the API is working on 1M characters only.
So will I be charged for complete 10M characters, or only 1M characters?

About the Translate.py sample

Hello ,
I couldn't run the script Translate.py until I forced the parameter 'Ocp-Apim-Subscription-Region' in the header to the region of my subscription , to me 'francecentral' .
Otherwise great sample.
Thank you .

Ocp-Apim-Subscription-Region is missing from the headers

I was not able to make the Translate.py work, because all I got back from the API was:

{
    "error": {
        "code": 401000,
        "message": "The request is not authorized because credentials are missing or invalid."
    }
}

I was investigating the documentation and it seems, that the Ocp-Apim-Subscription-Region header is required for the authentication.

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.