Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3bb55f2dc | ||
|
|
fa31644c4c | ||
|
|
0c023c7ec9 | ||
|
|
9943a61619 | ||
|
|
1d509c885e |
@@ -103,7 +103,7 @@ Pick an open ComfyUI window and a node, then review the exact before and after.
|
||||
|
||||
### Deletes you can review
|
||||
|
||||
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
|
||||
Choose what happens to the files before anything is removed: remove the image from the library and leave the file on disk, or on Linux and macOS also move it to the system trash. On a Linux or BSD server you can also delete the files permanently, for headless servers where a trash only fills up the disk; those files can't be recovered. On Windows, images can only be removed from the library. A safety backup of the database is on by default, and removed images can be brought back.
|
||||
|
||||

|
||||
|
||||
@@ -230,6 +230,7 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
|
||||
## Known limits
|
||||
|
||||
- **Trash is Linux and macOS only.** Windows has no Recycle Bin option, because the bin can delete large files permanently without warning. On Windows you can only remove an image from the library, and the file stays on disk. Where a move to the trash isn't possible on Linux or macOS, the dialog lists why for each file.
|
||||
- **Permanent delete is Linux and BSD only,** and can't be undone. The safety backup brings back the library records, not the files.
|
||||
- **Show in folder** opens the file manager on the machine running ComfyUI, not necessarily the one with your browser.
|
||||
- **Returned images** get their prompt links back, but not their tags, categories, collections or favorites.
|
||||
- **Inspect a file** doesn't add the file to your library.
|
||||
|
||||
+13
@@ -491,6 +491,19 @@ differ are files whose pixel data is undecodable or cut short: legacy found
|
||||
nothing, the walk keeps the text before the pixels. Animated PNGs still use
|
||||
`.text`.
|
||||
|
||||
WebP, AVIF and JPEG keep the same records in EXIF, not in text chunks.
|
||||
ComfyUI's `SaveAnimatedWEBP` writes `prompt:{json}` to EXIF tag 0x0110, then
|
||||
`workflow:{json}` and every other `extra_pnginfo` key to 0x010F and down; the
|
||||
AVIF writer uses that layout. `utils/exif_text.py` answers the `png_text` shape
|
||||
through Pillow's `getexif()`, and both metadata readers fall back to it when a
|
||||
file has no text chunks. Only a value shaped like a record counts (a key, a
|
||||
colon, then a JSON object, array or string), so camera EXIF stays out.
|
||||
`tests/test_exif_text.py` writes real still and animated WebP files, AVIF (where
|
||||
Pillow has it) and JPEG in that layout; `tests/test_metadata_extraction.py` and
|
||||
`tests/test_api_core.py` hold the two readers to it. No scan, monitor or
|
||||
gallery list collects `.avif` yet, so AVIF files are read correctly but never
|
||||
reach the readers; #652 tracks AVIF as a media type.
|
||||
|
||||
Image work runs on PromptManager's own threads (#523). glibc keeps each thread's
|
||||
malloc arena at its high-water mark, so image buffers spread over the default
|
||||
executor's threads stay resident. Interactive image work (view previews behind their
|
||||
|
||||
+4
-2
@@ -99,19 +99,21 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
|
||||
"prepend_text": (
|
||||
IO.STRING,
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"Text to prepend to the main prompt (connected STRING "
|
||||
"nodes will be added before the main text)"
|
||||
)
|
||||
),
|
||||
},
|
||||
),
|
||||
"append_text": (
|
||||
IO.STRING,
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"Text to append to the main prompt (connected STRING "
|
||||
"nodes will be added after the main text)"
|
||||
)
|
||||
),
|
||||
},
|
||||
),
|
||||
"save_to_library": SAVE_TO_LIBRARY_INPUT,
|
||||
|
||||
+7
-3
@@ -89,6 +89,7 @@ from .source_rescope import SourceRescopeMixin
|
||||
|
||||
try:
|
||||
from ...database.operations import PromptDatabase
|
||||
from ...utils.exif_text import exif_text
|
||||
from ...utils.logging_config import get_logger
|
||||
from ...utils.native_memory import release_free_memory
|
||||
from ...utils.png_text import png_text
|
||||
@@ -100,6 +101,7 @@ except ImportError:
|
||||
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
)
|
||||
from database.operations import PromptDatabase
|
||||
from utils.exif_text import exif_text
|
||||
from utils.logging_config import get_logger
|
||||
from utils.native_memory import release_free_memory
|
||||
from utils.png_text import png_text
|
||||
@@ -1018,9 +1020,11 @@ class PromptManagerAPI(
|
||||
return []
|
||||
|
||||
def _extract_comfyui_metadata(self, image_path):
|
||||
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
|
||||
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
|
||||
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523).
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523);
|
||||
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
|
||||
``utils.exif_text``.
|
||||
|
||||
Videos go through ffprobe (see utils/video_metadata). Unreadable files
|
||||
are a warning, not an error: a scan over a large output tree meets
|
||||
@@ -1030,7 +1034,7 @@ class PromptManagerAPI(
|
||||
return read_video_metadata(image_path)
|
||||
try:
|
||||
with Image.open(image_path) as img:
|
||||
return png_text(img)
|
||||
return png_text(img) or exif_text(img)
|
||||
except Exception as e:
|
||||
self.logger.warning(
|
||||
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
|
||||
|
||||
@@ -290,7 +290,7 @@ class ImageDeleteMixin:
|
||||
acted.append(target)
|
||||
counted = db.count_removal_records([t["removal"] for t in acted])
|
||||
library_count = len(acted)
|
||||
permanent_supported = isinstance(trash.BACKEND, trash.FreedesktopBackend)
|
||||
permanent_supported = permanent_delete_supported()
|
||||
public = {
|
||||
"operation": IMAGE_DELETE,
|
||||
"scope": {"count": library_count, "label": "images"},
|
||||
@@ -570,6 +570,12 @@ class ImageDeleteMixin:
|
||||
return [path for path in paths if not removed(path)]
|
||||
|
||||
|
||||
def permanent_delete_supported() -> bool:
|
||||
"""Permanent delete is offered only with the Freedesktop trash backend
|
||||
(Linux/BSD servers); the review and the apply both ask here (#644)."""
|
||||
return isinstance(trash.BACKEND, trash.FreedesktopBackend)
|
||||
|
||||
|
||||
def parse_mode(value):
|
||||
"""The apply's ``mode``, or None when it is not one of MODES."""
|
||||
return value if isinstance(value, str) and value in MODES else None
|
||||
|
||||
@@ -516,7 +516,7 @@ class MaintenanceRoutesMixin:
|
||||
# ── apply ─────────────────────────────────────────────────────────
|
||||
|
||||
async def apply_maintenance_plan(self, request):
|
||||
from .image_delete import IMAGE_DELETE, parse_mode
|
||||
from .image_delete import IMAGE_DELETE, parse_mode, permanent_delete_supported
|
||||
|
||||
data, error = await self._read_maintenance_body(request, ("token", "mode"))
|
||||
if error is not None:
|
||||
@@ -531,7 +531,12 @@ class MaintenanceRoutesMixin:
|
||||
if plan.operation == IMAGE_DELETE:
|
||||
mode = parse_mode(data.get("mode"))
|
||||
if mode is None:
|
||||
return _invalid('mode must be "library" or "trash"')
|
||||
return _invalid('mode must be "library", "trash" or "permanent"')
|
||||
if mode == "permanent" and not permanent_delete_supported():
|
||||
# The review never offers it here; refuse a direct call (#644).
|
||||
return _invalid(
|
||||
"Permanent delete is only available on Linux and BSD servers"
|
||||
)
|
||||
elif "mode" in data:
|
||||
return _invalid("Unknown field: mode")
|
||||
store = self._maintenance_plans
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "promptmanager"
|
||||
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
|
||||
version = "3.6.0"
|
||||
version = "3.7.1"
|
||||
license = {file = "LICENSE"}
|
||||
requires-python = ">=3.12"
|
||||
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
|
||||
|
||||
@@ -565,9 +565,11 @@ test('URLs and media end with their owning session', async ({ page }) => {
|
||||
// Replacement.
|
||||
await choose(page, parityPng('f02.png'));
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible();
|
||||
// #653: a video still starting (inline, or in the viewer the selection opened) is held until it settles or
|
||||
// STARTING_VIDEO_MS (15 s) passes, so its release can follow the new preview: wait for it, never check once.
|
||||
let state = await urls(page);
|
||||
expect(state.revoked).toEqual([state.created[0]]);
|
||||
expect(await page.evaluate(() => window.__loads)).toBeGreaterThanOrEqual(1);
|
||||
await expect.poll(async () => (await urls(page)).revoked, { timeout: 20000 }).toEqual([state.created[0]]);
|
||||
await expect.poll(() => page.evaluate(() => window.__loads), { timeout: 20000 }).toBeGreaterThanOrEqual(1);
|
||||
// Route change, from the page (D155: the selection opened the viewer, which makes the sidebar inert).
|
||||
await closeOpened(page);
|
||||
await page.locator('aside.sidebar nav').getByRole('link', { name: 'Overview', exact: true }).click();
|
||||
|
||||
@@ -926,6 +926,24 @@ class TestMetadataParsing(unittest.TestCase):
|
||||
f.write(b"nope")
|
||||
self.assertEqual(self.api._extract_comfyui_metadata(garbage), {})
|
||||
|
||||
def test_extract_metadata_from_webp_exif(self):
|
||||
"""SaveAnimatedWEBP writes the records as EXIF, with no text chunks."""
|
||||
from PIL import Image
|
||||
|
||||
path = os.path.join(self.tmpdir, "m.webp")
|
||||
exif = Image.Exif()
|
||||
exif[0x0110] = 'prompt:{"1": {"class_type": "KSampler"}}'
|
||||
exif[0x010F] = 'workflow:{"nodes": [{"type": "CLIPTextEncode"}]}'
|
||||
Image.new("RGB", (1, 1)).save(path, "WEBP", exif=exif)
|
||||
|
||||
self.assertEqual(
|
||||
self.api._extract_comfyui_metadata(path),
|
||||
{
|
||||
"prompt": '{"1": {"class_type": "KSampler"}}',
|
||||
"workflow": '{"nodes": [{"type": "CLIPTextEncode"}]}',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -273,6 +273,12 @@ class TestNodeIntegration(unittest.TestCase):
|
||||
# Check optional inputs
|
||||
self.assertIn("search_text", input_types["optional"])
|
||||
|
||||
# Every optional STRING starts empty, so the schema offers "" and not
|
||||
# null: the composition sockets used to be the only ones without a
|
||||
# default, although the node already treats them as empty.
|
||||
for name in ("category", "tags", "search_text", "prepend_text", "append_text"):
|
||||
self.assertEqual(input_types["optional"][name][1]["default"], "", name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""ComfyUI's EXIF records: what WebP, AVIF and JPEG carry instead of text.
|
||||
|
||||
ComfyUI's SaveAnimatedWEBP writes ``prompt:{json}`` to EXIF tag 0x0110, then
|
||||
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down;
|
||||
the AVIF writer uses that layout too. Pillow exposes them only through
|
||||
``getexif()``, so a reader that looks at ``image.info`` or the text chunks
|
||||
finds nothing. These tests write real files in that layout.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from PIL import Image, features
|
||||
|
||||
from utils.exif_text import exif_text
|
||||
|
||||
PROMPT = {"1": {"class_type": "KSampler", "inputs": {"seed": 7}}}
|
||||
WORKFLOW = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "cat"}}]}
|
||||
PAIRS = [{"positive": "cat", "negative": "dog"}]
|
||||
|
||||
|
||||
def comfyui_exif(prompt=PROMPT, extra=None):
|
||||
"""The tags ComfyUI writes: the prompt on 0x0110, extra_pnginfo from 0x010F."""
|
||||
exif = Image.Exif()
|
||||
if prompt is not None:
|
||||
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
|
||||
tag = 0x010F
|
||||
for key, value in ({"workflow": WORKFLOW} if extra is None else extra).items():
|
||||
exif[tag] = f"{key}:{json.dumps(value)}"
|
||||
tag -= 1
|
||||
return exif
|
||||
|
||||
|
||||
class ExifTextCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.folder = folder.name
|
||||
|
||||
def write(self, name, image_format, exif, **options):
|
||||
path = os.path.join(self.folder, name)
|
||||
Image.new("RGB", (8, 8), "red").save(path, image_format, exif=exif, **options)
|
||||
return path
|
||||
|
||||
def read(self, path):
|
||||
with Image.open(path) as image:
|
||||
return exif_text(image)
|
||||
|
||||
|
||||
class TestComfyuiRecords(ExifTextCase):
|
||||
def test_reads_the_records_of_a_webp(self):
|
||||
path = self.write("a.webp", "WEBP", comfyui_exif())
|
||||
|
||||
self.assertEqual(
|
||||
self.read(path),
|
||||
{"prompt": json.dumps(PROMPT), "workflow": json.dumps(WORKFLOW)},
|
||||
)
|
||||
|
||||
def test_reads_an_animated_webp(self):
|
||||
# SaveAnimatedWEBP writes the first frame's EXIF and appends the rest.
|
||||
frames = [Image.new("RGB", (8, 8), color) for color in ("red", "blue")]
|
||||
path = os.path.join(self.folder, "anim.webp")
|
||||
frames[0].save(
|
||||
path,
|
||||
"WEBP",
|
||||
save_all=True,
|
||||
append_images=frames[1:],
|
||||
duration=100,
|
||||
exif=comfyui_exif(),
|
||||
)
|
||||
|
||||
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
|
||||
|
||||
def test_reads_every_extra_pnginfo_key_and_not_only_the_workflow(self):
|
||||
exif = comfyui_exif(
|
||||
extra={"workflow": WORKFLOW, "comfyassets_prompt_pairs": PAIRS}
|
||||
)
|
||||
path = self.write("pairs.webp", "WEBP", exif)
|
||||
|
||||
self.assertEqual(self.read(path)["comfyassets_prompt_pairs"], json.dumps(PAIRS))
|
||||
|
||||
def test_reads_a_jpeg_in_the_same_layout(self):
|
||||
# Not a core saver, but a third-party one reusing the convention.
|
||||
path = self.write("a.jpg", "JPEG", comfyui_exif())
|
||||
|
||||
self.assertEqual(self.read(path)["prompt"], json.dumps(PROMPT))
|
||||
|
||||
@unittest.skipUnless(features.check("avif"), "Pillow has no AVIF support")
|
||||
def test_reads_an_avif(self):
|
||||
path = self.write("a.avif", "AVIF", comfyui_exif())
|
||||
|
||||
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
|
||||
|
||||
|
||||
class TestOtherExif(ExifTextCase):
|
||||
def test_a_camera_exif_is_not_a_comfyui_record(self):
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "Canon" # Make
|
||||
exif[0x0110] = "Canon EOS R5" # Model
|
||||
exif[0x0131] = "GIMP 2.10.38" # Software
|
||||
exif[0x0132] = "2024:01:02 03:04:05" # DateTime
|
||||
path = self.write("camera.jpg", "JPEG", exif)
|
||||
|
||||
self.assertEqual(self.read(path), {})
|
||||
|
||||
def test_a_value_that_is_not_json_is_not_a_record(self):
|
||||
exif = Image.Exif()
|
||||
exif[0x010E] = "note:not json"
|
||||
exif[0x010D] = "make:Canon"
|
||||
path = self.write("notes.webp", "WEBP", exif)
|
||||
|
||||
self.assertEqual(self.read(path), {})
|
||||
|
||||
def test_a_png_answers_empty_its_records_are_text_chunks(self):
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
|
||||
info = PngInfo()
|
||||
info.add_text("workflow", json.dumps(WORKFLOW))
|
||||
path = os.path.join(self.folder, "a.png")
|
||||
Image.new("RGB", (8, 8)).save(path, pnginfo=info)
|
||||
|
||||
self.assertEqual(self.read(path), {})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -428,10 +428,31 @@ class TestPermanentMode(ImageDeleteTestCase):
|
||||
else:
|
||||
self.assertFalse(plan.get("permanent_delete_supported"))
|
||||
|
||||
async def test_permanent_is_refused_where_the_review_does_not_offer_it(self):
|
||||
"""#644: without the Freedesktop backend the apply answers 400 for
|
||||
"permanent" before any backup, and the file and its records stay."""
|
||||
from utils import trash
|
||||
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
self.link("a.png")
|
||||
with patch.object(trash, "BACKEND", trash.UnavailableBackend()):
|
||||
plan = await self.review(["a.png"])
|
||||
self.assertFalse(plan["permanent_delete_supported"])
|
||||
with patch("os.remove") as remove:
|
||||
body = await self.post(
|
||||
APPLY, {"token": plan["token"], "mode": "permanent"}, 400
|
||||
)
|
||||
remove.assert_not_called()
|
||||
self.assertIn("Linux", body["error"])
|
||||
self.assertTrue((self.output_dir / "a.png").exists())
|
||||
self.assertEqual(self.count("SELECT COUNT(*) FROM generated_images"), 1)
|
||||
|
||||
async def test_permanent_delete_removes_the_file(self):
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
if sys.platform == "win32":
|
||||
if not image_delete.permanent_delete_supported():
|
||||
self.skipTest("permanent delete is Linux/BSD only")
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
self.link("a.png")
|
||||
@@ -453,7 +474,7 @@ class TestPermanentMode(ImageDeleteTestCase):
|
||||
|
||||
fake_trash.uninstall()
|
||||
self.addCleanup(fake_trash.uninstall)
|
||||
if sys.platform == "win32":
|
||||
if not image_delete.permanent_delete_supported():
|
||||
self.skipTest("permanent delete is Linux/BSD only")
|
||||
self.write("a.png", b"aaa", mtime=1_000_000)
|
||||
self.link("a.png")
|
||||
|
||||
@@ -41,6 +41,31 @@ def _create_png(text_chunks=None, size=(64, 64)):
|
||||
return tmp.name
|
||||
|
||||
|
||||
def _create_webp(workflow=None, prompt=None, size=(64, 64)):
|
||||
"""Create a minimal WebP with the EXIF records ComfyUI writes.
|
||||
|
||||
SaveAnimatedWEBP puts ``prompt:{json}`` at EXIF tag 0x0110 and
|
||||
``workflow:{json}`` at 0x010F; the file has no text chunks at all.
|
||||
|
||||
Args:
|
||||
workflow: Workflow dict to embed as the workflow record.
|
||||
prompt: Prompt dict to embed as the prompt record.
|
||||
size: tuple (width, height).
|
||||
|
||||
Returns:
|
||||
Path to the temporary WebP file.
|
||||
"""
|
||||
exif = Image.Exif()
|
||||
if prompt is not None:
|
||||
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
|
||||
if workflow is not None:
|
||||
exif[0x010F] = f"workflow:{json.dumps(workflow)}"
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".webp")
|
||||
tmp.close()
|
||||
Image.new("RGB", size, color=(128, 128, 128)).save(tmp.name, "WEBP", exif=exif)
|
||||
return tmp.name
|
||||
|
||||
|
||||
class MetadataTestCase(unittest.TestCase):
|
||||
"""Base class that cleans up temp files."""
|
||||
|
||||
@@ -58,6 +83,11 @@ class MetadataTestCase(unittest.TestCase):
|
||||
self.temp_files.append(path)
|
||||
return path
|
||||
|
||||
def _webp(self, workflow=None, prompt=None, size=(64, 64)):
|
||||
path = _create_webp(workflow, prompt, size)
|
||||
self.temp_files.append(path)
|
||||
return path
|
||||
|
||||
|
||||
class TestExtractMetadata(MetadataTestCase):
|
||||
"""Test extract_metadata method."""
|
||||
@@ -82,6 +112,17 @@ class TestExtractMetadata(MetadataTestCase):
|
||||
self.assertIsNotNone(result)
|
||||
self.assertIn("prompt", result)
|
||||
|
||||
def test_extracts_metadata_from_webp_exif(self):
|
||||
"""A WebP carries the records as EXIF, not as text chunks."""
|
||||
workflow = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "hi"}}]}
|
||||
prompt = {"1": {"class_type": "KSampler", "inputs": {}}}
|
||||
path = self._webp(workflow=workflow, prompt=prompt)
|
||||
result = self.extractor.extract_metadata(path)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result["workflow"]["nodes"][0]["type"], "CLIPTextEncode")
|
||||
self.assertIn("prompt", result)
|
||||
self.assertEqual(result["file_info"]["format"], "WEBP")
|
||||
|
||||
def test_extracts_text_encoder_nodes(self):
|
||||
workflow = {
|
||||
"nodes": [
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""ComfyUI's EXIF metadata records (WebP, AVIF, JPEG).
|
||||
|
||||
PNG keeps the workflow and the prompt in text chunks (``utils.png_text``).
|
||||
The formats without text chunks carry the same records as EXIF strings:
|
||||
``SaveAnimatedWEBP`` writes ``prompt:{json}`` to tag 0x0110, then
|
||||
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down,
|
||||
and the AVIF writer uses that layout too. Pillow answers those tags only
|
||||
through ``getexif()``; ``image.info`` holds the raw EXIF blob, so reading it
|
||||
as text found no metadata at all.
|
||||
|
||||
``exif_text`` returns the ``{key: json}`` shape of ``utils.png_text`` so a
|
||||
caller reads either source the same way. Only a value shaped like a ComfyUI
|
||||
record counts, a key and a colon followed by a JSON object, array or string;
|
||||
a camera's ``Make`` or a ``DateTime`` is not metadata.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# A record's key: ``workflow``, ``prompt`` or an extra_pnginfo key.
|
||||
_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
||||
# What a record holds: the workflow and the prompt are objects, the pair
|
||||
# records a list, a custom extra_pnginfo value may be a string. Numbers,
|
||||
# dates and camera names start with anything else.
|
||||
_STARTS = ("{", "[", '"')
|
||||
|
||||
|
||||
def exif_text(image) -> dict:
|
||||
"""ComfyUI's EXIF records of an opened image, or ``{}``.
|
||||
|
||||
The image stays usable and nothing is decoded but the EXIF block. Formats
|
||||
whose records are text chunks (PNG) answer ``{}``; read those with
|
||||
``utils.png_text.png_text`` first.
|
||||
"""
|
||||
try:
|
||||
exif = image.getexif()
|
||||
except Exception: # a broken EXIF block never fails a scan
|
||||
return {}
|
||||
records = {}
|
||||
for value in exif.values():
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("utf-8", errors="replace")
|
||||
if not isinstance(value, str):
|
||||
continue
|
||||
key, separator, payload = value.partition(":")
|
||||
if separator and _KEY.match(key) and payload.lstrip()[:1] in _STARTS:
|
||||
records[key] = payload
|
||||
return records
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
This module provides comprehensive metadata extraction capabilities for
|
||||
ComfyUI-generated images. It can extract workflow information, prompt data, and
|
||||
generation parameters from PNG images that contain embedded ComfyUI metadata in
|
||||
their text chunks.
|
||||
generation parameters from the text chunks of PNG images and the EXIF records
|
||||
ComfyUI writes for WebP, AVIF and JPEG images.
|
||||
|
||||
The extractor supports:
|
||||
- Complete workflow data extraction from PNG text chunks
|
||||
- Complete workflow data extraction from PNG text chunks and EXIF records
|
||||
- Text encoder node identification and analysis
|
||||
- Generation parameter extraction (steps, cfg_scale, sampler, etc.)
|
||||
- Basic file information fallback when metadata is unavailable
|
||||
@@ -36,6 +36,7 @@ import json
|
||||
from typing import Optional, Dict, Any
|
||||
from PIL import Image
|
||||
|
||||
from .exif_text import exif_text
|
||||
from .logging_config import get_logger
|
||||
from .png_text import png_text
|
||||
|
||||
@@ -89,9 +90,10 @@ class ComfyUIMetadataExtractor:
|
||||
# Add basic file information
|
||||
metadata["file_info"] = self.get_file_info(image_path, image)
|
||||
|
||||
# Extract ComfyUI-specific metadata from PNG text chunks,
|
||||
# read without decoding the pixels (#523)
|
||||
text = png_text(image)
|
||||
# ComfyUI writes PNG text chunks, read without decoding the
|
||||
# pixels (#523). WebP (and AVIF, once collected: #652) carry
|
||||
# the same records as EXIF text, so those images link too.
|
||||
text = png_text(image) or exif_text(image)
|
||||
if text:
|
||||
# Look for ComfyUI workflow data
|
||||
if "workflow" in text:
|
||||
|
||||
Reference in New Issue
Block a user