|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from dataclasses import dataclass |
| 4 | + |
| 5 | +from PIL import Image |
| 6 | + |
| 7 | +from invokeai.app.services.workflow_records.workflow_records_common import WorkflowWithoutIDValidator |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class ExtractedMetadata: |
| 12 | + invokeai_metadata: str | None |
| 13 | + invokeai_workflow: str | None |
| 14 | + invokeai_graph: str | None |
| 15 | + |
| 16 | + |
| 17 | +def extract_metadata_from_image( |
| 18 | + pil_image: Image.Image, |
| 19 | + invokeai_metadata_override: str | None, |
| 20 | + invokeai_workflow_override: str | None, |
| 21 | + invokeai_graph_override: str | None, |
| 22 | + logger: logging.Logger, |
| 23 | +) -> ExtractedMetadata: |
| 24 | + """ |
| 25 | + Extracts the "invokeai_metadata", "invokeai_workflow", and "invokeai_graph" data embedded in the PIL Image. |
| 26 | +
|
| 27 | + These items are stored as stringified JSON in the image file's metadata, so we need to do some parsing to validate |
| 28 | + them. Once parsed, the values are returned as they came (as strings), or None if they are not present or invalid. |
| 29 | +
|
| 30 | + In some situations, we may prefer to override the values extracted from the image file with some other values. |
| 31 | +
|
| 32 | + For example, when uploading an image via API, the client can optionally provide the metadata directly in the request, |
| 33 | + as opposed to embedding it in the image file. In this case, the client-provided metadata will be used instead of the |
| 34 | + metadata embedded in the image file. |
| 35 | +
|
| 36 | + Args: |
| 37 | + pil_image: The PIL Image object. |
| 38 | + invokeai_metadata_override: The metadata override provided by the client. |
| 39 | + invokeai_workflow_override: The workflow override provided by the client. |
| 40 | + invokeai_graph_override: The graph override provided by the client. |
| 41 | + logger: The logger to use for debug logging. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + ExtractedMetadata: The extracted metadata, workflow, and graph. |
| 45 | + """ |
| 46 | + |
| 47 | + # The fallback value for metadata is None. |
| 48 | + stringified_metadata: str | None = None |
| 49 | + |
| 50 | + # Use the metadata override if provided, else attempt to extract it from the image file. |
| 51 | + metadata_raw = invokeai_metadata_override or pil_image.info.get("invokeai_metadata", None) |
| 52 | + |
| 53 | + # If the metadata is present in the image file, we will attempt to parse it as JSON. When we create images, |
| 54 | + # we always store metadata as a stringified JSON dict. So, we expect it to be a string here. |
| 55 | + if isinstance(metadata_raw, str): |
| 56 | + try: |
| 57 | + # Must be a JSON string |
| 58 | + metadata_parsed = json.loads(metadata_raw) |
| 59 | + # Must be a dict |
| 60 | + if isinstance(metadata_parsed, dict): |
| 61 | + # Looks good, overwrite the fallback value |
| 62 | + stringified_metadata = metadata_raw |
| 63 | + except Exception as e: |
| 64 | + logger.debug(f"Failed to parse metadata for uploaded image, {e}") |
| 65 | + pass |
| 66 | + |
| 67 | + # We expect the workflow, if embedded in the image, to be a JSON-stringified WorkflowWithoutID. We will store it |
| 68 | + # as a string. |
| 69 | + workflow_raw: str | None = invokeai_workflow_override or pil_image.info.get("invokeai_workflow", None) |
| 70 | + |
| 71 | + # The fallback value for workflow is None. |
| 72 | + stringified_workflow: str | None = None |
| 73 | + |
| 74 | + # If the workflow is present in the image file, we will attempt to parse it as JSON. When we create images, we |
| 75 | + # always store workflows as a stringified JSON WorkflowWithoutID. So, we expect it to be a string here. |
| 76 | + if isinstance(workflow_raw, str): |
| 77 | + try: |
| 78 | + # Validate the workflow JSON before storing it |
| 79 | + WorkflowWithoutIDValidator.validate_json(workflow_raw) |
| 80 | + # Looks good, overwrite the fallback value |
| 81 | + stringified_workflow = workflow_raw |
| 82 | + except Exception: |
| 83 | + logger.debug("Failed to parse workflow for uploaded image") |
| 84 | + pass |
| 85 | + |
| 86 | + # We expect the workflow, if embedded in the image, to be a JSON-stringified Graph. We will store it as a |
| 87 | + # string. |
| 88 | + graph_raw: str | None = invokeai_graph_override or pil_image.info.get("invokeai_graph", None) |
| 89 | + |
| 90 | + # The fallback value for graph is None. |
| 91 | + stringified_graph: str | None = None |
| 92 | + |
| 93 | + # If the graph is present in the image file, we will attempt to parse it as JSON. When we create images, we |
| 94 | + # always store graphs as a stringified JSON Graph. So, we expect it to be a string here. |
| 95 | + if isinstance(graph_raw, str): |
| 96 | + try: |
| 97 | + # TODO(psyche): Due to pydantic's handling of None values, it is possible for the graph to fail validation, |
| 98 | + # even if it is a direct dump of a valid graph. Node fields in the graph are allowed to have be unset if |
| 99 | + # they have incoming connections, but something about the ser/de process cannot adequately handle this. |
| 100 | + # |
| 101 | + # In lieu of fixing the graph validation, we will just do a simple check here to see if the graph is dict |
| 102 | + # with the correct keys. This is not a perfect solution, but it should be good enough for now. |
| 103 | + |
| 104 | + # FIX ME: Validate the graph JSON before storing it |
| 105 | + # Graph.model_validate_json(graph_raw) |
| 106 | + |
| 107 | + # Crappy workaround to validate JSON |
| 108 | + graph_parsed = json.loads(graph_raw) |
| 109 | + if not isinstance(graph_parsed, dict): |
| 110 | + raise ValueError("Not a dict") |
| 111 | + if not isinstance(graph_parsed.get("nodes", None), dict): |
| 112 | + raise ValueError("'nodes' is not a dict") |
| 113 | + if not isinstance(graph_parsed.get("edges", None), list): |
| 114 | + raise ValueError("'edges' is not a list") |
| 115 | + |
| 116 | + # Looks good, overwrite the fallback value |
| 117 | + stringified_graph = graph_raw |
| 118 | + except Exception as e: |
| 119 | + logger.debug(f"Failed to parse graph for uploaded image, {e}") |
| 120 | + pass |
| 121 | + |
| 122 | + return ExtractedMetadata( |
| 123 | + invokeai_metadata=stringified_metadata, invokeai_workflow=stringified_workflow, invokeai_graph=stringified_graph |
| 124 | + ) |
0 commit comments