i've installed google/cloud/translate in my project, the version in the Gemfile.lock is:
google-cloud-translate (2.1.0)
With the below code:
require "google/cloud/translate"
project_id = "<Project ID>" # from my Google Cloud Platform
translate = Google::Cloud::Translate.new version: :v2, project_id: project_id
That is what the documentation says and also what this answer related suggest (please note that i'm using v2 instead of v3)
RuntimeError: Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials for more information
This part returns true:
require "google/cloud/translate"
Update
I already followed all the steps in:
https://cloud.google.com/docs/authentication/production
Created a service account, a credential key and set the env variable (on Windows), then I tried testing the credential configuration with the google/cloud/storage example and it's worked fine, but when I tried with: google/cloud/translate gem with
translate = Google::Cloud::Translate.new version: :v2, project_id: project_id
I still got the same error
What can be the error?
Thanks in advance for any help.
Hi for doing this you will need to have your .json file with all the keys of your google service account, once that you have that file in the same path of your project you could do something like the following code:
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
Hope this can be clear :)...!
Create a service account:
gcloud iam service-accounts create rubyruby --description "rubyruby" --display-name "rubyruby"
Get the service account name:
gcloud iam service-accounts list
Create the credential key file for your service account:
gcloud iam service-accounts keys create key.json --iam-account rubyruby#your-project.iam.gserviceaccount.com
Set the env variable:
export GOOGLE_APPLICATION_CREDENTIALS=key.json
Enable the translate API
Install the library:
gem install google-cloud-translate
Edit the ruby.rb script
# 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}"
Run the script:
ruby ruby.rb
Output:
'I am home' detected as language: en
Confidence: 1
Related
I would like to get URL that uploaded to Google Drive using 'google_drive' gem in rails.
I tried to get that from returned value that created but there were no such a link but API link so you cannot access to Google Drive.
Is there a method to get that link?
This is returned link, not this
https://www.googleapis.com/drive/v3/files/1m4Ja7qCNrfqhrkrtKibuPoV02Shp5w7G2?
I want this
https://drive.google.com/drive/u/0/folders/1ObHbN1heqwewgx1RkyEJ1Bm4GL3TSTjmI
Thank you.
require "google/apis/drive_v3"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "upload-image-to-gdrive".freeze
CREDENTIALS_PATH = "credentials.json".freeze
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE
class DriveUploader
def initialize
# Initialize the API
##drive = Google::Apis::DriveV3
##service = ##drive::DriveService.new
##service.client_options.application_name = APPLICATION_NAME
##service.authorization = authorize
end
def authorize
client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
user_id = "default"
credentials = authorizer.get_credentials user_id
credentials
end
def upload(name, image_source)
file_metadata = {
name: name,
parents: ['1ObHbN11jdig94x1RkyEJ1Bm4GL3TSTjmI'] # Drive ID
}
file = ##service.create_file(
file_metadata,
fields: 'id',
upload_source: image_source,
#content_type: 'image/jpeg' # 'application/pdf'
content_type: 'application/pdf' # 'application/pdf'
)
user_permission = {type: 'anyone', role: 'reader'}
##service.create_permission(file.id, user_permission, fields: 'id')
file
end
end
After uploading a file your drive and retrieving its Id, you can use the method Files: get in order to obtain the file resource.
The file resource contains all the metadata of the file, as specified in the documentation
Useful for you might be e.g. the webContentLink or the webViewLink
Both can be obtained by specifying them in fields for the drive.files.get method
I am using sitemap_generator for generating sitemaps in my RoR project.Everything is working fine till now.I am hosting my project on Heroku, which doesn't allow writing to the local filesystem.I still require some write access, because the sitemap files need to be written out before uploading. But I have to use microsoft azure to store my sitemap.The adapters listed in sitemap_generator does not include azure.Could someone point me in the right direction for writing an adapter for azure.
Refering to "Configure carrierwave" in this article I have made a few changes in my code.
But I am not sure only editing the initialiazer file is going to help.In the above article Carrierwave points to the WaveAdapter here which uses CarrierWave::Uploader::Base to upload to any service supported by CarrierWave
config/initializers/azure.rb
Azure.configure do |config|
config.cache_dir = "#{Rails.root}/tmp/"
config.storage = :microsoft_azure
config.permissions = 0666
config.microsoft_azure_credentials = {
:provider => 'azure',
:storage_account_name => 'your account name',
:storage_access_key => 'your key',
}
config.azure_directory = 'container name'
end
Please help!
I copied my setup from the S3 adapter and from Azure's ruby example
Add the azure blob gem to your Gemfile:
gem 'azure-storage-blob'
create config/initializers/sitemap_generator/azure_adapter.rb:
require 'azure/storage/blob'
module SitemapGenerator
# Class for uploading sitemaps to Azure blobs using azure-storage-blob gem.
class AzureAdapter
#
# #option :storage_account_name [String] Your Azure access key id
# #option :storage_access_key [String] Your Azure secret access key
# #option :container [String]
def initialize
#storage_account_name = 'your account name'
#storage_access_key = 'your key'
#container = 'your container name (created already in Azure)'
end
# Call with a SitemapLocation and string data
def write(location, raw_data)
SitemapGenerator::FileAdapter.new.write(location, raw_data)
credentials = {
storage_account_name: #storage_account_name,
storage_access_key: #storage_access_key
}
client = Azure::Storage::Blob::BlobService.create(credentials)
container = #container
content = ::File.open(location.path, 'rb') { |file| file.read }
client.create_block_blob(container, location.filename, content)
end
end
end
Make sure the container you create in Azure is a 'blob' container so the container is not public but the blobs within are.
and then in config/sitemaps.rb:
SitemapGenerator::Sitemap.sitemaps_host = 'https://[your-azure-address].blob.core.windows.net/'
SitemapGenerator::Sitemap.sitemaps_path = '[your-container-name]/'
SitemapGenerator::Sitemap.adapter = SitemapGenerator::AzureAdapter.new
That should do it!
I am trying to use Google Calendar API in my Ruby project and I meet a problem when I try to use the insert in the API. When I try the sample code on the https://developers.google.com/calendar/v3/reference/events/insert#examples,
I end up getting an error.
insertEvent.rb:2:in `<main>': uninitialized constant Google (NameError)
And if I paste this sample code after the quickstart.rb on this page
https://developers.google.com/calendar/quickstart/ruby, I will get this error:
quickstart.rb:84:in `<main>': undefined local variable or method `client' for main:Object (NameError)
Google did not get me the definition of client variable here so I do not what to insert here. I am a new learner of Ruby and thank you so much for helping.
Here is the code that I am stuck in
result = client.insert_event('primary', event)
puts "Event created: #{result.html_link}"
Ya, client isn't defined. Try this example code instead
https://github.com/googleapis/google-api-ruby-client/blob/master/samples/cli/lib/samples/calendar.rb
and
https://developers.google.com/calendar/quickstart/ruby
Important parts here:
require 'google/apis/calendar_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze
APPLICATION_NAME = 'Google Calendar API Ruby Quickstart'.freeze
CREDENTIALS_PATH = 'credentials.json'.freeze
TOKEN_PATH = 'token.yaml'.freeze
SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY
def authorize
client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
# figure out your user_id
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(base_url: OOB_URI)
puts 'Open the following URL in the browser and enter the ' \
"resulting code after authorization:\n" + url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.client_options.application_name = APPLICATION_NAME
calendar.authorization = authorize
event = {
summary: 'Events',
attendees: [
{email: 'lpage#example.com'},
{email: 'sbrin#example.com'},
],
start: {
date_time: '2015-05-28T09:00:00-07:00',
time_zone: 'America/Los_Angeles',
},
end: {
date_time: '2015-05-28T17:00:00-07:00',
time_zone: 'America/Los_Angeles',
}
}
event = calendar.insert_event('primary', event, send_notifications: true)
and don't forget to run this first:
gem install google-api-client
and also to create these files with the correct authentication information
credentials.json
token.yaml
and to figure out your user_id.
I'm setting up an API integration in my rails application with the Facebook Ads/Marketing API. I'm attempting to test very basic options with my Sandbox Ad Account and cannot seem to get them to work. This is error I keep getting:
FacebookAds::ClientError: Unsupported post request.
Object with ID '119033245616727' does not exist, cannot be loaded due
to missing permissions, or does not support this operation.
Please read the Graph API documentation at
https://developers.facebook.com/docs/graph-api: (fbtrace_id: GyiFjx24NY/)
from /Users/kelly/.rvm/gems/ruby-2.3.0/gems/facebookads-0.2.11.0/lib/facebook_ads/api_request.rb:67:in `create_response'
To run the test, I used their Marketing API quickstart to get my access token, app secret and ad account id.
This is my rails config:
Gemfile:
gem 'facebookads' #https://github.com/facebook/facebook-ruby-ads-sdk
My Test Module:
module Advertising
module Facebook
class API
attr_accessor :access_token
attr_accessor :app_secret
attr_accessor :ad_account_id
def initialize
#access_token = 'EAAYVZBezhACwBAKwMk7fhAJO2WFlUeUaCcASveD9gb6ZCKBzEAJIzDToagt4Vy5n6Ue9QpOwyb0SWYCSHHf4A2jbdTOb99GTBjhSOu5WnU03mnKymd2YgmquOJHg4lPx3iZBonYTzriU27OnlBXDMXdIZApwt45SSqQ8SLs5xaMM3lVEsm0r6WXSoos5yiOiqfMB83SfnntzUzqkEywQ'
#app_secret = '15326d2073b04504ef72267bf36a8bd4'
#ad_account_id = '119033245616727'
end
def test1
FacebookAds.configure do |config|
config.access_token = #access_token
config.app_secret = #app_secret
end
ad_account = FacebookAds::AdAccount.get(ad_account_id)
ad_account.campaigns.create(
objective: 'LINK_CLICKS',
status: 'PAUSED',
buying_type: 'AUCTION',
name: 'My Campaign'
)
end
def test2
# With session
session = FacebookAds::Session.new(access_token: #access_token, app_secret: #app_secret)
ad_account = FacebookAds::AdAccount.get(ad_account_id, session)
puts "This is my account name: #{ad_account.name}"
end
end
end
end
Then I'm running this in the rails console:
ad = Advertising::Facebook::API.new()
ad.test1
# OR
ad.test2
This is a newly created facebook app. These are the settings:
Status: In Development
App ID: 1713013025472556
App Secret: 15326d2073b04504ef72267bf36a8bd4
I added the Marketing API to the products section and created a Sandbox Ad Account called T2 Sandbox (119033245616727).
When setting your ad_account_id, add 'act_' in front of the ID. As the SDK will not do this for you.
I am new to RubyOnRails and SoundCloud.
I want to integrate SoundCloud API in my ruby on rails application.
For this I have registered on SoundCloud And I got the ClientID and ClientSecret. Also I have downloaded the SDK.
Now I have copied the files and folders from lib and spec directory to my applications lib and spec directory. Also I have added gem 'soundcloud' in the Gemfile.
After this I made simple code (copied from doc) in My Interactor:
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => YOUR_CLIENT_ID)
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
But here I'm getting the error -
uninitialized constant MyApp::Interactors::MyInteractor::MyAction::SoundCloud
I followed the steps from APIDoc. Is there any step by step example for integrating SoundCloud in Ruby on Rails so that I can follow?
How can I resolve this error?
MyInteracor.rb
module MyApp
module Interactors
module MyInteractor
class MyAction < Struct.new(:user, :params)
def run
# SoundCloud
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => 'my-client-id')
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
end
end
end
end
end
There's a typo in the soundcloud github page change the line:
client = SoundCloud.new(:client_id => 'my-client-id')
to
client = Soundcloud.new(:client_id => 'my-client-id')
[notice the lowercase c in Soundcloud]
Also you are going to need your client secret for SoundCloud's API to verify you.
Perhaps put client method and in it have client = SoundCloud.new(your-client-id,your-secret-key-your-redirect-uri) in a controller or helper with your client_id, client_secret, and redirect uri values protected in a .env file.
I think by leaving out your redirect_uri and client secret you might be getting this error in MyInteractor.rb
Hope this helps