LoginSignup
1
0

More than 5 years have passed since last update.

ファイルリストを指定サイズ以下になるようにグルーピングする

Posted at

言葉で説明すると分かりにくい。
例えば、あるディレクトリに画像ファイルが100個あるとき、ファイルサイズの合計が10MB以下になるように複数のグループに分けたいときに使うクラスメソッドです。

なんでこんなことをしたいかというと、Google Cloud Vision API に画像からテキストを抽出する OCR 機能があり、この API は複数ファイルを処理できますが最大で 10MB までしか受け付けてくれません。
ファイルが100個あって繰り返しAPIを呼び出すときにうまく分割しながら送るためにこのグルーピングが必要になります。

MAX_POST_SIZE = 10 * 1024 * 1024 # 10MB

files = ['/path/to/1.png', '/path/to/2.png', '/path/to.3.png', ... ];
files_grouped = File.group_into_chunk(files, MAX_POST_SIZE)
files_grouped.each do |files|
  # ここで files を Vision API に送る
end
class File
  # ファイルリストを `chunk_size` 以下のファイルサイズになるように分割する
  # File.group_into_chunk(paths, 10 * 1024 * 1024).each do |files|
  #   # files => ファイルサイズの合計が10MB以下になるように分割されたファイルリスト
  # end
  def self.group_into_chunk(files, chunk_size)
    files.inject([]) do |groups, file|
      group = groups.last
      if group.nil? || group.sum { |f| File.size(f) } + File.size(file) > chunk_size then
        group = []
        groups.push group
      end
      group.push file 
      groups
    end
  end
end
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0