metadata_editor.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import os
  2. import json
  3. import sys
  4. import io
  5. import base64
  6. import platform
  7. import subprocess as sp
  8. from PIL import PngImagePlugin, Image
  9. from modules import shared
  10. import gradio as gr
  11. import modules.ui
  12. from modules.ui_components import ToolButton
  13. import modules.extras
  14. import modules.generation_parameters_copypaste as parameters_copypaste
  15. from scripts import safetensors_hack, model_util
  16. from scripts.model_util import MAX_MODEL_COUNT
  17. folder_symbol = '\U0001f4c2' # 📂
  18. keycap_symbols = [
  19. '\u0031\ufe0f\u20e3', # 1️⃣
  20. '\u0032\ufe0f\u20e3', # 2️⃣
  21. '\u0033\ufe0f\u20e3', # 3️⃣
  22. '\u0034\ufe0f\u20e3', # 4️⃣
  23. '\u0035\ufe0f\u20e3', # 5️⃣
  24. '\u0036\ufe0f\u20e3', # 6️⃣
  25. '\u0037\ufe0f\u20e3', # 7️⃣
  26. '\u0038\ufe0f\u20e3', # 8️
  27. '\u0039\ufe0f\u20e3', # 9️
  28. '\u1f51f' # 🔟
  29. ]
  30. def write_webui_model_preview_image(model_path, image):
  31. basename, ext = os.path.splitext(model_path)
  32. preview_path = f"{basename}.png"
  33. # Copy any text-only metadata
  34. use_metadata = False
  35. metadata = PngImagePlugin.PngInfo()
  36. for key, value in image.info.items():
  37. if isinstance(key, str) and isinstance(value, str):
  38. metadata.add_text(key, value)
  39. use_metadata = True
  40. image.save(preview_path, "PNG", pnginfo=(metadata if use_metadata else None))
  41. def delete_webui_model_preview_image(model_path):
  42. basename, ext = os.path.splitext(model_path)
  43. preview_paths = [f"{basename}.preview.png", f"{basename}.png"]
  44. for preview_path in preview_paths:
  45. if os.path.isfile(preview_path):
  46. os.unlink(preview_path)
  47. def decode_base64_to_pil(encoding):
  48. if encoding.startswith("data:image/"):
  49. encoding = encoding.split(";")[1].split(",")[1]
  50. return Image.open(io.BytesIO(base64.b64decode(encoding)))
  51. def encode_pil_to_base64(image):
  52. with io.BytesIO() as output_bytes:
  53. # Copy any text-only metadata
  54. use_metadata = False
  55. metadata = PngImagePlugin.PngInfo()
  56. for key, value in image.info.items():
  57. if isinstance(key, str) and isinstance(value, str):
  58. metadata.add_text(key, value)
  59. use_metadata = True
  60. image.save(
  61. output_bytes, "PNG", pnginfo=(metadata if use_metadata else None)
  62. )
  63. bytes_data = output_bytes.getvalue()
  64. return base64.b64encode(bytes_data)
  65. def open_folder(f):
  66. if not os.path.exists(f):
  67. print(f'Folder "{f}" does not exist. After you create an image, the folder will be created.')
  68. return
  69. elif not os.path.isdir(f):
  70. print(f"""
  71. WARNING
  72. An open_folder request was made with an argument that is not a folder.
  73. This could be an error or a malicious attempt to run code on your computer.
  74. Requested path was: {f}
  75. """, file=sys.stderr)
  76. return
  77. if not shared.cmd_opts.hide_ui_dir_config:
  78. path = os.path.normpath(f)
  79. if platform.system() == "Windows":
  80. os.startfile(path)
  81. elif platform.system() == "Darwin":
  82. sp.Popen(["open", path])
  83. elif "microsoft-standard-WSL2" in platform.uname().release:
  84. sp.Popen(["wsl-open", path])
  85. else:
  86. sp.Popen(["xdg-open", path])
  87. def copy_metadata_to_all(module, model_path, copy_dir, same_session_only, missing_meta_only, cover_image):
  88. """
  89. Given a model with metadata, copies that metadata to all models in copy_dir.
  90. :str module: Module name ("LoRA")
  91. :str model: Model key in lora_models ("MyModel(123456abcdef)")
  92. :str copy_dir: Directory to copy to
  93. :bool same_session_only: Only copy to modules with the same ss_session_id
  94. :bool missing_meta_only: Only copy to modules that are missing user metadata
  95. :Optional[Image] cover_image: Cover image to embed in the file as base64
  96. :returns: gr.HTML.update()
  97. """
  98. if model_path == "None":
  99. return "No model selected."
  100. if not os.path.isfile(model_path):
  101. return f"Model path not found: {model_path}"
  102. model_path = os.path.realpath(model_path)
  103. if os.path.splitext(model_path)[1] != ".safetensors":
  104. return "Model is not in .safetensors format."
  105. if not os.path.isdir(copy_dir):
  106. return "Please provide a directory containing models in .safetensors format."
  107. print(f"[MetadataEditor] Copying metadata to models in {copy_dir}.")
  108. metadata = model_util.read_model_metadata(model_path, module)
  109. count = 0
  110. for entry in os.scandir(copy_dir):
  111. if entry.is_file():
  112. path = os.path.realpath(os.path.join(copy_dir, entry.name))
  113. if path != model_path and model_util.is_safetensors(path):
  114. if same_session_only:
  115. other_metadata = safetensors_hack.read_metadata(path)
  116. if missing_meta_only and other_metadata.get("ssmd_display_name", "").strip():
  117. print(f"[MetadataEditor] Skipping {path} as it already has metadata")
  118. continue
  119. session_id = metadata.get("ss_session_id", None)
  120. other_session_id = other_metadata.get("ss_session_id", None)
  121. if session_id is None or other_session_id is None or session_id != other_session_id:
  122. continue
  123. updates = {
  124. "ssmd_cover_images": "[]",
  125. "ssmd_display_name": "",
  126. "ssmd_version": "",
  127. "ssmd_keywords": "",
  128. "ssmd_author": "",
  129. "ssmd_source": "",
  130. "ssmd_description": "",
  131. "ssmd_rating": "0",
  132. "ssmd_tags": "",
  133. }
  134. for k, v in metadata.items():
  135. if k.startswith("ssmd_") and k != "ssmd_cover_images":
  136. updates[k] = v
  137. model_util.write_model_metadata(path, module, updates)
  138. count += 1
  139. print(f"[MetadataEditor] Updated {count} models in directory {copy_dir}.")
  140. return f"Updated {count} models in directory {copy_dir}."
  141. def load_cover_image(model_path, metadata):
  142. """
  143. Loads a cover image either from embedded metadata or an image file with
  144. .preview.png/.png format
  145. """
  146. cover_images = json.loads(metadata.get("ssmd_cover_images", "[]"))
  147. cover_image = None
  148. if len(cover_images) > 0:
  149. print("[MetadataEditor] Loading embedded cover image.")
  150. cover_image = decode_base64_to_pil(cover_images[0])
  151. else:
  152. basename, ext = os.path.splitext(model_path)
  153. preview_paths = [f"{basename}.preview.png", f"{basename}.png"]
  154. for preview_path in preview_paths:
  155. if os.path.isfile(preview_path):
  156. print(f"[MetadataEditor] Loading webui preview image: {preview_path}")
  157. cover_image = Image.open(preview_path)
  158. return cover_image
  159. # Dummy value since gr.Dataframe cannot handle an empty list
  160. # https://github.com/gradio-app/gradio/issues/3182
  161. unknown_folders = ["(Unknown)", 0, 0, 0]
  162. def refresh_metadata(module, model_path):
  163. """
  164. Reads metadata from the model on disk and updates all Gradio components
  165. """
  166. if model_path == "None":
  167. return {}, None, "", "", "", "", "", 0, "", "", "", "", "", {}, [unknown_folders]
  168. if not os.path.isfile(model_path):
  169. return {"info": f"Model path not found: {model_path}"}, None, "", "", "", "", "", 0, "", "", "", "", "", {}, [unknown_folders]
  170. if os.path.splitext(model_path)[1] != ".safetensors":
  171. return {"info": "Model is not in .safetensors format."}, None, "", "", "", "", "", 0, "", "", "", "", "", {}, [unknown_folders]
  172. metadata = model_util.read_model_metadata(model_path, module)
  173. if metadata is None:
  174. training_params = {}
  175. metadata = {}
  176. else:
  177. training_params = {k: v for k, v in metadata.items() if k.startswith("ss_")}
  178. cover_image = load_cover_image(model_path, metadata)
  179. display_name = metadata.get("ssmd_display_name", "")
  180. author = metadata.get("ssmd_author", "")
  181. #version = metadata.get("ssmd_version", "")
  182. source = metadata.get("ssmd_source", "")
  183. keywords = metadata.get("ssmd_keywords", "")
  184. description = metadata.get("ssmd_description", "")
  185. rating = int(metadata.get("ssmd_rating", "0"))
  186. tags = metadata.get("ssmd_tags", "")
  187. model_hash = metadata.get("sshs_model_hash", model_util.cache("hashes").get(model_path, {}).get("model", ""))
  188. legacy_hash = metadata.get("sshs_legacy_hash", model_util.cache("hashes").get(model_path, {}).get("legacy", ""))
  189. top_tags = {}
  190. if "ss_tag_frequency" in training_params:
  191. tag_frequency = json.loads(training_params.pop("ss_tag_frequency"))
  192. count_max = 0
  193. for dir, frequencies in tag_frequency.items():
  194. for tag, count in frequencies.items():
  195. tag = tag.strip()
  196. existing = top_tags.get(tag, 0)
  197. top_tags[tag] = count + existing
  198. if len(top_tags) > 0:
  199. top_tags = dict(sorted(top_tags.items(), key=lambda x: x[1], reverse=True))
  200. count_max = max(top_tags.values())
  201. top_tags = {k: float(v / count_max) for k, v in top_tags.items()}
  202. dataset_folders = []
  203. if "ss_dataset_dirs" in training_params:
  204. dataset_dirs = json.loads(training_params.pop("ss_dataset_dirs"))
  205. for dir, counts in dataset_dirs.items():
  206. img_count = int(counts["img_count"])
  207. n_repeats = int(counts["n_repeats"])
  208. dataset_folders.append([dir, img_count, n_repeats, img_count * n_repeats])
  209. if dataset_folders:
  210. dataset_folders.append(["(Total)", sum(r[1] for r in dataset_folders), sum(r[2] for r in dataset_folders), sum(r[3] for r in dataset_folders)])
  211. else:
  212. dataset_folders.append(unknown_folders)
  213. return training_params, cover_image, display_name, author, source, keywords, description, rating, tags, model_hash, legacy_hash, model_path, os.path.dirname(model_path), top_tags, dataset_folders
  214. def save_metadata(module, model_path, cover_image, display_name, author, source, keywords, description, rating, tags):
  215. """
  216. Writes metadata from the Gradio components to the model file
  217. """
  218. if model_path == "None":
  219. return "No model selected.", "", ""
  220. if not os.path.isfile(model_path):
  221. return f"file not found: {model_path}", "", ""
  222. if os.path.splitext(model_path)[1] != ".safetensors":
  223. return "Model is not in .safetensors format", "", ""
  224. metadata = safetensors_hack.read_metadata(model_path)
  225. model_hash = safetensors_hack.hash_file(model_path)
  226. legacy_hash = model_util.get_legacy_hash(metadata, model_path)
  227. # TODO: Support multiple images
  228. # Blocked on gradio not having a gallery upload option
  229. # https://github.com/gradio-app/gradio/issues/1379
  230. cover_images = []
  231. if cover_image is not None:
  232. cover_images.append(encode_pil_to_base64(cover_image).decode("ascii"))
  233. # NOTE: User-specified metadata should NOT be prefixed with "ss_". This is
  234. # to maintain backwards compatibility with the old hashing method. "ss_"
  235. # should be used for training parameters that will never be manually
  236. # updated on the model.
  237. updates = {
  238. "ssmd_cover_images": json.dumps(cover_images),
  239. "ssmd_display_name": display_name,
  240. "ssmd_author": author,
  241. # "ssmd_version": version,
  242. "ssmd_source": source,
  243. "ssmd_keywords": keywords,
  244. "ssmd_description": description,
  245. "ssmd_rating": rating,
  246. "ssmd_tags": tags,
  247. "sshs_model_hash": model_hash,
  248. "sshs_legacy_hash": legacy_hash
  249. }
  250. model_util.write_model_metadata(model_path, module, updates)
  251. if cover_image is None:
  252. delete_webui_model_preview_image(model_path)
  253. else:
  254. write_webui_model_preview_image(model_path, cover_image)
  255. model_name = os.path.basename(model_path)
  256. return f"Model saved: {model_name}", model_hash, legacy_hash
  257. model_name_filter = ""
  258. def get_filtered_model_paths(s):
  259. if not s:
  260. return ["None"] + list(model_util.lora_models.values())
  261. return ["None"] + [v for v in model_util.lora_models.values() if v and s in v.lower()]
  262. def get_filtered_model_paths_global():
  263. global model_name_filter
  264. return get_filtered_model_paths(model_name_filter)
  265. def setup_ui(addnet_paste_params):
  266. """
  267. :dict addnet_paste_params: Dictionary of txt2img/img2img controls for each model weight slider,
  268. for sending module and model to them from the metadata editor
  269. """
  270. can_edit = False
  271. with gr.Row().style(equal_height=False):
  272. # Lefthand column
  273. with gr.Column(variant='panel'):
  274. # Module and model selector
  275. with gr.Row():
  276. model_filter = gr.Textbox("", label="Model path filter", placeholder="Filter models by path name")
  277. def update_model_filter(s):
  278. global model_name_filter
  279. model_name_filter = s.strip().lower()
  280. model_filter.change(update_model_filter, inputs=[model_filter], outputs=[])
  281. with gr.Row():
  282. module = gr.Dropdown(["LoRA"], label="Network module", value="LoRA", interactive=True, elem_id="additional_networks_metadata_editor_module")
  283. model = gr.Dropdown(get_filtered_model_paths_global(), label="Model", value="None", interactive=True,
  284. elem_id="additional_networks_metadata_editor_model")
  285. modules.ui.create_refresh_button(model, model_util.update_models, lambda: {"choices": get_filtered_model_paths_global()}, "refresh_lora_models")
  286. def submit_model_filter(s):
  287. global model_name_filter
  288. model_name_filter = s
  289. paths = get_filtered_model_paths(s)
  290. return gr.Dropdown.update(choices=paths, value="None")
  291. model_filter.submit(submit_model_filter, inputs=[model_filter], outputs=[model])
  292. # Model hashes and path
  293. with gr.Row():
  294. model_hash = gr.Textbox("", label="Model hash", interactive=False)
  295. legacy_hash = gr.Textbox("", label="Legacy hash", interactive=False)
  296. with gr.Row():
  297. model_path = gr.Textbox("", label="Model path", interactive=False)
  298. open_folder_button = ToolButton(value=folder_symbol, elem_id="hidden_element" if shared.cmd_opts.hide_ui_dir_config else "open_folder_metadata_editor")
  299. # Send to txt2img/img2img buttons
  300. for tabname in ["txt2img", "img2img"]:
  301. with gr.Row():
  302. with gr.Box():
  303. with gr.Row():
  304. gr.HTML(f"Send to {tabname}:")
  305. for i in range(MAX_MODEL_COUNT):
  306. send_to_button = ToolButton(value=keycap_symbols[i], elem_id=f"additional_networks_send_to_{tabname}_{i}")
  307. send_to_button.click(fn=lambda modu, mod: (modu, model_util.find_closest_lora_model_name(mod) or "None"), inputs=[module, model], outputs=[addnet_paste_params[tabname][i]["module"], addnet_paste_params[tabname][i]["model"]])
  308. send_to_button.click(fn=None,_js=f"addnet_switch_to_{tabname}", inputs=None, outputs=None)
  309. # "Copy metadata to other models" panel
  310. with gr.Row():
  311. with gr.Column():
  312. gr.HTML(value="Copy metadata to other models in directory")
  313. copy_metadata_dir = gr.Textbox("", label="Containing directory", placeholder="All models in this directory will receive the selected model's metadata")
  314. with gr.Row():
  315. copy_same_session = gr.Checkbox(True, label="Only copy to models with same session ID")
  316. copy_no_metadata = gr.Checkbox(True, label="Only copy to models with no metadata")
  317. copy_metadata_button = gr.Button("Copy Metadata", variant="primary")
  318. # Center column, metadata viewer/editor
  319. with gr.Column():
  320. with gr.Row():
  321. display_name = gr.Textbox(value="", label="Name", placeholder="Display name for this model", interactive=can_edit)
  322. author = gr.Textbox(value="", label="Author", placeholder="Author of this model", interactive=can_edit)
  323. with gr.Row():
  324. keywords = gr.Textbox(value="", label="Keywords", placeholder="Activation keywords, comma-separated", interactive=can_edit)
  325. with gr.Row():
  326. description = gr.Textbox(value="", label="Description", placeholder="Model description/readme/notes/instructions", lines=15, interactive=can_edit)
  327. with gr.Row():
  328. source = gr.Textbox(value="", label="Source", placeholder="Source URL where this model could be found", interactive=can_edit)
  329. with gr.Row():
  330. rating = gr.Slider(minimum=0, maximum=10, step=1, label="Rating", value=0, interactive=can_edit)
  331. tags = gr.Textbox(value="", label="Tags", placeholder="Comma-separated list of tags (\"artist, style, character, 2d, 3d...\")", lines=2, interactive=can_edit)
  332. with gr.Row():
  333. editing_enabled = gr.Checkbox(label="Editing Enabled", value=can_edit)
  334. with gr.Row():
  335. save_metadata_button = gr.Button("Save Metadata", variant="primary", interactive=can_edit)
  336. with gr.Row():
  337. save_output = gr.HTML("")
  338. # Righthand column, cover image and training parameters view
  339. with gr.Column():
  340. # Cover image
  341. with gr.Row():
  342. cover_image = gr.Image(label="Cover image", elem_id="additional_networks_cover_image", source="upload", interactive=can_edit, type="pil", image_mode="RGBA").style(height=480)
  343. # Image parameters
  344. with gr.Accordion("Image Parameters", open=False):
  345. with gr.Row():
  346. info2 = gr.HTML()
  347. with gr.Row():
  348. try:
  349. send_to_buttons = parameters_copypaste.create_buttons(["txt2img", "img2img", "inpaint", "extras"])
  350. except:
  351. pass
  352. # Training info, below cover image
  353. with gr.Accordion("Training info", open=False):
  354. # Top tags used
  355. with gr.Row():
  356. max_top_tags = int(shared.opts.data.get("additional_networks_max_top_tags", 20))
  357. most_frequent_tags = gr.Label(value={}, label="Most frequent tags in captions", num_top_classes=max_top_tags)
  358. # Dataset folders
  359. with gr.Row():
  360. max_dataset_folders = int(shared.opts.data.get("additional_networks_max_dataset_folders", 20))
  361. dataset_folders = gr.Dataframe(
  362. headers=["Name", "Image Count", "Repeats", "Total Images"],
  363. datatype=["str", "number", "number", "number"],
  364. label="Dataset folder structure",
  365. max_rows=max_dataset_folders,
  366. col_count=(4, "fixed"))
  367. # Training Parameters
  368. with gr.Row():
  369. metadata_view = gr.JSON(value={}, label="Training parameters")
  370. # Hidden/internal
  371. with gr.Row(visible=False):
  372. info1 = gr.HTML()
  373. img_file_info = gr.Textbox(label="Generate Info", interactive=False, lines=6)
  374. open_folder_button.click(fn=lambda p: open_folder(os.path.dirname(p)), inputs=[model_path], outputs=[])
  375. copy_metadata_button.click(fn=copy_metadata_to_all, inputs=[module, model, copy_metadata_dir, copy_same_session, copy_no_metadata, cover_image], outputs=[save_output])
  376. def update_editing(enabled):
  377. """
  378. Enable/disable components based on "Editing Enabled" status
  379. """
  380. updates = [gr.Textbox.update(interactive=enabled)] * 6
  381. updates.append(gr.Image.update(interactive=enabled))
  382. updates.append(gr.Slider.update(interactive=enabled))
  383. updates.append(gr.Button.update(interactive=enabled))
  384. return updates
  385. editing_enabled.change(fn=update_editing, inputs=[editing_enabled], outputs=[display_name, author, source, keywords, description, tags, cover_image, rating, save_metadata_button])
  386. cover_image.change(fn=modules.extras.run_pnginfo, inputs=[cover_image], outputs=[info1, img_file_info, info2])
  387. try:
  388. parameters_copypaste.bind_buttons(send_to_buttons, cover_image, img_file_info)
  389. except:
  390. pass
  391. model.change(refresh_metadata, inputs=[module, model], outputs=[metadata_view, cover_image, display_name, author, source, keywords, description, rating, tags, model_hash, legacy_hash, model_path, copy_metadata_dir, most_frequent_tags, dataset_folders])
  392. save_metadata_button.click(save_metadata, inputs=[module, model, cover_image, display_name, author, source, keywords, description, rating, tags], outputs=[save_output, model_hash, legacy_hash])