How to return the auto detected language from LanguageApp.translate?

安稳与你 提交于 2021-01-29 11:10:45

问题


I´d like to make an application which translates text to english (no matter which language is entered). The translation is already working pretty well, but now i´m trying to detect the language entered and i have no clue how to get the detected language from LanguageApp.translate.

I tried using the google API but as it´s paid i need a opinion which is free as it´s a small project just for me and non commercial.

var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);

sourceText, and targetLang (target Language) are specified. sourceLang is "" (empty), so google translate auto detects it.

I´d like to add the detected language to the string that gets returned. For example if i enter "bonjur" it returns "hellofr" with fr standing for french.


回答1:


If you analyze the response of a manually fetched translation request, e.g.

var response = UrlFetchApp.fetch('https://translate.google.com/#view=home&op=translate&sl=auto&tl=en&text=pantalla');  
  Logger.log(response.getAllHeaders())

you will see that the response does not contain any details about the detected source language. Google must be doing the detection server-side, with an additional API. Thus, unfortunately, you cannot retrieve the automatically detected language with the LanguageApp functionality in Apps Script.

As a workaround, I recommend you to call within Apps Script an external Language detection API in addition to using the LanguageApp for translation.




回答2:


You can use an external api, for example detectlanguage.com. Their free account offers 1000 requests per day.

// Get your APIkey at https://www.detectlanguage.com
// Replace it in 'yourApiKeyHere'
function detectLanguage(text) {
  var payload = {
    "q": text
  };

  var options = {
    "method"  : "post",
    "payload" : payload,
    "headers" : {
      "Authorization" : "Bearer " + yourApiKeyHere
    }
  };

  var url        = "https://ws.detectlanguage.com/0.2/detect";   
  var response   = UrlFetchApp.fetch(url, options);   

  Logger.log(response.getContentText());
  // response: {"data":{"detections":[{"language":"nl","isReliable":true,"confidence":11}]}}
  return JSON.parse(response.getContentText()).data.detections[0].language;
}

Now use this in your code

// contentType is optional
function translateTo(word, targetLanguage, contentType) {
  return contentType ?
    LanguageApp.translate(word, detectLanguage(word), targetLanguage, {contentType: contentType})
    : LanguageApp.translate(word, detectLanguage(word), targetLanguage);
}


来源:https://stackoverflow.com/questions/57076471/how-to-return-the-auto-detected-language-from-languageapp-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!