Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse lora weights from civitai resources #15712

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion extensions-builtin/Lora/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def read_hash(self):

def get_alias(self):
import networks
if shared.opts.lora_preferred_name == "Filename" or self.alias.lower() in networks.forbidden_network_aliases:
if (hasattr(shared.opts, "lora_preferred_name") and shared.opts.lora_preferred_name == "Filename") or self.alias.lower() in networks.forbidden_network_aliases:
return self.name
else:
return self.alias
Expand Down
14 changes: 14 additions & 0 deletions extensions-builtin/Lora/networks.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import gradio as gr
import json
import logging
import os
import re
Expand Down Expand Up @@ -571,6 +572,7 @@ def list_available_networks():
available_network_aliases.clear()
forbidden_network_aliases.clear()
available_network_hash_lookup.clear()
network_version_id_to_alias.clear()
forbidden_network_aliases.update({"none": 1, "Addams": 1})

os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
Expand All @@ -596,6 +598,17 @@ def list_available_networks():
available_network_aliases[name] = entry
available_network_aliases[entry.alias] = entry

# Try to get modelVersionId from model json
json_path = os.path.join(os.path.dirname(filename), name + ".json")
if os.path.exists(json_path):
try:
with open(json_path, "r", encoding="utf-8") as f:
model_json = json.load(f)
if "modelVersionId" in model_json:
model_ver_id = str(model_json["modelVersionId"])
network_version_id_to_alias[model_ver_id] = entry.get_alias()
except (OSError, json.JSONDecodeError):
errors.report(f"Failed to load network json: {json_path}", exc_info=False)

re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")

Expand Down Expand Up @@ -642,5 +655,6 @@ def infotext_pasted(infotext, params):
networks_in_memory = {}
available_network_hash_lookup = {}
forbidden_network_aliases = {}
network_version_id_to_alias = {}

list_available_networks()
43 changes: 43 additions & 0 deletions modules/infotext_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations
import base64
import importlib
import io
import json
import os
Expand Down Expand Up @@ -230,6 +231,45 @@ def restore_old_hires_fix_params(res):
res['Hires resize-2'] = height


def parse_civitai_resources(x: str):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be implemented in an extension using script_callbacks.on_infotext_pasted

"""parses the Civitai resources string to automatically set the model weights in the prompt:
```
Civitai resources: [{"type":"checkpoint","modelVersionId":290640},{"type":"ImageJobNetworkParams { Strength = 0.4, TriggerWord = , Type = lora }","weight":0.4,"modelVersionId":135867},
{"type":"embed","modelVersionId":250708}]
```
returns a string to append to the prompt
"""
x = "".join(x.strip().split("\n"))
if "Civitai resources:" not in x:
return ""
x = x[x.find("Civitai resources:") + 19:]
if "[" not in x or "]" not in x:
return ""

x = x[x.find("["):x.find("]") + 1]
try:
resources = json.loads(x)
except json.JSONDecodeError:
return ""

prompt_resources = []
for resource in resources:
if "weight" not in resource or "modelVersionId" not in resource:
continue

weight = resource["weight"]
model_version_id = str(resource["modelVersionId"])
networks = importlib.import_module("extensions-builtin.Lora.networks")
if model_version_id in networks.network_version_id_to_alias:
model_name = networks.network_version_id_to_alias[model_version_id]
prompt_resource = f"<lora:{model_name}:{weight}>"
prompt_resources.append(prompt_resource)

if prompt_resources:
return " " + " ".join(prompt_resources)
return ""


def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
"""parses generation parameters string, the one you see in text field under the picture in UI:
```
Expand Down Expand Up @@ -296,6 +336,9 @@ def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
if (shared.opts.infotext_styles == "Apply if any" and found_styles) or shared.opts.infotext_styles == "Apply":
res['Styles array'] = found_styles

# Parse civitai resources
prompt += parse_civitai_resources(x)

res["Prompt"] = prompt
res["Negative prompt"] = negative_prompt

Expand Down