Module: VivlioStarter::CLI::PreProcessCommands::ImageGenerator
- Defined in:
- lib/vivlio_starter/cli/pre_process/image_generator.rb
Overview
テーマ画像バリアント生成モジュール
Constant Summary collapse
- DEFAULT_WAIFU2X_BIN =
File.('~/.local/bin/waifu2x/waifu2x-ncnn-vulkan')
- FRONTISPIECE_WAIFU2X_NOISE =
1- FRONTISPIECE_SCALE =
2- FRONTISPIECE_TARGET_WIDTH =
frontispiece推奨横幅
2880- FRONTISPIECE_WEBP_QUALITY =
90
Class Method Summary collapse
-
.command_available?(cmd) ⇒ Boolean
コマンドが利用可能かチェック.
-
.convert_to_webp(source_path, target_path, target_width:, webp_quality:, label:) ⇒ Object
画像(PNG 等)を最終的な WebP(透過・指定幅・品質)へ変換して target_path に書き出す.
-
.ensure_magick_available! ⇒ Object
ImageMagick が利用可能かチェック.
-
.ensure_variant_generated(source_path, variant) ⇒ Object
バリアント画像が存在しなければ生成。 生成物はソースの隣ではなく生成キャッシュ .cache/vs/theme-images/ へ (images root からの相対サブパスを維持・generated-assets 移設仕様 §2)。 waifu2x を伴う高コスト処理のため、生成済みチェックが実質のメモ化になる。.
- .frontispiece_variants ⇒ Object
-
.generate_diagonal_variant(input_png, output_png, ratio) ⇒ Object
対角線分割バリアントを生成.
-
.generate_frontispiece_and_ornament_from(image_spec, fuzz: nil, waifu2x: DEFAULT_WAIFU2X_BIN, waifu2x_args: [], waifu2x_noise: FRONTISPIECE_WAIFU2X_NOISE, scale: FRONTISPIECE_SCALE, target_width: FRONTISPIECE_TARGET_WIDTH, webp_quality: FRONTISPIECE_WEBP_QUALITY, keep_intermediate: false) ⇒ Object
frontispiece と ornament を生成.
-
.generate_variant_output(input_png, target_path, variant:, waifu2x_available:, waifu2x:, waifu2x_args:, waifu2x_noise:, scale:, target_width:, webp_quality:, keep_intermediate:) ⇒ Object
バリアント出力を生成 rubocop:disable Lint/UnusedMethodArgument.
-
.resolve_image_reference(images_root, image_spec) ⇒ Object
画像参照を解決.
-
.run_command!(cmd, label:, stream_output: false) ⇒ Object
コマンドを実行.
-
.trim_image_to(source_path, destination_path, fuzz) ⇒ Object
画像をトリミング.
Class Method Details
.command_available?(cmd) ⇒ Boolean
コマンドが利用可能かチェック
134 135 136 137 138 139 140 141 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 134 def command_available?(cmd) return File.executable?(cmd) if cmd.include?(File::SEPARATOR) ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).any? do |path| candidate = File.join(path, cmd) File.executable?(candidate) end end |
.convert_to_webp(source_path, target_path, target_width:, webp_quality:, label:) ⇒ Object
画像(PNG 等)を最終的な WebP(透過・指定幅・品質)へ変換して target_path に書き出す
297 298 299 300 301 302 303 304 305 306 307 308 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 297 def convert_to_webp(source_path, target_path, target_width:, webp_quality:, label:) convert_cmd = [ 'magick', source_path, '-alpha', 'set', '-background', 'none', '-transparent', 'white', '-resize', "#{target_width}x", '-quality', webp_quality.to_s, target_path ] run_command!(convert_cmd, label: "WebP 変換 (#{label})") end |
.ensure_magick_available! ⇒ Object
ImageMagick が利用可能かチェック
126 127 128 129 130 131 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 126 def ensure_magick_available! _out, status = Open3.capture2('magick', '-version') raise 'ImageMagick (magick) が見つかりません。インストールを確認してください。' unless status.success? rescue Errno::ENOENT raise 'magick コマンドが見つかりません。ImageMagick をインストールしてください。' end |
.ensure_variant_generated(source_path, variant) ⇒ Object
バリアント画像が存在しなければ生成。 生成物はソースの隣ではなく生成キャッシュ .cache/vs/theme-images/ へ (images root からの相対サブパスを維持・generated-assets 移設仕様 §2)。 waifu2x を伴う高コスト処理のため、生成済みチェックが実質のメモ化になる。
56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 56 def ensure_variant_generated(source_path, variant) images_root = ThemeImageResolver.theme_images_root relative = source_path.sub(%r{\A#{Regexp.escape(images_root)}/}, '') return nil if relative.empty? base = relative.sub(/\.[^.]+\z/, '') target = File.join(ThemeImageResolver.theme_images_cache_root, "#{base}_#{variant}.webp") return target if File.exist?(target) success = generate_frontispiece_and_ornament_from(relative) success ? target : nil end |
.frontispiece_variants ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 44 def frontispiece_variants portrait_ratio = ThemeImageResolver.binding_safe_portrait_ratio { portrait: portrait_ratio, landscape: (1.0 / 2.39) # ornament用 2.39:1(シネマスコープ) } end |
.generate_diagonal_variant(input_png, output_png, ratio) ⇒ Object
対角線分割バリアントを生成
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 185 def generate_diagonal_variant(input_png, output_png, ratio) dims, status = Open3.capture2('magick', 'identify', '-format', '%w %h', input_png) raise "寸法取得に失敗しました: #{input_png}" unless status.success? width_str, height_str = dims.strip.split width = width_str.to_i height = height_str.to_i raise "不正な寸法です: #{input_png}" if width <= 0 || height <= 0 ratio = ratio.to_f current_ratio = height.to_f / width if ratio >= current_ratio new_width = width new_height = (width * ratio).round bottom_x_offset = 0 bottom_y_offset = new_height - height else new_height = height new_width = (height / ratio).round bottom_x_offset = new_width - width bottom_y_offset = 0 end top_path = output_png.sub(/\.png\z/, '_top.png') bottom_path = output_png.sub(/\.png\z/, '_bottom.png') top_cmd = [ 'magick', input_png, '-background', 'white', '-flatten', '(', '-size', "#{width}x#{height}", 'xc:none', '-fill', 'white', '-draw', "polygon 0,0 #{width},0 0,#{height}", ')', '-compose', 'CopyAlpha', '-composite', "PNG32:#{top_path}" ] bottom_cmd = [ 'magick', input_png, '-background', 'white', '-flatten', '(', '-size', "#{width}x#{height}", 'xc:none', '-fill', 'white', '-draw', "polygon #{width},#{height} #{width},0 0,#{height}", ')', '-compose', 'CopyAlpha', '-composite', "PNG32:#{bottom_path}" ] composite_cmd = [ 'magick', '-size', "#{new_width}x#{new_height}", 'xc:white', '-alpha', 'set', '+repage', top_path, '-geometry', '+0+0', '-compose', 'Over', '-composite', bottom_path, '-geometry', "+#{bottom_x_offset}+#{bottom_y_offset}", '-compose', 'Over', '-composite', '-transparent', 'white', "PNG32:#{output_png}" ] run_command!(top_cmd, label: '対角線分割 (上)') run_command!(bottom_cmd, label: '対角線分割 (下)') run_command!(composite_cmd, label: '対角線分割 (合成)') ensure FileUtils.rm_f(top_path) FileUtils.rm_f(bottom_path) end |
.generate_frontispiece_and_ornament_from(image_spec, fuzz: nil, waifu2x: DEFAULT_WAIFU2X_BIN, waifu2x_args: [], waifu2x_noise: FRONTISPIECE_WAIFU2X_NOISE, scale: FRONTISPIECE_SCALE, target_width: FRONTISPIECE_TARGET_WIDTH, webp_quality: FRONTISPIECE_WEBP_QUALITY, keep_intermediate: false) ⇒ Object
frontispiece と ornament を生成
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 70 def generate_frontispiece_and_ornament_from(image_spec, fuzz: nil, waifu2x: DEFAULT_WAIFU2X_BIN, waifu2x_args: [], waifu2x_noise: FRONTISPIECE_WAIFU2X_NOISE, scale: FRONTISPIECE_SCALE, target_width: FRONTISPIECE_TARGET_WIDTH, webp_quality: FRONTISPIECE_WEBP_QUALITY, keep_intermediate: false) ensure_magick_available! images_root = File.join(Common::STYLESHEETS_DIR, 'images') source_path = resolve_image_reference(images_root, image_spec) basename = File.basename(source_path, '.*') # 出力先はソースの隣ではなく生成キャッシュ(相対サブパス維持・移設仕様 §2)。 # bundled/sakura.webp → theme-images/bundled/、myphoto.png → theme-images/ 直下。 relative_dir = File.dirname( File.(source_path).delete_prefix("#{File.(images_root)}/") ) base_dir = File.join(ThemeImageResolver.theme_images_cache_root, relative_dir == '.' ? '' : relative_dir) Common.log_action("frontispiece/ornament 生成: #{image_spec} → #{basename}_portrait/landscape.webp") waifu2x_available = waifu2x && !waifu2x.strip.empty? && command_available?(waifu2x) Common.log_warn("waifu2x (#{waifu2x}) が見つかりません。ImageMagick のみで生成します。") unless waifu2x_available Dir.mktmpdir('frontispiece-one') do |tmpdir| trimmed_path = File.join(tmpdir, "#{basename}_trimmed.png") trim_image_to(source_path, trimmed_path, fuzz) frontispiece_variants.each do |variant, ratio| variant_png = File.join(tmpdir, "#{basename}_#{variant}.png") generate_diagonal_variant(trimmed_path, variant_png, ratio) target_path = File.join(base_dir, "#{basename}_#{variant}.webp") generate_variant_output( variant_png, target_path, variant: variant, waifu2x_available: waifu2x_available, waifu2x: waifu2x, waifu2x_args: waifu2x_args, waifu2x_noise: waifu2x_noise, scale: scale, target_width: target_width, webp_quality: webp_quality, keep_intermediate: keep_intermediate ) Common.log_success("生成しました: #{target_path}") end end true rescue StandardError => e Common.log_error("frontispiece/ornament 生成に失敗しました: #{e.}") false end |
.generate_variant_output(input_png, target_path, variant:, waifu2x_available:, waifu2x:, waifu2x_args:, waifu2x_noise:, scale:, target_width:, webp_quality:, keep_intermediate:) ⇒ Object
バリアント出力を生成 rubocop:disable Lint/UnusedMethodArgument
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 245 def generate_variant_output(input_png, target_path, variant:, waifu2x_available:, waifu2x:, waifu2x_args:, waifu2x_noise:, scale:, target_width:, webp_quality:, keep_intermediate:) # rubocop:enable Lint/UnusedMethodArgument FileUtils.mkdir_p(File.dirname(target_path)) variant_label = File.basename(target_path) unless waifu2x_available convert_to_webp(input_png, target_path, target_width:, webp_quality:, label: variant_label) return end # waifu2x 経路: アルファ抽出 → waifu2x 拡大 → アルファ拡大 → 再合成 の中間 PNG は # tmpdir に隔離する。base_dir(bundled/)へ書かないため、途中で例外が起きても # ブロック離脱で自動削除され、bundled/ に中間生成物が残らない。 Dir.mktmpdir('frontispiece-variant') do |tmpdir| stem = File.join(tmpdir, File.basename(target_path, '.webp')) alpha_path = "#{stem}_alpha.png" alpha_scaled_path = "#{stem}_alpha_x#{scale}.png" color_path = "#{stem}_color_x#{scale}.png" merged_path = "#{stem}_merged_x#{scale}.png" run_command!( ['magick', input_png, '-alpha', 'extract', "PNG32:#{alpha_path}"], label: "アルファ抽出 (#{variant_label})" ) waifu_cmd = [waifu2x, '-i', input_png, '-o', color_path, '-n', waifu2x_noise.to_s, '-s', scale.to_s] + waifu2x_args run_command!( waifu_cmd, label: "waifu2x (#{variant_label})", stream_output: Common.current_log_level >= 3 ) scale_percent = format('%.2f%%', scale.to_f * 100) run_command!( ['magick', alpha_path, '-filter', 'catrom', '-resize', scale_percent, "PNG32:#{alpha_scaled_path}"], label: "アルファ拡大 (#{variant_label})" ) run_command!( ['magick', color_path, alpha_scaled_path, '-compose', 'CopyAlpha', '-composite', "PNG32:#{merged_path}"], label: "アルファ再適用 (#{variant_label})" ) convert_to_webp(merged_path, target_path, target_width:, webp_quality:, label: variant_label) end end |
.resolve_image_reference(images_root, image_spec) ⇒ Object
画像参照を解決
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 144 def resolve_image_reference(images_root, image_spec) spec = image_spec.to_s.strip raise '画像指定が空です' if spec.empty? normalized_root = File.(images_root) base_dir = normalized_root.end_with?(File::SEPARATOR) ? normalized_root : normalized_root + File::SEPARATOR relative = spec.sub(%r{^/+}, '') absolute = File.(relative, base_dir) unless absolute == normalized_root || absolute.start_with?(normalized_root + File::SEPARATOR) raise "画像指定が不正です: #{spec}" end return absolute if File.exist?(absolute) if File.extname(relative).empty? %w[.webp .png .jpg .jpeg].each do |ext| candidate = absolute + ext return candidate if File.exist?(candidate) end else stem = absolute.sub(/\.[^.]+\z/, '') exts = %w[.webp .png .jpg .jpeg] ([absolute] + exts.map { |ext| "#{stem}#{ext}" }).each do |candidate| return candidate if File.exist?(candidate) end end raise "画像が見つかりません: #{spec}" end |
.run_command!(cmd, label:, stream_output: false) ⇒ Object
コマンドを実行
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 311 def run_command!(cmd, label:, stream_output: false) Common.log_action(" $ #{Shellwords.join(cmd.map(&:to_s))}") if stream_output # stderr は常に /dev/null へ捨てる(waifu2x-ncnn-vulkan 等のデバイス情報ログを抑制) success = system(*cmd, err: File::NULL) raise "#{label} に失敗しました" unless success return end # stderr は /dev/null へ捨てる。エラー時のみ再取得して報告する stdout_str, status = Open3.capture2(*cmd, err: File::NULL) if status.success? if Common.current_log_level >= 3 && stdout_str && !stdout_str.strip.empty? stdout_str.each_line { |line| Common.log_debug("#{label}: #{line.rstrip}") } end return end # 失敗時は stderr も取得してエラーメッセージに含める _out, stderr_str, = Open3.capture3(*cmd) combined = [stdout_str, stderr_str].map(&:to_s).reject(&:empty?).join("\n") = combined.empty? ? "#{label} に失敗しました" : "#{label} に失敗しました:\n#{combined}" raise end |
.trim_image_to(source_path, destination_path, fuzz) ⇒ Object
画像をトリミング
176 177 178 179 180 181 182 |
# File 'lib/vivlio_starter/cli/pre_process/image_generator.rb', line 176 def trim_image_to(source_path, destination_path, fuzz) FileUtils.mkdir_p(File.dirname(destination_path)) command = ['magick', source_path, '-alpha', 'set'] command += ['-fuzz', fuzz] if fuzz command += ['-bordercolor', 'none', '-border', '1x1', '-trim', '+repage', "PNG32:#{destination_path}"] run_command!(command, label: "トリミング (#{File.basename(source_path)})") end |