Monday, September 9, 2024

Azure translation api connection from python

 import requests, uuid, json

import re
# Add your key and endpoint
myKey = "XXXXXXXXX"
api_url = "https://XXXXXXXXXX/translate"
api_url1 = "https://XXXXXXXX/detect"
myParams = {
    'api-version': '3.0',
    'scope': 'translation',
    # 'from': 'en',
    'to': ['fr']
}
myHeaders = {
    'Ocp-Apim-Subscription-Key': myKey,
    'charset': 'UTF-8',
    'Content-type': 'application/json',
    'includeAlignment': 'true'
    # 'X-ClientTraceId': str(uuid.uuid4())
}

ztext = 'pH value (10% dry substance  DIN 19268                                                                   '
ztext_copy = ztext
words = ztext.split("  ")
translated = []
cnt = 0; word_len = 0; endIndex, startIndex = 0,0
ztext1=""; extra=""

fromText = [{'Text': ztext}]
APIRequest = requests.post(api_url1, params=myParams, headers=myHeaders, json=fromText)
APIResponse = APIRequest.json()
language = APIResponse[0]["language"]
print("Lang:",language)

if language == "de":
    print("ok")
local_var = ""
leng = 0
for i,word in enumerate(words):
    if word:
        startIndex += (word_len + cnt)
        # print("start index:",startIndex)
        sp = startIndex - endIndex
        # lc = local_var[word_len:sp]
        if sp>0:
            ztext1 +=extra[:sp-1]
            leng = len(extra[:sp-1])
        word_len = len(word)
        endIndex = startIndex + word_len
        # print(word_len)
        cnt =2
        # print("end index: ", endIndex)
        fromText = [{'Text': word}]
        APIRequest = requests.post(api_url, params=myParams, headers=myHeaders, json=fromText)
        APIResponse = APIRequest.json()
        #Getting only language text
        translation = APIResponse[0]["translations"][0]["text"]
        translation = translation.replace("&lt;","<").replace("&gt;",">")
        # translation = translation.replace("!", " ")
        # Return the translation
        translated.append(translation)
        # print(translation)
        # t = ztext[startIndex:endIndex].replace(" ","*")
        # print("index printinting: ",t)
        trsLen = len(translation)
        # print("trslen:",word_len, trsLen)
        # ex_len = 0
        # if trsLen > word_len:
        #     ex_len = trsLen - word_len
        if trsLen < word_len:
            addSpace = word_len - trsLen
            translation = translation + " " * addSpace
        print("Start and end:",startIndex, endIndex)
        # print("____start val:",ztext[:startIndex])
        print(translation)
        # print("end val___:",ztext[(endIndex+ex_len):])
        # ztext =ztext[:startIndex]+ translation + ztext[(endIndex+ex_len):]
        dif = endIndex - startIndex
        ztext1 +=(sp - leng)*" "
        ztext1 +=translation[:word_len]
        extra = translation[word_len:]
        # print(ztext)
        # print(ztext_copy)
        cnt =2
    else:
        cnt +=2
   
print(ztext)
print(ztext1)
print(ztext_copy)

No comments: