Comfyのメタデータ処理
from 20241213
Comfyのメタデータ処理
ComfyUIが画像を保存する際の処理を追いかける
nodes.pyにある
https://github.com/comfyanonymous/ComfyUI/blob/563291ee515bd71065a6e16d9e7dfb97fd747b7c/nodes.py#L1537-L1542
code:python
metadata = PngInfo()
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfox))
PIL.PngImagePlugin.PngInfo()を使ってメタデータを読み書きする
リファレンスはこれ
メタデータは少なくとも以下に相当するプロパティを見ればOK
prompt
extra_pnginfo(総称)
workflow: xxxなどのプロパティが入る
extra_pnginfoに相当するパラメータの数は可変
もし何か他のフォーマットに移植する場合は取りこぼしがないようにしたい
どうやって判断する?
それぞれの定義はnode_typing.pyにある
双方で同じ値を持つノードが保存される場合もあるみたい
prompt
... is the complete prompt sent by the client to the server. See the prompt object for a full description.
extra_pnginfo
... is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node).
ExifToolを使って確認する
code:sh
cat ComfyUI_00043_.png | exiftool - -b -workflow | jq -C | less -R
code:sh
cat ComfyUI_00043_.png | exiftool - -b -workflow | jq -C | less -R
見た感じComfy本体ではPNG以外以外の保存形式には対応していない
だからcomfy-image-saverがあるというわけか
Save image with generation metadata on ComfyUI
これの処理も追う
https://github.com/giriss/comfy-image-saver/blob/main/nodes.py#L241-L262
code:python
if extension == 'png':
metadata = PngInfo()
metadata.add_text("parameters", comment)
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfox))
filename = f"{filename_prefix}.png"
img.save(os.path.join(output_path, filename), pnginfo=metadata, optimize=True)
else:
filename = f"{filename_prefix}.{extension}"
file = os.path.join(output_path, filename)
img.save(file, optimize=True, quality=quality_jpeg_or_webp, lossless=lossless_webp)
exif_bytes = piexif.dump({
"Exif": {
piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(comment, encoding="unicode")
},
})
piexif.insert(exif_bytes, file)
code:python
comment = f"{handle_whitespace(positive)}\nNegative prompt: {handle_whitespace(negative)}\nSteps: {steps}, Sampler: {sampler_name}{f'_{scheduler}' if scheduler != 'normal' else ''}, CFG Scale: {cfg}, Seed: {seed_value}, Size: {width}x{height}, Model hash: {modelhash}, Model: {basemodelname}, Version: ComfyUI"
追加のパラメーターにcommentがある
これでA1111互換にしている
save_files()から渡される
見た感じPNGではparameters: <comment>に、そうでない形式の場合はExifに突っ込んでいる
JPEG、WebPならExifでもおk
とくにWebPでは
https://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_WEBP_files
AVIFやHEIFは?