我已经在我的项目中安装了google/cloud/translate,Gemfile.lock中的版本是:
google-cloud-translate (2.1.0)使用以下代码:
require "google/cloud/translate"
project_id = "<Project ID>" # from my Google Cloud Platform
translate = Google::Cloud::Translate.new version: :v2, project_id: project_id这是文档所说的,也是回答相关的建议(请注意,我使用的是v2而不是v3)
RuntimeError: Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials for more information此部分返回true:
require "google/cloud/translate"Update I已经执行了以下所有步骤:
https://cloud.google.com/docs/authentication/production
创建一个服务帐户,一个凭据密钥,并设置env变量(在Windows上),然后我尝试用google/cloud/storage示例测试凭据配置,它运行良好,但当我尝试使用:google/cloud/translate gem时
translate = Google::Cloud::Translate.new version: :v2, project_id: project_id
我还是犯了同样的错误
什么是错误?提前感谢您的帮助。
发布于 2020-09-18 03:43:38
为此,您将需要使用google帐户的所有密钥的.json文件,一旦您在项目的相同路径中拥有该文件,您可以执行如下代码:
module GoogleTranslator
require "google/cloud/translate"
ENV["GOOGLE_APPLICATION_CREDENTIALS"] = "yourfile.json"
class Translate
attr_reader :project_id, :location_id, :word, :target_language
def initialize(project_id, location_id, word, target_language)
@project_id = project_id
@location_id = location_id
@word = word
@target_language = target_language
end
def translate
client = Google::Cloud::Translate.translation_service
parent = client.location_path project: project_id, location: location_id
response = client.translate_text(parent: parent, contents: word.words.to_a, target_language_code: target_language)
translate_content(response)
end
def translate_content(response)
word.translation(response)
end
end
end
class Word
attr_reader :words
def initialize(words)
@words = words
end
def translation(words)
words.translations.each do |word|
puts word.translated_text
end
end
end
module GoogleTranslatorWrapper
def self.translate(project_id:, location_id:, word:, target_language:)
GoogleTranslator::Translate.new(project_id, location_id, word, target_language)
end
end
GoogleTranslatorWrapper.translate(project_id: "your_project_id_on_google", location_id: "us-central1", word: Word.new(["your example word"]), target_language: "es-mx").translate希望这能清楚:)!
发布于 2019-12-10 20:49:56
ruby.rb脚本 # project_id = "Your Google Cloud project ID"
# text = "The text you would like to detect the language of"
require "google/cloud/translate"
text = 'I am home'
translate = Google::Cloud::Translate.new version: :v2, project_id: project_id
detection = translate.detect text
puts "'#{text}' detected as language: #{detection.language}"
puts "Confidence: #{detection.confidence}"https://stackoverflow.com/questions/59273317
复制相似问题