|
| 1 | +import json |
1 | 2 | from typing import Any, Literal, Optional, Union
|
2 | 3 |
|
3 | 4 | from pydantic import BaseModel, ConfigDict, Field
|
|
18 | 19 | UIType,
|
19 | 20 | )
|
20 | 21 | from invokeai.app.invocations.model import ModelIdentifierField
|
| 22 | +from invokeai.app.invocations.primitives import StringOutput |
21 | 23 | from invokeai.app.services.shared.invocation_context import InvocationContext
|
22 | 24 | from invokeai.app.util.controlnet_utils import CONTROLNET_MODE_VALUES, CONTROLNET_RESIZE_VALUES
|
23 | 25 | from invokeai.version.invokeai_version import __version__
|
@@ -275,3 +277,25 @@ def invoke(self, context: InvocationContext) -> MetadataOutput:
|
275 | 277 | return MetadataOutput(metadata=MetadataField.model_validate(as_dict))
|
276 | 278 |
|
277 | 279 | model_config = ConfigDict(extra="allow")
|
| 280 | + |
| 281 | + |
| 282 | +@invocation("metadata_field_extractor", title="Metadata Field Extractor", tags=["metadata"], category="metadata", version="1.0.0") |
| 283 | +class MetadataFieldExtractorInvocation(BaseInvocation): |
| 284 | + """Extracts the text value from an image's metadata given a key. |
| 285 | + Raises an error if the image has no metadata or if the value is not a string (nesting not permitted).""" |
| 286 | + |
| 287 | + image: ImageField = InputField(description="The image to extract metadata from") |
| 288 | + key: str = InputField(description="The key in the image's metadata to extract the value from") |
| 289 | + |
| 290 | + def invoke(self, context: InvocationContext) -> StringOutput: |
| 291 | + metadata = context.images.get_metadata(image_name=self.image.image_name) |
| 292 | + if not metadata: |
| 293 | + raise ValueError("No metadata found on image") |
| 294 | + |
| 295 | + try: |
| 296 | + val = metadata.root[self.key] |
| 297 | + if not isinstance(val, str): |
| 298 | + raise ValueError(f"Metadata at key '{self.key}' must be a string") |
| 299 | + return StringOutput(value=val) |
| 300 | + except KeyError as e: |
| 301 | + raise ValueError(f"No key {self.key} found in metadata") from e |
0 commit comments