googleapis / google-cloud-ruby

Google Cloud Client Library for Ruby
https://googleapis.github.io/google-cloud-ruby/
Apache License 2.0
1.35k stars 543 forks source link

Unable to run text_detection with image arguments #26470

Closed itsmeritesh closed 1 month ago

itsmeritesh commented 1 month ago

Hi folks, I'm building a simple text detection service but keep hitting a dead end in terms of # of arguments or type. Here's my code.

def extract(image_path)
    ENV['GOOGLE_APPLICATION_CREDENTIALS'] ||= ('/cert.json').to_s

    Google::Cloud::Vision.configure do |config|
      config.credentials = ENV["GOOGLE_APPLICATION_CREDENTIALS"]
      puts "=== credentials: #{config.credentials}"
    end

    vision = Google::Cloud::Vision.image_annotator

    File.open(image_path, "rb") do |image_file|
      response = vision.safe_search_detection image: image_file
      safe_search = response.responses.first.safe_search_annotation

      puts "Adult: #{safe_search.adult}"
      puts "Violence: #{safe_search.violence}"

      text_detector = vision.text_detection(image: image_file).   #crashes here
      texts = text_detector.responses.map(&:text_annotations).flatten.map(&:description)
      puts texts.join(" ")
      texts.join(" ")
    end

  end

I get different errors like Invalid # of arguments, wrong file type etc, there's not much public code to go by. Is there something obvious I'm missing? Thanks.

dazuma commented 1 month ago

Most likely the actual crash you're getting in the code above is because the image_file object has already been read by your previous call to safe_search_detection, so it's at EOF when you make the text_detection call. Try calling image_file.rewind to reset the file pointer before calling text_detection. Or alternately, just read the file contents into a string first, and pass the string into both calls.

The other thing I notice from your code is, the call to Google::Cloud::Vision.configure should not be necessary. The client library authentication already understands the GOOGLE_APPLICATION_CREDENTIALS environment variable. (That is, it implements https://cloud.google.com/docs/authentication/application-default-credentials for you.)

dazuma commented 1 month ago

In the future, consider posting usage questions to StackOverflow. Google Support generally doesn't monitor these GitHub repositories, and it's uncommon that you'll get a timely response here.

itsmeritesh commented 1 month ago

gThanks @dazuma. Appreciate your help here. I'll try these out now. Appreciate your note on the credentials bit too.