tlam commited on
Commit ·
3a320b8
1
Parent(s): 6364f3e
Refactor: rewrite ComfyUI parsing with graph tracing, add LoRA/dimensions/strip metadata, update for Gradio 6.x
Browse filesFiles changed (4)
- .gitignore+2
- README.md+1-1
- app.py+350-119
- requirements.txt+2-1
12/venv.DS_Store1234/venvvenv/__pycache__/.DS_Store
3 unmodified lines456789103 unmodified linescolorFrom: bluecolorTo: bluesdk: gradiosdk_version: 4.44.0app_file: app.pypinned: falselicense: apache-2.03 unmodified lines456789103 unmodified linescolorFrom: bluecolorTo: bluesdk: gradiosdk_version: 5.34.0app_file: app.pypinned: falselicense: apache-2.0
1234567891011121314151617181 unmodified line2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import gradio as grfrom PIL import Imagefrom PIL.ExifTags import TAGSimport numpy as npimport reimport jsonimport tempfileimport osdef get_image_metadata(img):"""Extract metadata based on image format."""metadata = {}if img.format == 'PNG':metadata = img.infoelif img.format in ['JPEG', 'TIFF']:exif_data = img._getexif()if exif_data:for tag, value in exif_data.items():1 unmodified linemetadata[tag_name] = valuereturn metadatadef parse_parameters(parameters):"""Parse the 'parameters' field to extract prompts and seed number."""prompt = 'N/A'negative_prompt = 'N/A'adetailer_prompt_1 = 'N/A'adetailer_prompt_2 = 'N/A'seed_number = -1# Extract the promptprompt_match = re.search(r'(.*?)Negative prompt:', parameters, re.DOTALL | re.IGNORECASE)if prompt_match:prompt = prompt_match.group(1).strip()else:prompt_match = re.search(r'(.*?)(Steps:|$)', parameters, re.DOTALL | re.IGNORECASE)if prompt_match:prompt = prompt_match.group(1).strip()# Extract the negative promptnegative_prompt_match = re.search(r'Negative prompt:(.*?)(Steps:|$)', parameters, re.DOTALL | re.IGNORECASE)if negative_prompt_match:negative_prompt = negative_prompt_match.group(1).strip()# Extract ADetailer promptsadetailer_prompt_1_match = re.search(r'ADetailer prompt:\s*"(.*?)"', parameters, re.IGNORECASE)if adetailer_prompt_1_match:adetailer_prompt_1 = adetailer_prompt_1_match.group(1).strip()adetailer_prompt_2_match = re.search(r'ADetailer negative prompt 2nd:\s*"(.*?)"', parameters, re.IGNORECASE)if adetailer_prompt_2_match:adetailer_prompt_2 = adetailer_prompt_2_match.group(1).strip()# Extract Seed Numberseed_match = re.search(r'Seed:\s*(\d+)', parameters, re.IGNORECASE)if seed_match:seed_number = seed_match.group(1).strip()return prompt, negative_prompt, adetailer_prompt_1, adetailer_prompt_2, seed_numberdef extract_metadata(image_file):"""Extract and parse metadata from the uploaded image."""try:img = Image.open(image_file)except Exception as e:# Return placeholders in case of errorreturn (None, 'Error: Unable to open image.', *(['N/A'] * 7))metadata = get_image_metadata(img)img_display = np.array(img)# Convert metadata to stringmetadata_str = "\n".join([f"{key}: {value}" for key, value in metadata.items()])# Initialize default valuesprompt = negative_prompt = adetailer_prompt_1 = adetailer_prompt_2 = 'N/A'seed_number = -1comfy_prompt = comfy_workflow = 'N/A'# Parse parameters if availableif 'parameters' in metadata:parsed = parse_parameters(metadata['parameters'])prompt, negative_prompt, adetailer_prompt_1, adetailer_prompt_2, seed_number = parsed# Direct extraction with validation for Comfy Promptif 'prompt' in metadata and isinstance(metadata['prompt'], str):comfy_prompt = metadata['prompt'].strip()else:comfy_prompt = 'N/A' # Fallback if prompt is missing or not a string# Direct extraction with validation for Comfy Workflowif 'workflow' in metadata and isinstance(metadata['workflow'], str):comfy_workflow = metadata['workflow'].strip()else:comfy_workflow = 'N/A' # Fallback if workflow is missing or not a stringreturn (img_display,prompt,negative_prompt,seed_number,adetailer_prompt_1,adetailer_prompt_2,metadata_str,comfy_prompt,comfy_workflow)def export_workflow(workflow_text):"""Converts the workflow text into JSON format and returns it as a downloadable file."""print("Export workflow function called.")if workflow_text == "N/A" or not workflow_text.strip():print("No workflow data to export.")return None, "No workflow data to export."# Structure the JSON dataworkflow_data = {"comfy_workflow": workflow_text}# Create a temporary JSON filetry:with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as tmp_file:json.dump(workflow_data, tmp_file, indent=4)tmp_file_path = tmp_file.nameprint(f"Temporary JSON file created at: {tmp_file_path}")except Exception as e:print(f"Error creating temporary file: {e}")return None, "Failed to create workflow JSON file."# Check if the file was created successfullyif os.path.exists(tmp_file_path):message = "Workflow exported successfully."print(message)return tmp_file_path, messageelse:message = "Failed to export workflow."print(message)return None, messagedef main():# Create Gradio User Interfacewith gr.Blocks() as iface:gr.Markdown("<h1>Automatic 1111/ Comfy Metadata Reader</h1>")gr.Markdown("<p>Upload an image (PNG, JPEG) to extract its metadata and parse it for prompts.</p>")with gr.Row():with gr.Column(): # First column for image upload and previewimage_input = gr.File(label="Upload Image", type="filepath")image_output = gr.Image(label="Image Preview")original_metadata_output = gr.Textbox(label="Original Metadata", lines=20, interactive=False)with gr.Column(): # Second column for metadata outputsprompt_output = gr.Textbox(label="Prompt", lines=4, show_copy_button=True, interactive=False)negative_prompt_output = gr.Textbox(label="Negative Prompt", lines=4, show_copy_button=True, interactive=False)seed_output = gr.Textbox(label="Seed Number", lines=1, show_copy_button=True, interactive=False)adetailer_prompt_1_output = gr.Textbox(label="ADetailer Prompt 1", lines=3, show_copy_button=True, interactive=False)adetailer_prompt_2_output = gr.Textbox(label="ADetailer Prompt 2", lines=3, show_copy_button=True, interactive=False)with gr.Column(): # Third column for additional metadata outputswith gr.Row():comfy_prompt_output = gr.Textbox(label="Comfy Prompt", lines=4, value="N/A", interactive=False)with gr.Row():comfy_workflow_output = gr.Textbox(label="Comfy Workflow", lines=20, value="N/A", interactive=False)export_button = gr.Button("Export Workflow as JSON")workflow_file = gr.File(label="Download Workflow JSON", visible=False)with gr.Row():export_message = gr.Textbox(label="Export Status", lines=1, interactive=False, visible=False)# Set up the input-output relationshipsimage_input.change(fn=extract_metadata,inputs=image_input,outputs=[image_output,prompt_output,negative_prompt_output,seed_output,adetailer_prompt_1_output,adetailer_prompt_2_output,original_metadata_output,comfy_prompt_output,comfy_workflow_output,])# Connect the export button to the export functionexport_button.click(fn=export_workflow,inputs=comfy_workflow_output,outputs=[workflow_file, export_message],queue=False)iface.launch()if __name__ == "__main__":main()1234567891011121314151617181920212223242526272829303132333435363738394041424344451 unmodified line4748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430import gradio as grfrom PIL import Imagefrom PIL.ExifTags import TAGSimport reimport jsonimport tempfileimport osimport mathdef get_aspect_ratio(w, h):"""Return the closest standard aspect ratio string for given dimensions."""if w == 0 or h == 0:return "N/A"ratio = w / htolerance = 0.02ratios = {"1:1": 1.0,"5:4": 5 / 4,"4:3": 4 / 3,"3:2": 3 / 2,"16:9": 16 / 9,"16:10": 16 / 10,"21:9": 21 / 9,"2:3": 2 / 3,"3:4": 3 / 4,"4:5": 4 / 5,"9:16": 9 / 16,}for label, val in ratios.items():if abs(ratio - val) < tolerance:return labelgcd = math.gcd(w, h)return f"{w // gcd}:{h // gcd}"def get_image_metadata(img):"""Extract metadata based on image format."""metadata = {}if img.format == "PNG":metadata = img.infoelif img.format in ["JPEG", "TIFF", "WEBP"]:exif_data = img._getexif()if exif_data:for tag, value in exif_data.items():1 unmodified linemetadata[tag_name] = valuereturn metadatadef parse_comfy_prompt(prompt_data):"""Parse ComfyUI prompt JSON using graph tracing for correct pos/neg identification."""positive_prompt = "N/A"negative_prompt = "N/A"seed = "N/A"try:if isinstance(prompt_data, str):prompt_data = json.loads(prompt_data)except (json.JSONDecodeError, TypeError):return positive_prompt, negative_prompt, seed, []if not isinstance(prompt_data, dict):return positive_prompt, negative_prompt, seed, []clip_text_nodes = {}lora_names = []for node_id, node in prompt_data.items():if not isinstance(node, dict):continueclass_type = node.get("class_type", "")inputs = node.get("inputs", {})widgets = node.get("widgets_values", [])if class_type in ("CLIPTextEncode", "CLIPTextEncodeSDXL"):text = inputs.get("text", "")if not text or not text.strip():continueclip_text_nodes[node_id] = {"text": text.strip(),"links": node.get("inputs", []),}if "LoraLoader" in class_type or "LoraLoaderModelOnly" in class_type:lora_name = inputs.get("lora_name", inputs.get("lora", ""))if isinstance(lora_name, str) and lora_name.strip():lora_names.append(lora_name.strip())for wv in widgets:if isinstance(wv, str) and wv.endswith((".safetensors", ".ckpt", ".pt")):if wv not in lora_names:lora_names.append(wv)if class_type in ("KSampler","KSamplerAdvanced","SamplerCustom","SamplerCustomAdvanced",):if "seed" in inputs:seed = str(inputs["seed"])if "noise_seed" in inputs:seed = str(inputs["noise_seed"])positive_ids = set()negative_ids = set()for node_id, node in prompt_data.items():if not isinstance(node, dict):continueclass_type = node.get("class_type", "")inputs = node.get("inputs", {})is_sampler = class_type in ("KSampler","KSamplerAdvanced","SamplerCustom","SamplerCustomAdvanced",)if is_sampler:for input_name in ("positive", "latent_image"):link = inputs.get(input_name)if isinstance(link, list) and len(link) >= 1:positive_ids.add(str(link[0]))for input_name in ("negative",):link = inputs.get(input_name)if isinstance(link, list) and len(link) >= 1:negative_ids.add(str(link[0]))if class_type in ("SamplerCustom", "SamplerCustomAdvanced"):for input_name in ("guider", "sampler", "sigmas"):link = inputs.get(input_name)if isinstance(link, list) and len(link) >= 1:passdef trace_positive(node_id, visited=None):if visited is None:visited = set()if node_id in visited:return []visited.add(node_id)node = prompt_data.get(node_id, {})if not isinstance(node, dict):return []class_type = node.get("class_type", "")inputs = node.get("inputs", {})texts = []if class_type in ("CLIPTextEncode", "CLIPTextEncodeSDXL"):text = inputs.get("text", "")if text and text.strip():texts.append(text.strip())for input_name, link in inputs.items():if isinstance(link, list) and len(link) >= 1:texts.extend(trace_positive(str(link[0]), visited))return textsdef trace_negative(node_id, visited=None):if visited is None:visited = set()if node_id in visited:return []visited.add(node_id)node = prompt_data.get(node_id, {})if not isinstance(node, dict):return []class_type = node.get("class_type", "")inputs = node.get("inputs", {})texts = []if class_type in ("CLIPTextEncode", "CLIPTextEncodeSDXL"):text = inputs.get("text", "")if text and text.strip():texts.append(text.strip())for input_name, link in inputs.items():if isinstance(link, list) and len(link) >= 1:texts.extend(trace_negative(str(link[0]), visited))return textsfound_pos = Falsefound_neg = Falsefor nid in sorted(positive_ids):if nid in clip_text_nodes:positive_prompt = clip_text_nodes[nid]["text"]found_pos = Truebreakif not found_pos:for nid in sorted(positive_ids):texts = trace_positive(nid)if texts:positive_prompt = texts[0]found_pos = Truebreakfor nid in sorted(negative_ids):if nid in clip_text_nodes:negative_prompt = clip_text_nodes[nid]["text"]found_neg = Truebreakif not found_neg:for nid in sorted(negative_ids):texts = trace_negative(nid)if texts:negative_prompt = texts[0]found_neg = Truebreakif not found_pos and not found_neg:texts = [n["text"] for n in clip_text_nodes.values()]if len(texts) >= 1:positive_prompt = texts[0]if len(texts) >= 2:negative_prompt = texts[1]return positive_prompt, negative_prompt, seed, lora_namesdef extract_metadata(image_file):"""Extract and parse metadata from the uploaded image."""try:img = Image.open(image_file)except Exception:return ("Error: Unable to open image.", *(["N/A"] * 6), [], "N/A")metadata = get_image_metadata(img)width, height = img.sizeaspect_ratio = get_aspect_ratio(width, height)dimensions = f"{width} × {height} ({aspect_ratio})"metadata_str = "\n".join([f"{key}: {value}" for key, value in metadata.items()])prompt = "N/A"negative_prompt = "N/A"seed_number = "N/A"comfy_workflow = "N/A"lora_names = []comfy_prompt_data = metadata.get("prompt", None)if comfy_prompt_data is not None:pos, neg, s, loras = parse_comfy_prompt(comfy_prompt_data)if pos != "N/A":prompt = posif neg != "N/A":negative_prompt = negif s != "N/A":seed_number = slora_names = loraselif "parameters" in metadata:params = metadata["parameters"]prompt_match = re.search(r"(.*?)Negative prompt:", params, re.DOTALL | re.IGNORECASE)if prompt_match:prompt = prompt_match.group(1).strip()else:prompt_match = re.search(r"(.*?)(Steps:|$)", params, re.DOTALL | re.IGNORECASE)if prompt_match:prompt = prompt_match.group(1).strip()neg_match = re.search(r"Negative prompt:(.*?)(Steps:|$)", params, re.DOTALL | re.IGNORECASE)if neg_match:negative_prompt = neg_match.group(1).strip()seed_match = re.search(r"Seed:\s*(\d+)", params, re.IGNORECASE)if seed_match:seed_number = seed_match.group(1).strip()lora_pattern = re.compile(r"<lora:([^:>]+)", re.IGNORECASE)lora_names = lora_pattern.findall(params)workflow_data = metadata.get("workflow", None)if workflow_data is not None:if isinstance(workflow_data, str):try:json.loads(workflow_data)comfy_workflow = workflow_dataexcept json.JSONDecodeError:comfy_workflow = workflow_dataelif isinstance(workflow_data, dict):comfy_workflow = json.dumps(workflow_data, indent=2)else:comfy_workflow = str(workflow_data)return (dimensions,prompt,negative_prompt,seed_number,metadata_str,comfy_workflow,lora_names,"N/A",)def export_workflow(workflow_text):"""Convert the workflow text into a downloadable JSON file."""if workflow_text == "N/A" or not workflow_text.strip():return None, "No workflow data to export."workflow_data = {"comfy_workflow": workflow_text}try:with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".json") as tmp_file:json.dump(workflow_data, tmp_file, indent=4)tmp_file_path = tmp_file.nameexcept Exception:return None, "Failed to create workflow JSON file."if os.path.exists(tmp_file_path):return tmp_file_path, "Workflow exported successfully."else:return None, "Failed to export workflow."def strip_metadata(image_file):"""Strip all metadata from an image and return a clean file."""if image_file is None:return None, "No image provided."try:img = Image.open(image_file)except Exception:return None, "Error: Unable to open image."clean_img = Image.new(img.mode, img.size)clean_img.putdata(list(img.getdata()))try:with tempfile.NamedTemporaryFile(mode="wb", delete=False, suffix=".png") as tmp_file:clean_img.save(tmp_file, format="PNG")tmp_file_path = tmp_file.nameexcept Exception:return None, "Error saving stripped image."return tmp_file_path, "Metadata stripped successfully."def main():with gr.Blocks() as iface:gr.Markdown("<h1>Comfy / A1111 Metadata Reader</h1>")gr.Markdown("<p>Upload an image (PNG, JPEG, WebP) to extract its metadata and parse it for prompts.</p>")with gr.Row():with gr.Column(scale=1):image_input = gr.Image(label="Drop Image Here", type="filepath")with gr.Column(scale=2):dimensions_output = gr.Textbox(label="Dimensions", lines=1, interactive=False)prompt_output = gr.Textbox(label="Prompt", lines=4, buttons=["copy"], interactive=False)negative_prompt_output = gr.Textbox(label="Negative Prompt",lines=4,buttons=["copy"],interactive=False,)seed_output = gr.Textbox(label="Seed Number", lines=1, buttons=["copy"], interactive=False)lora_output = gr.Textbox(label="LoRA(s)", lines=2, buttons=["copy"], interactive=False)original_metadata_output = gr.Textbox(label="Original Metadata", lines=15, interactive=False)with gr.Column(scale=2):comfy_workflow_output = gr.Textbox(label="Comfy Workflow", lines=20, value="N/A", interactive=False)with gr.Row():export_button = gr.Button("Export Workflow as JSON")strip_button = gr.Button("Strip Metadata", variant="stop")workflow_file = gr.File(label="Download Workflow JSON", visible=False)export_message = gr.Textbox(label="Export Status", lines=1, interactive=False)strip_file = gr.File(label="Download Stripped Image", visible=False)strip_message = gr.Textbox(label="Strip Status", lines=1, interactive=False)image_input.change(fn=extract_metadata,inputs=image_input,outputs=[dimensions_output,prompt_output,negative_prompt_output,seed_output,original_metadata_output,comfy_workflow_output,lora_output,strip_message,],)export_button.click(fn=export_workflow,inputs=comfy_workflow_output,outputs=[workflow_file, export_message],queue=False,)strip_button.click(fn=strip_metadata,inputs=image_input,outputs=[strip_file, strip_message],queue=False,)iface.launch()if __name__ == "__main__":main()
12gradioPillow123gradioPillownumpy
.gitignore+2
README.md+1-1
app.py+350-119
requirements.txt+2-1