Rails Active Storage + AWS Rekognition:如何获取IO文件

问题描述 投票:0回答:1

我正在尝试将AWS Rekognition集成到我的Rails应用程序中。用户通过Active Storage上传其头像后,Rekognition应显示有关它的一些信息。

def update
  respond_to do |format|
    if @user.update(user_params)
      if @user.images.attached?
        Aws.config.update({
            region: 'us-west-2',
            credentials: Aws::Credentials.new('ACCESS_KEY', 'SECRET_KEY')
          })
          rekognition = Aws::Rekognition::Client.new(region: Aws.config[:region], credentials: Aws.config[:credentials])
          img = @user.images.first. # original was: File.read(ARGV.first)

          #detect faces  
          resp = rekognition.detect_faces({
            image: { bytes: img },
            attributes: ["ALL"], # What attributes to return
          })
          resp.face_details[0].emotions.each do |emo|
            puts emo.type + " " + emo.confidence.to_i.to_s #=> Strings "HAPPY", "SAD", "ANGRY"
          end
      end
   end
end

但是,我得到了错误

expected params[:image][:bytes] to be a String or IO object, got value #<ActiveStorage::Attachment id: 4, name: "images", record_type: "User", record_id: 47, blob_id: 9, created_at: ""> (class: ActiveStorage::Attachment) instead.

如何将图像文件属性导入AWS Rekognition?

ruby-on-rails amazon-rekognition
1个回答
1
投票

将图像传递给Aws::Rekognition有两种方法。

  1. AWS S3图像网址和名称
resp = rekognition.detect_faces(
        {image:
          {s3_object:
            {bucket: `bucket name`,
              name: `pull path of file`,
            },
          }, attributes: ['ALL'],
        }
      )
  1. 通过Image对象
rekognition.detect_faces({
         image: { bytes: File.read(`path of file`) }
       })

在您的情况下,您传递的是无法通过AWS解析的ActiveStorage对象。这就是它抛出错误的原因。

© www.soinside.com 2019 - 2024. All rights reserved.