Commit
•
553ec58
1
Parent(s):
46a3b13
Upload 22 files
Browse files- sd_civitai_extension/.gitignore +10 -0
- sd_civitai_extension/DEVELOPING.md +3 -0
- sd_civitai_extension/LICENSE +21 -0
- sd_civitai_extension/README.md +50 -0
- sd_civitai_extension/civitai/generation.py +60 -0
- sd_civitai_extension/civitai/hashes.py +58 -0
- sd_civitai_extension/civitai/lib.py +462 -0
- sd_civitai_extension/civitai/link.py +240 -0
- sd_civitai_extension/civitai/models.py +94 -0
- sd_civitai_extension/install.py +79 -0
- sd_civitai_extension/javascript/across-tabs.min.js +18 -0
- sd_civitai_extension/javascript/civitai.js +102 -0
- sd_civitai_extension/preload.py +6 -0
- sd_civitai_extension/requirements.txt +1 -0
- sd_civitai_extension/scripts/api.py +16 -0
- sd_civitai_extension/scripts/gen_hashing.py +77 -0
- sd_civitai_extension/scripts/info.py +90 -0
- sd_civitai_extension/scripts/link.py +17 -0
- sd_civitai_extension/scripts/pasted.py +16 -0
- sd_civitai_extension/scripts/previews.py +63 -0
- sd_civitai_extension/scripts/settings.py +19 -0
- sd_civitai_extension/style.css +33 -0
sd_civitai_extension/.gitignore
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__pycache__
|
2 |
+
/repositories
|
3 |
+
/venv
|
4 |
+
/outputs
|
5 |
+
/log
|
6 |
+
/webui.settings.bat
|
7 |
+
/.idea
|
8 |
+
.vscode
|
9 |
+
/test/stdout.txt
|
10 |
+
/test/stderr.txt
|
sd_civitai_extension/DEVELOPING.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
I've been referencing this extension repo as a guide:
|
2 |
+
[DreamBooth Extension](https://github.com/d8ahazard/sd_dreambooth_extension/blob/main/scripts/main.py)
|
3 |
+
[stable-diffusion-webui-inspiration](https://github.com/yfszzx/stable-diffusion-webui-inspiration)
|
sd_civitai_extension/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 Civitai
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
sd_civitai_extension/README.md
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Civitai Extension for Automatic 1111 Stable Diffusion Web UI
|
2 |
+
|
3 |
+
Manage and interact with your Automatic 1111 SD instance right from Civitai
|
4 |
+
|
5 |
+
https://user-images.githubusercontent.com/607609/234462691-ecd578cc-b0ec-49e4-8e50-a917395a6874.mp4
|
6 |
+
|
7 |
+
## Features
|
8 |
+
- [x] Automatically download preview images for all models, LORAs, hypernetworks, and embeds
|
9 |
+
- [x] Automatically download a model based on the model hash upon applying pasted generation params
|
10 |
+
- [x] Resources in Metadata: Include the SHA256 hash of all resources used in an image to be able to automatically link to corresponding resources on Civitai
|
11 |
+
- [x] Flexible Resource Naming in Metadata: Hashify the names of resources in prompts to avoid issues with resource renaming and make prompts more portable
|
12 |
+
- [x] **[Civitai Link (Alpha)](https://civitai.com/v/civitai-link-intro):** Optional websocket connection to be able to add/remove resources and more in your SD instance while browsing Civitai or other Civitai Link enabled sites.
|
13 |
+
|
14 |
+
## Installation
|
15 |
+
|
16 |
+
### Through the Extensions UI (Recommended)
|
17 |
+
1. Open the Extensions Tab in Automatic1111 SD Web UI
|
18 |
+
2. In the Extension Tab Open the "Instal from URL" tab
|
19 |
+
3. Paste `https://github.com/civitai/sd_civitai_extension.git` into the URL input
|
20 |
+
4. Press install and wait for it to complete
|
21 |
+
5. **Restart Automatic1111** (Reloading the UI will not install the necessary requirements)
|
22 |
+
|
23 |
+
### Manually
|
24 |
+
1. Download the repo using any method (zip download or cloning)
|
25 |
+
```sh
|
26 |
+
git clone https://github.com/civitai/sd_civitai_extension.git
|
27 |
+
```
|
28 |
+
|
29 |
+
2. After downloading the repo, open a command prompt in that location
|
30 |
+
```sh
|
31 |
+
cd C:\path\to\sd_civitai_extension
|
32 |
+
```
|
33 |
+
|
34 |
+
3. Then run the included install.py script
|
35 |
+
```sh
|
36 |
+
py install.py
|
37 |
+
# OR
|
38 |
+
python install.py
|
39 |
+
```
|
40 |
+
|
41 |
+
## Frequently Asked Questions
|
42 |
+
|
43 |
+
### What the Civitai Link Key? Where do I get it?
|
44 |
+
The Civitai Link Key is a short 6 character token that you'll receive when setting up your Civitai Link instance (you can see it referenced here in this [Civitai Link installation video](https://civitai.com/v/civitai-link-installation)). The Link Key acts as a temporary secret key to connect your Stable Diffusion instance to your Civitai Account inside our link service.
|
45 |
+
|
46 |
+
Since Civitai Link is still in alpha, it is currently only available to Supporters as part of the Civitai Early Access program. You can get access to Civitai Link today by [becoming a supporter](https://civitai.com/pricing) 🥰 or you can wait until we've gotten it to a state that we're ready for a full release.
|
47 |
+
|
48 |
+
## Contribute
|
49 |
+
|
50 |
+
Hop into the development channel in our [Discord server](https://discord.gg/UwX5wKwm6c) and let's chat!
|
sd_civitai_extension/civitai/generation.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# api endpoints
|
2 |
+
from modules import shared
|
3 |
+
from modules.api.api import encode_pil_to_base64, validate_sampler_name
|
4 |
+
from modules.api.models import StableDiffusionTxt2ImgProcessingAPI, TextToImageResponse
|
5 |
+
from modules.processing import StableDiffusionProcessingTxt2Img, process_images
|
6 |
+
from modules.call_queue import queue_lock
|
7 |
+
|
8 |
+
from civitai.models import CommandImageTxt2Img
|
9 |
+
import civitai.lib as lib
|
10 |
+
|
11 |
+
def internal_txt2img(txt2imgreq: StableDiffusionTxt2ImgProcessingAPI):
|
12 |
+
populate = txt2imgreq.copy(update={ # Override __init__ params
|
13 |
+
"sampler_name": validate_sampler_name(txt2imgreq.sampler_name or txt2imgreq.sampler_index),
|
14 |
+
"do_not_save_samples": True,
|
15 |
+
"do_not_save_grid": True
|
16 |
+
}
|
17 |
+
)
|
18 |
+
if populate.sampler_name:
|
19 |
+
populate.sampler_index = None # prevent a warning later on
|
20 |
+
|
21 |
+
args = vars(populate)
|
22 |
+
args.pop('script_name', None)
|
23 |
+
args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
|
24 |
+
args.pop('alwayson_scripts', None)
|
25 |
+
|
26 |
+
send_images = args.pop('send_images', True)
|
27 |
+
args.pop('save_images', None)
|
28 |
+
|
29 |
+
with queue_lock:
|
30 |
+
p = StableDiffusionProcessingTxt2Img(sd_model=shared.sd_model, **args)
|
31 |
+
|
32 |
+
shared.state.begin()
|
33 |
+
processed = process_images(p)
|
34 |
+
shared.state.end()
|
35 |
+
|
36 |
+
b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
|
37 |
+
|
38 |
+
return TextToImageResponse(images=b64images, parameters=vars(txt2imgreq), info=processed.js())
|
39 |
+
|
40 |
+
def txt2img(command: CommandImageTxt2Img):
|
41 |
+
# TODO: Add support for VAEs
|
42 |
+
# if (command['vae'] is None): lib.clear_vae()
|
43 |
+
|
44 |
+
if (command['model'] is not None): lib.select_model({ 'hash': command['model'] })
|
45 |
+
# if (command['vae'] is not None): lib.select_vae(command['vae'])
|
46 |
+
|
47 |
+
return internal_txt2img(
|
48 |
+
StableDiffusionTxt2ImgProcessingAPI(
|
49 |
+
prompt=command['params']['prompt'],
|
50 |
+
negative_prompt=command['params']['negativePrompt'],
|
51 |
+
seed=command['params']['seed'],
|
52 |
+
steps=command['params']['steps'],
|
53 |
+
width=command['params']['width'],
|
54 |
+
height=command['params']['height'],
|
55 |
+
cfg_scale=command['params']['cfgScale'],
|
56 |
+
clip_skip=command['params']['clipSkip'],
|
57 |
+
n_iter=command['quantity'],
|
58 |
+
batch_size=command['batchSize'],
|
59 |
+
)
|
60 |
+
)
|
sd_civitai_extension/civitai/hashes.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from blake3 import blake3 as hasher
|
2 |
+
import os.path
|
3 |
+
|
4 |
+
from modules import hashes as sd_hashes
|
5 |
+
|
6 |
+
# NOTE: About this file
|
7 |
+
# ---------------------------------
|
8 |
+
# This is not being used. It was added to see if Blake3 was faster than SHA256.
|
9 |
+
# It was not noticeably faster in our tests, so we are sticking with SHA256 for now.
|
10 |
+
# Especially since SHA256 is the standard inside this UI.
|
11 |
+
|
12 |
+
# cache_key = "civitai_hashes"
|
13 |
+
|
14 |
+
# def blake3_from_cache(filename, title):
|
15 |
+
# hashes = sd_hashes.cache(cache_key)
|
16 |
+
# ondisk_mtime = os.path.getmtime(filename)
|
17 |
+
|
18 |
+
# if title not in hashes:
|
19 |
+
# return None
|
20 |
+
|
21 |
+
# cached_blake3 = hashes[title].get("blake3", None)
|
22 |
+
# cached_mtime = hashes[title].get("mtime", 0)
|
23 |
+
|
24 |
+
# if ondisk_mtime > cached_mtime or cached_blake3 is None:
|
25 |
+
# return None
|
26 |
+
|
27 |
+
# return cached_blake3
|
28 |
+
|
29 |
+
# def calculate_blake3(filename):
|
30 |
+
# hash_blake3 = hasher()
|
31 |
+
# blksize = 1024 * 1024
|
32 |
+
|
33 |
+
# with open(filename, "rb") as f:
|
34 |
+
# for chunk in iter(lambda: f.read(blksize), b""):
|
35 |
+
# hash_blake3.update(chunk)
|
36 |
+
|
37 |
+
# return hash_blake3.hexdigest()
|
38 |
+
|
39 |
+
# def blake3(filename, title):
|
40 |
+
# hashes = sd_hashes.cache(cache_key)
|
41 |
+
|
42 |
+
# blake3_value = blake3_from_cache(filename, title)
|
43 |
+
# if blake3_value is not None:
|
44 |
+
# return blake3_value
|
45 |
+
|
46 |
+
# print(f"Calculating blake3 for {filename}: ", end='')
|
47 |
+
# blake3_value = calculate_blake3(filename)
|
48 |
+
# print(f"{blake3_value}")
|
49 |
+
|
50 |
+
# if title not in hashes:
|
51 |
+
# hashes[title] = {}
|
52 |
+
|
53 |
+
# hashes[title]["mtime"] = os.path.getmtime(filename)
|
54 |
+
# hashes[title]["blake3"] = blake3_value
|
55 |
+
|
56 |
+
# sd_hashes.dump_cache()
|
57 |
+
|
58 |
+
# return blake3_value
|
sd_civitai_extension/civitai/lib.py
ADDED
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import shutil
|
4 |
+
import tempfile
|
5 |
+
import time
|
6 |
+
from typing import List
|
7 |
+
import requests
|
8 |
+
import glob
|
9 |
+
|
10 |
+
from tqdm import tqdm
|
11 |
+
from modules import shared, sd_models, sd_vae, hashes
|
12 |
+
from modules.paths import models_path
|
13 |
+
from civitai.models import Command, ResourceRequest
|
14 |
+
|
15 |
+
#region shared variables
|
16 |
+
try:
|
17 |
+
base_url = shared.cmd_opts.civitai_endpoint
|
18 |
+
except:
|
19 |
+
base_url = 'https://civitai.com/api/v1'
|
20 |
+
|
21 |
+
connected = False
|
22 |
+
user_agent = 'CivitaiLink:Automatic1111'
|
23 |
+
download_chunk_size = 8192
|
24 |
+
cache_key = 'civitai'
|
25 |
+
#endregion
|
26 |
+
|
27 |
+
#region Utils
|
28 |
+
def log(message):
|
29 |
+
"""Log a message to the console."""
|
30 |
+
print(f'Civitai: {message}')
|
31 |
+
|
32 |
+
def download_file(url, dest, on_progress=None):
|
33 |
+
if os.path.exists(dest):
|
34 |
+
log(f'File already exists: {dest}')
|
35 |
+
|
36 |
+
log(f'Downloading: "{url}" to {dest}\n')
|
37 |
+
|
38 |
+
response = requests.get(url, stream=True, headers={"User-Agent": user_agent})
|
39 |
+
total = int(response.headers.get('content-length', 0))
|
40 |
+
start_time = time.time()
|
41 |
+
|
42 |
+
dest = os.path.expanduser(dest)
|
43 |
+
dst_dir = os.path.dirname(dest)
|
44 |
+
f = tempfile.NamedTemporaryFile(delete=False, dir=dst_dir)
|
45 |
+
|
46 |
+
try:
|
47 |
+
current = 0
|
48 |
+
with tqdm(total=total, unit='B', unit_scale=True, unit_divisor=1024) as bar:
|
49 |
+
for data in response.iter_content(chunk_size=download_chunk_size):
|
50 |
+
current += len(data)
|
51 |
+
pos = f.write(data)
|
52 |
+
bar.update(pos)
|
53 |
+
if on_progress is not None:
|
54 |
+
should_stop = on_progress(current, total, start_time)
|
55 |
+
if should_stop == True:
|
56 |
+
raise Exception('Download cancelled')
|
57 |
+
f.close()
|
58 |
+
shutil.move(f.name, dest)
|
59 |
+
except OSError as e:
|
60 |
+
print(f"Could not write the preview file to {dst_dir}")
|
61 |
+
print(e)
|
62 |
+
finally:
|
63 |
+
f.close()
|
64 |
+
if os.path.exists(f.name):
|
65 |
+
os.remove(f.name)
|
66 |
+
#endregion Utils
|
67 |
+
|
68 |
+
#region API
|
69 |
+
def req(endpoint, method='GET', data=None, params=None, headers=None):
|
70 |
+
"""Make a request to the Civitai API."""
|
71 |
+
if headers is None:
|
72 |
+
headers = {}
|
73 |
+
headers['User-Agent'] = user_agent
|
74 |
+
api_key = shared.opts.data.get("civitai_api_key", None)
|
75 |
+
if api_key is not None:
|
76 |
+
headers['Authorization'] = f'Bearer {api_key}'
|
77 |
+
if data is not None:
|
78 |
+
headers['Content-Type'] = 'application/json'
|
79 |
+
data = json.dumps(data)
|
80 |
+
if not endpoint.startswith('/'):
|
81 |
+
endpoint = '/' + endpoint
|
82 |
+
if params is None:
|
83 |
+
params = {}
|
84 |
+
response = requests.request(method, base_url+endpoint, data=data, params=params, headers=headers)
|
85 |
+
if response.status_code != 200:
|
86 |
+
raise Exception(f'Error: {response.status_code} {response.text}')
|
87 |
+
return response.json()
|
88 |
+
|
89 |
+
def get_models(query, creator, tag, type, page=1, page_size=20, sort='Most Downloaded', period='AllTime'):
|
90 |
+
"""Get a list of models from the Civitai API."""
|
91 |
+
response = req('/models', params={
|
92 |
+
'query': query,
|
93 |
+
'username': creator,
|
94 |
+
'tag': tag,
|
95 |
+
'type': type,
|
96 |
+
'sort': sort,
|
97 |
+
'period': period,
|
98 |
+
'page': page,
|
99 |
+
'pageSize': page_size,
|
100 |
+
})
|
101 |
+
return response
|
102 |
+
|
103 |
+
def get_all_by_hash(hashes: List[str]):
|
104 |
+
response = req(f"/model-versions/by-hash", method='POST', data=hashes)
|
105 |
+
return response
|
106 |
+
|
107 |
+
def get_model_version(id):
|
108 |
+
"""Get a model version from the Civitai API."""
|
109 |
+
response = req('/model-versions/'+id)
|
110 |
+
return response
|
111 |
+
|
112 |
+
def get_model_version_by_hash(hash: str):
|
113 |
+
response = req(f"/model-versions/by-hash/{hash}")
|
114 |
+
return response
|
115 |
+
|
116 |
+
def get_creators(query, page=1, page_size=20):
|
117 |
+
"""Get a list of creators from the Civitai API."""
|
118 |
+
response = req('/creators', params={
|
119 |
+
'query': query,
|
120 |
+
'page': page,
|
121 |
+
'pageSize': page_size
|
122 |
+
})
|
123 |
+
return response
|
124 |
+
|
125 |
+
def get_tags(query, page=1, page_size=20):
|
126 |
+
"""Get a list of tags from the Civitai API."""
|
127 |
+
response = req('/tags', params={
|
128 |
+
'query': query,
|
129 |
+
'page': page,
|
130 |
+
'pageSize': page_size
|
131 |
+
})
|
132 |
+
return response
|
133 |
+
#endregion API
|
134 |
+
|
135 |
+
#region Get Utils
|
136 |
+
def get_lora_dir():
|
137 |
+
lora_dir = shared.opts.data.get('civitai_folder_lora', shared.cmd_opts.lora_dir).strip()
|
138 |
+
if not lora_dir: lora_dir = shared.cmd_opts.lora_dir
|
139 |
+
return lora_dir
|
140 |
+
|
141 |
+
def get_locon_dir():
|
142 |
+
try:
|
143 |
+
lyco_dir = shared.opts.data.get('civitai_folder_lyco', shared.cmd_opts.lyco_dir).strip()
|
144 |
+
if not lyco_dir: lyco_dir = shared.cmd_opts.lyco_dir
|
145 |
+
if not lyco_dir: lyco_dir = os.path.join(models_path, "LyCORIS"),
|
146 |
+
return lyco_dir
|
147 |
+
except:
|
148 |
+
return get_lora_dir()
|
149 |
+
|
150 |
+
def get_model_dir():
|
151 |
+
model_dir = shared.opts.data.get('civitai_folder_model', shared.cmd_opts.ckpt_dir)
|
152 |
+
if not model_dir: model_dir = shared.cmd_opts.ckpt_dir
|
153 |
+
if not model_dir: model_dir = sd_models.model_path
|
154 |
+
return model_dir.strip()
|
155 |
+
|
156 |
+
def get_automatic_type(type: str):
|
157 |
+
if type == 'Hypernetwork': return 'hypernet'
|
158 |
+
return type.lower()
|
159 |
+
|
160 |
+
def get_automatic_name(type: str, filename: str, folder: str):
|
161 |
+
abspath = os.path.abspath(filename)
|
162 |
+
if abspath.startswith(folder):
|
163 |
+
fullname = abspath.replace(folder, '')
|
164 |
+
else:
|
165 |
+
fullname = os.path.basename(filename)
|
166 |
+
|
167 |
+
if fullname.startswith("\\") or fullname.startswith("/"):
|
168 |
+
fullname = fullname[1:]
|
169 |
+
|
170 |
+
if type == 'Checkpoint': return fullname
|
171 |
+
return os.path.splitext(fullname)[0]
|
172 |
+
|
173 |
+
def has_preview(filename: str):
|
174 |
+
return os.path.isfile(os.path.splitext(filename)[0] + '.preview.png')
|
175 |
+
|
176 |
+
def has_info(filename: str):
|
177 |
+
return os.path.isfile(os.path.splitext(filename)[0] + '.json')
|
178 |
+
|
179 |
+
def get_resources_in_folder(type, folder, exts=[], exts_exclude=[]):
|
180 |
+
resources = []
|
181 |
+
os.makedirs(folder, exist_ok=True)
|
182 |
+
|
183 |
+
candidates = []
|
184 |
+
for ext in exts:
|
185 |
+
candidates += glob.glob(os.path.join(folder, '**/*.' + ext), recursive=True)
|
186 |
+
for ext in exts_exclude:
|
187 |
+
candidates = [x for x in candidates if not x.endswith(ext)]
|
188 |
+
|
189 |
+
folder = os.path.abspath(folder)
|
190 |
+
automatic_type = get_automatic_type(type)
|
191 |
+
for filename in sorted(candidates):
|
192 |
+
if os.path.isdir(filename):
|
193 |
+
continue
|
194 |
+
|
195 |
+
name = os.path.splitext(os.path.basename(filename))[0]
|
196 |
+
automatic_name = get_automatic_name(type, filename, folder)
|
197 |
+
hash = hashes.sha256(filename, f"{automatic_type}/{automatic_name}")
|
198 |
+
|
199 |
+
resources.append({'type': type, 'name': name, 'hash': hash, 'path': filename, 'hasPreview': has_preview(filename), 'hasInfo': has_info(filename) })
|
200 |
+
|
201 |
+
return resources
|
202 |
+
|
203 |
+
resources = []
|
204 |
+
def load_resource_list(types=['LORA', 'LoCon', 'Hypernetwork', 'TextualInversion', 'Checkpoint', 'VAE', 'Controlnet']):
|
205 |
+
global resources
|
206 |
+
|
207 |
+
# If resources is empty and types is empty, load all types
|
208 |
+
# This is a helper to be able to get the resource list without
|
209 |
+
# having to worry about initialization. On subsequent calls, no work will be done
|
210 |
+
if len(resources) == 0 and len(types) == 0:
|
211 |
+
types = ['LORA', 'LoCon', 'Hypernetwork', 'TextualInversion', 'Checkpoint', 'VAE', 'Controlnet']
|
212 |
+
|
213 |
+
if 'LORA' in types:
|
214 |
+
resources = [r for r in resources if r['type'] != 'LORA']
|
215 |
+
resources += get_resources_in_folder('LORA', get_lora_dir(), ['pt', 'safetensors', 'ckpt'])
|
216 |
+
if 'LoCon' in types:
|
217 |
+
resources = [r for r in resources if r['type'] != 'LoCon']
|
218 |
+
resources += get_resources_in_folder('LoCon', get_locon_dir(), ['pt', 'safetensors', 'ckpt'])
|
219 |
+
if 'Hypernetwork' in types:
|
220 |
+
resources = [r for r in resources if r['type'] != 'Hypernetwork']
|
221 |
+
resources += get_resources_in_folder('Hypernetwork', shared.cmd_opts.hypernetwork_dir, ['pt', 'safetensors', 'ckpt'])
|
222 |
+
if 'TextualInversion' in types:
|
223 |
+
resources = [r for r in resources if r['type'] != 'TextualInversion']
|
224 |
+
resources += get_resources_in_folder('TextualInversion', shared.cmd_opts.embeddings_dir, ['pt', 'bin', 'safetensors'])
|
225 |
+
if 'Checkpoint' in types:
|
226 |
+
resources = [r for r in resources if r['type'] != 'Checkpoint']
|
227 |
+
resources += get_resources_in_folder('Checkpoint', get_model_dir(), ['safetensors', 'ckpt'], ['vae.safetensors', 'vae.ckpt'])
|
228 |
+
if 'Controlnet' in types:
|
229 |
+
resources = [r for r in resources if r['type'] != 'Controlnet']
|
230 |
+
resources += get_resources_in_folder('Controlnet', os.path.join(models_path, "ControlNet"), ['safetensors', 'ckpt'], ['vae.safetensors', 'vae.ckpt'])
|
231 |
+
if 'VAE' in types:
|
232 |
+
resources = [r for r in resources if r['type'] != 'VAE']
|
233 |
+
resources += get_resources_in_folder('VAE', get_model_dir(), ['vae.pt', 'vae.safetensors', 'vae.ckpt'])
|
234 |
+
resources += get_resources_in_folder('VAE', sd_vae.vae_path, ['pt', 'safetensors', 'ckpt'])
|
235 |
+
|
236 |
+
return resources
|
237 |
+
|
238 |
+
def get_resource_by_hash(hash: str):
|
239 |
+
resources = load_resource_list([])
|
240 |
+
|
241 |
+
found = [resource for resource in resources if hash.lower() == resource['hash'] and ('downloading' not in resource or resource['downloading'] != True)]
|
242 |
+
if found:
|
243 |
+
return found[0]
|
244 |
+
|
245 |
+
return None
|
246 |
+
|
247 |
+
def get_model_by_hash(hash: str):
|
248 |
+
found = [info for info in sd_models.checkpoints_list.values() if hash == info.sha256 or hash == info.shorthash or hash == info.hash]
|
249 |
+
if found:
|
250 |
+
return found[0]
|
251 |
+
|
252 |
+
return None
|
253 |
+
|
254 |
+
#endregion Get Utils
|
255 |
+
|
256 |
+
#region Removing
|
257 |
+
def remove_resource(resource: ResourceRequest):
|
258 |
+
removed = None
|
259 |
+
target = get_resource_by_hash(resource['hash'])
|
260 |
+
if target is None or target['type'] != resource['type']: removed = False
|
261 |
+
elif os.path.exists(target['path']):
|
262 |
+
os.remove(target['path'])
|
263 |
+
removed = True
|
264 |
+
|
265 |
+
if removed == True:
|
266 |
+
log(f'Removed resource')
|
267 |
+
load_resource_list([resource['type']])
|
268 |
+
if resource['type'] == 'Checkpoint':
|
269 |
+
sd_models.list_models()
|
270 |
+
elif resource['type'] == 'Hypernetwork':
|
271 |
+
shared.reload_hypernetworks()
|
272 |
+
# elif resource['type'] == 'LORA':
|
273 |
+
# TODO: reload LORA
|
274 |
+
elif removed == None:
|
275 |
+
log(f'Resource not found')
|
276 |
+
#endregion Removing
|
277 |
+
|
278 |
+
#region Downloading
|
279 |
+
def load_if_missing(path, url, on_progress=None):
|
280 |
+
if os.path.exists(path): return True
|
281 |
+
if url is None: return False
|
282 |
+
|
283 |
+
download_file(url, path, on_progress)
|
284 |
+
return None
|
285 |
+
|
286 |
+
def load_resource(resource: ResourceRequest, on_progress=None):
|
287 |
+
resource['hash'] = resource['hash'].lower()
|
288 |
+
existing_resource = get_resource_by_hash(resource['hash'])
|
289 |
+
if existing_resource:
|
290 |
+
log(f'Already have resource: {resource["name"]}')
|
291 |
+
return
|
292 |
+
|
293 |
+
resources.append({'type': resource['type'], 'name': resource['name'], 'hash': resource['hash'], 'downloading': True })
|
294 |
+
|
295 |
+
if resource['type'] == 'Checkpoint': load_model(resource, on_progress)
|
296 |
+
elif resource['type'] == 'CheckpointConfig': load_model_config(resource, on_progress)
|
297 |
+
elif resource['type'] == 'Controlnet': load_controlnet(resource, on_progress)
|
298 |
+
elif resource['type'] == 'Hypernetwork': load_hypernetwork(resource, on_progress)
|
299 |
+
elif resource['type'] == 'TextualInversion': load_textual_inversion(resource, on_progress)
|
300 |
+
elif resource['type'] == 'LORA': load_lora(resource, on_progress)
|
301 |
+
elif resource['type'] == 'LoCon': load_locon(resource, on_progress)
|
302 |
+
|
303 |
+
load_resource_list([resource['type']])
|
304 |
+
|
305 |
+
def fetch_model_by_hash(hash: str):
|
306 |
+
model_version = get_model_version_by_hash(hash)
|
307 |
+
if model_version is None:
|
308 |
+
log(f'Could not find model version with hash {hash}')
|
309 |
+
return None
|
310 |
+
|
311 |
+
file = [x for x in model_version['files'] if x['primary'] == True][0]
|
312 |
+
resource = ResourceRequest(
|
313 |
+
name=file['name'],
|
314 |
+
type='Checkpoint',
|
315 |
+
hash=file['hashes']['SHA256'],
|
316 |
+
url=file['downloadUrl']
|
317 |
+
)
|
318 |
+
load_resource(resource)
|
319 |
+
|
320 |
+
def load_model_config(resource: ResourceRequest, on_progress=None):
|
321 |
+
load_if_missing(os.path.join(get_model_dir(), resource['name']), resource['url'], on_progress)
|
322 |
+
|
323 |
+
def load_model(resource: ResourceRequest, on_progress=None):
|
324 |
+
model = get_model_by_hash(resource['hash'])
|
325 |
+
if model is not None:
|
326 |
+
log('Found model in model list')
|
327 |
+
if model is None and resource['url'] is not None:
|
328 |
+
log('Downloading model')
|
329 |
+
download_file(resource['url'], os.path.join(get_model_dir(), resource['name']), on_progress)
|
330 |
+
sd_models.list_models()
|
331 |
+
model = get_model_by_hash(resource['hash'])
|
332 |
+
|
333 |
+
return model
|
334 |
+
|
335 |
+
def load_controlnet(resource: ResourceRequest, on_progress=None):
|
336 |
+
isAvailable = load_if_missing(os.path.join(models_path, 'ControlNet', resource['name']), resource['url'], on_progress)
|
337 |
+
# TODO: reload controlnet list - not sure best way to import this
|
338 |
+
# if isAvailable is None:
|
339 |
+
# controlnet.list_available_models()
|
340 |
+
|
341 |
+
def load_textual_inversion(resource: ResourceRequest, on_progress=None):
|
342 |
+
load_if_missing(os.path.join(shared.cmd_opts.embeddings_dir, resource['name']), resource['url'], on_progress)
|
343 |
+
|
344 |
+
def load_lora(resource: ResourceRequest, on_progress=None):
|
345 |
+
isAvailable = load_if_missing(os.path.join(get_lora_dir(), resource['name']), resource['url'], on_progress)
|
346 |
+
# TODO: reload lora list - not sure best way to import this
|
347 |
+
# if isAvailable is None:
|
348 |
+
# lora.list_available_loras()
|
349 |
+
|
350 |
+
def load_locon(resource: ResourceRequest, on_progress=None):
|
351 |
+
isAvailable = load_if_missing(os.path.join(get_locon_dir(), resource['name']), resource['url'], on_progress)
|
352 |
+
# TODO: reload locon list - not sure best way to import this
|
353 |
+
# if isAvailable is None:
|
354 |
+
# lora.list_available_loras()
|
355 |
+
|
356 |
+
def load_vae(resource: ResourceRequest, on_progress=None):
|
357 |
+
# TODO: find by hash instead of name
|
358 |
+
if not resource['name'].endswith('.pt'): resource['name'] += '.pt'
|
359 |
+
full_path = os.path.join(models_path, 'VAE', resource['name'])
|
360 |
+
|
361 |
+
isAvailable = load_if_missing(full_path, resource['url'], on_progress)
|
362 |
+
if isAvailable is None:
|
363 |
+
sd_vae.refresh_vae_list()
|
364 |
+
|
365 |
+
def load_hypernetwork(resource: ResourceRequest, on_progress=None):
|
366 |
+
full_path = os.path.join(shared.cmd_opts.hypernetwork_dir, resource['name']);
|
367 |
+
if not full_path.endswith('.pt'): full_path += '.pt'
|
368 |
+
isAvailable = load_if_missing(full_path, resource['url'], on_progress)
|
369 |
+
if isAvailable is None:
|
370 |
+
shared.reload_hypernetworks()
|
371 |
+
|
372 |
+
#endregion Downloading
|
373 |
+
|
374 |
+
#region Selecting Resources
|
375 |
+
def select_model(resource: ResourceRequest):
|
376 |
+
if shared.opts.data["sd_checkpoint_hash"] == resource['hash']: return
|
377 |
+
|
378 |
+
model = load_model(resource)
|
379 |
+
|
380 |
+
if shared.sd_model.sd_checkpoint_info.model_name == model.model_name:
|
381 |
+
return
|
382 |
+
if model is not None:
|
383 |
+
sd_models.load_model(model)
|
384 |
+
shared.opts.save(shared.config_filename)
|
385 |
+
else: log('Could not find model and no URL was provided')
|
386 |
+
|
387 |
+
def select_vae(resource: ResourceRequest):
|
388 |
+
# TODO: find by hash instead of name
|
389 |
+
if not resource['name'].endswith('.pt'): resource['name'] += '.pt'
|
390 |
+
full_path = os.path.join(models_path, 'VAE', resource['name'])
|
391 |
+
|
392 |
+
if sd_vae.loaded_vae_file is not None and sd_vae.get_filename(sd_vae.loaded_vae_file) == resource['name']:
|
393 |
+
log('VAE already loaded')
|
394 |
+
return
|
395 |
+
|
396 |
+
isAvailable = load_if_missing(full_path, resource['url'])
|
397 |
+
if not isAvailable:
|
398 |
+
log('Could not find VAE')
|
399 |
+
return
|
400 |
+
|
401 |
+
sd_vae.refresh_vae_list()
|
402 |
+
sd_vae.load_vae(shared.sd_model, full_path)
|
403 |
+
|
404 |
+
def clear_vae():
|
405 |
+
log('Clearing VAE')
|
406 |
+
sd_vae.clear_loaded_vae()
|
407 |
+
|
408 |
+
def select_hypernetwork(resource: ResourceRequest):
|
409 |
+
# TODO: find by hash instead of name
|
410 |
+
if shared.opts.sd_hypernetwork == resource['name']:
|
411 |
+
log('Hypernetwork already loaded')
|
412 |
+
return
|
413 |
+
|
414 |
+
full_path = os.path.join(shared.cmd_opts.hypernetwork_dir, resource['name']);
|
415 |
+
if not full_path.endswith('.pt'): full_path += '.pt'
|
416 |
+
isAvailable = load_if_missing(full_path, resource['url'])
|
417 |
+
if not isAvailable:
|
418 |
+
log('Could not find hypernetwork')
|
419 |
+
return
|
420 |
+
|
421 |
+
shared.opts.sd_hypernetwork = resource['name']
|
422 |
+
shared.opts.save(shared.config_filename)
|
423 |
+
shared.reload_hypernetworks()
|
424 |
+
|
425 |
+
def clear_hypernetwork():
|
426 |
+
if (shared.opts.sd_hypernetwork == 'None'): return
|
427 |
+
|
428 |
+
log('Clearing hypernetwork')
|
429 |
+
shared.opts.sd_hypernetwork = 'None'
|
430 |
+
shared.opts.save(shared.config_filename)
|
431 |
+
shared.reload_hypernetworks()
|
432 |
+
#endregion
|
433 |
+
|
434 |
+
#region Resource Management
|
435 |
+
def update_resource_preview(hash: str, preview_url: str):
|
436 |
+
resources = load_resource_list([])
|
437 |
+
matches = [resource for resource in resources if hash.lower() == resource['hash']]
|
438 |
+
if len(matches) == 0: return
|
439 |
+
|
440 |
+
for resource in matches:
|
441 |
+
# download image and save to resource['path'] - ext + '.preview.png'
|
442 |
+
preview_path = os.path.splitext(resource['path'])[0] + '.preview.png'
|
443 |
+
download_file(preview_url, preview_path)
|
444 |
+
|
445 |
+
#endregion Selecting Resources
|
446 |
+
|
447 |
+
#region Activities
|
448 |
+
activities = []
|
449 |
+
activity_history_length = 10
|
450 |
+
ignore_activity_types = ['resources:list','activities:list','activities:clear', 'activities:cancel']
|
451 |
+
def add_activity(activity: Command):
|
452 |
+
global activities
|
453 |
+
|
454 |
+
if activity['type'] in ignore_activity_types: return
|
455 |
+
|
456 |
+
existing_activity_index = [i for i, x in enumerate(activities) if x['id'] == activity['id']]
|
457 |
+
if len(existing_activity_index) > 0: activities[existing_activity_index[0]] = activity
|
458 |
+
else: activities.insert(0, activity)
|
459 |
+
|
460 |
+
if len(activities) > activity_history_length:
|
461 |
+
activities.pop()
|
462 |
+
#endregion
|
sd_civitai_extension/civitai/link.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime, timezone
|
2 |
+
import time
|
3 |
+
from typing import List
|
4 |
+
import socketio
|
5 |
+
|
6 |
+
import civitai.lib as civitai
|
7 |
+
import civitai.generation as generation
|
8 |
+
from civitai.models import Command, CommandActivitiesList, CommandImageTxt2Img, CommandResourcesAdd, CommandActivitiesCancel, CommandResourcesList, CommandResourcesRemove, ErrorPayload, JoinedPayload, RoomPresence, UpgradeKeyPayload
|
9 |
+
|
10 |
+
from modules import shared, sd_models, script_callbacks, hashes
|
11 |
+
|
12 |
+
#region Civitai Link Utils
|
13 |
+
def log(message: str):
|
14 |
+
if not shared.opts.data.get('civitai_link_logging', True): return
|
15 |
+
print(f'Civitai Link: {message}')
|
16 |
+
#endregion
|
17 |
+
|
18 |
+
#region Civitai Link Command Handlers
|
19 |
+
def send_resources(types: List[str] = []):
|
20 |
+
command_response({'type': 'resources:list', 'resources': civitai.load_resource_list(types)})
|
21 |
+
|
22 |
+
def on_resources_list(payload: CommandResourcesList):
|
23 |
+
types = payload['types'] if 'types' in payload else []
|
24 |
+
payload['resources'] = civitai.load_resource_list(types)
|
25 |
+
payload['status'] = 'success'
|
26 |
+
command_response(payload)
|
27 |
+
|
28 |
+
def on_activities_list(payload: CommandActivitiesList):
|
29 |
+
payload['activities'] = civitai.activities
|
30 |
+
payload['status'] = 'success'
|
31 |
+
command_response(payload)
|
32 |
+
|
33 |
+
def on_activities_clear(payload: CommandActivitiesList):
|
34 |
+
civitai.activities = []
|
35 |
+
payload['activities'] = civitai.activities
|
36 |
+
payload['status'] = 'success'
|
37 |
+
command_response(payload)
|
38 |
+
|
39 |
+
report_interval = 1
|
40 |
+
processing_activities: List[str] = []
|
41 |
+
should_cancel_activity: List[str] = []
|
42 |
+
def on_resources_add(payload: CommandResourcesAdd):
|
43 |
+
resource = payload['resource']
|
44 |
+
payload['status'] = 'processing'
|
45 |
+
|
46 |
+
last_report = time.time()
|
47 |
+
def report_status(force=False):
|
48 |
+
nonlocal last_report
|
49 |
+
current_time = time.time()
|
50 |
+
if force or current_time - last_report > report_interval:
|
51 |
+
command_response(payload, history=True)
|
52 |
+
last_report = current_time
|
53 |
+
|
54 |
+
notified_of_download = False
|
55 |
+
def on_progress(current: int, total: int, start_time: float):
|
56 |
+
nonlocal notified_of_download
|
57 |
+
if not notified_of_download:
|
58 |
+
send_resources()
|
59 |
+
notified_of_download = True
|
60 |
+
|
61 |
+
if payload['id'] in should_cancel_activity:
|
62 |
+
should_cancel_activity.remove(payload['id'])
|
63 |
+
dl_resources = [r for r in civitai.resources if r['hash'] == resource['hash'] and r['downloading'] == True]
|
64 |
+
if len(dl_resources) > 0:
|
65 |
+
civitai.resources.remove(dl_resources[0])
|
66 |
+
payload['status'] = 'canceled'
|
67 |
+
return True
|
68 |
+
|
69 |
+
current_time = time.time()
|
70 |
+
elapsed_time = current_time - start_time
|
71 |
+
speed = current / elapsed_time
|
72 |
+
remaining_time = (total - current) / speed
|
73 |
+
progress = current / total * 100
|
74 |
+
payload['status'] = 'processing'
|
75 |
+
payload['progress'] = progress
|
76 |
+
payload['remainingTime'] = remaining_time
|
77 |
+
payload['speed'] = speed
|
78 |
+
report_status()
|
79 |
+
|
80 |
+
try:
|
81 |
+
processing_activities.append(payload['id'])
|
82 |
+
civitai.load_resource(resource, on_progress)
|
83 |
+
if payload['status'] != 'canceled':
|
84 |
+
payload['status'] = 'success'
|
85 |
+
except Exception as e:
|
86 |
+
log(e)
|
87 |
+
if payload['status'] != 'canceled':
|
88 |
+
payload['status'] = 'error'
|
89 |
+
payload['error'] = 'Failed to download resource'
|
90 |
+
|
91 |
+
processing_activities.remove(payload['id'])
|
92 |
+
report_status(True)
|
93 |
+
send_resources()
|
94 |
+
|
95 |
+
def on_activities_cancel(payload: CommandActivitiesCancel):
|
96 |
+
activity_id = payload['activityId']
|
97 |
+
if activity_id not in processing_activities:
|
98 |
+
payload['status'] = 'error'
|
99 |
+
payload['error'] = 'Activity not found or already completed'
|
100 |
+
else:
|
101 |
+
should_cancel_activity.append(activity_id)
|
102 |
+
payload['status'] = 'success'
|
103 |
+
|
104 |
+
command_response(payload)
|
105 |
+
|
106 |
+
def on_resources_remove(payload: CommandResourcesRemove):
|
107 |
+
try:
|
108 |
+
civitai.remove_resource(payload['resource'])
|
109 |
+
payload['status'] = 'success'
|
110 |
+
except Exception as e:
|
111 |
+
log(e)
|
112 |
+
payload['status'] = 'error'
|
113 |
+
payload['error'] = 'Failed to remove resource'
|
114 |
+
|
115 |
+
command_response(payload, history=True)
|
116 |
+
send_resources()
|
117 |
+
|
118 |
+
def on_image_txt2img(payload: CommandImageTxt2Img):
|
119 |
+
try:
|
120 |
+
result = generation.txt2img(payload)
|
121 |
+
payload['status'] = 'success'
|
122 |
+
payload['images'] = result.images
|
123 |
+
except Exception as e:
|
124 |
+
log(e)
|
125 |
+
payload['status'] = 'error'
|
126 |
+
payload['error'] = 'Failed to generate image: ' + e
|
127 |
+
|
128 |
+
command_response(payload)
|
129 |
+
#endregion
|
130 |
+
|
131 |
+
#region SocketIO Events
|
132 |
+
try:
|
133 |
+
socketio_url = shared.cmd_opts.civitai_link_endpoint
|
134 |
+
except:
|
135 |
+
socketio_url = 'https://link.civitai.com'
|
136 |
+
|
137 |
+
sio = socketio.Client()
|
138 |
+
should_reconnect = False
|
139 |
+
|
140 |
+
@sio.event
|
141 |
+
def connect():
|
142 |
+
global should_reconnect
|
143 |
+
|
144 |
+
log('Connected to Civitai Link Server')
|
145 |
+
sio.emit('iam', {"type": "sd"})
|
146 |
+
if should_reconnect:
|
147 |
+
key = shared.opts.data.get("civitai_link_key", None)
|
148 |
+
if key is None: return
|
149 |
+
join_room(key)
|
150 |
+
should_reconnect = False
|
151 |
+
|
152 |
+
@sio.event
|
153 |
+
def connect_error(data):
|
154 |
+
log('Error connecting to Civitai Link Server')
|
155 |
+
|
156 |
+
@sio.event
|
157 |
+
def disconnect():
|
158 |
+
global should_reconnect
|
159 |
+
global current_key
|
160 |
+
current_key = None
|
161 |
+
|
162 |
+
log('Disconnected from Civitai Link Server')
|
163 |
+
should_reconnect = True
|
164 |
+
|
165 |
+
@sio.on('command')
|
166 |
+
def on_command(payload: Command):
|
167 |
+
command = payload['type']
|
168 |
+
log(f"Incoming Command: {payload['type']}")
|
169 |
+
civitai.add_activity(payload)
|
170 |
+
|
171 |
+
if command == 'activities:list': return on_activities_list(payload)
|
172 |
+
elif command == 'activities:clear': return on_activities_clear(payload)
|
173 |
+
elif command == 'activities:cancel': return on_activities_cancel(payload)
|
174 |
+
elif command == 'resources:list': return on_resources_list(payload)
|
175 |
+
elif command == 'resources:add': return on_resources_add(payload)
|
176 |
+
elif command == 'resources:remove': return on_resources_remove(payload)
|
177 |
+
elif command == 'image:txt2img': return on_image_txt2img(payload)
|
178 |
+
|
179 |
+
@sio.on('kicked')
|
180 |
+
def on_kicked():
|
181 |
+
log(f"Kicked from instance. Clearing key.")
|
182 |
+
shared.opts.data['civitai_link_key'] = None
|
183 |
+
|
184 |
+
@sio.on('roomPresence')
|
185 |
+
def on_room_presence(payload: RoomPresence):
|
186 |
+
log(f"Presence update: SD: {payload['sd']}, Clients: {payload['client']}")
|
187 |
+
connected = payload['sd'] > 0 and payload['client'] > 0
|
188 |
+
if civitai.connected != connected:
|
189 |
+
civitai.connected = connected
|
190 |
+
if connected: log("Connected to Civitai Instance")
|
191 |
+
else: log("Disconnected from Civitai Instance")
|
192 |
+
|
193 |
+
upgraded_key = None
|
194 |
+
@sio.on('upgradeKey')
|
195 |
+
def on_upgrade_key(payload: UpgradeKeyPayload):
|
196 |
+
global upgraded_key
|
197 |
+
|
198 |
+
log("Link Key upgraded")
|
199 |
+
upgraded_key = payload['key']
|
200 |
+
|
201 |
+
shared.opts.set('civitai_link_key', upgraded_key)
|
202 |
+
shared.opts.save(shared.config_filename)
|
203 |
+
|
204 |
+
@sio.on('error')
|
205 |
+
def on_error(payload: ErrorPayload):
|
206 |
+
log(f"Error: {payload['msg']}")
|
207 |
+
|
208 |
+
def command_response(payload, history=False):
|
209 |
+
payload['updatedAt'] = datetime.now(timezone.utc).isoformat()
|
210 |
+
if history: civitai.add_activity(payload)
|
211 |
+
sio.emit('commandStatus', payload)
|
212 |
+
#endregion
|
213 |
+
|
214 |
+
#region SocketIO Connection Management
|
215 |
+
def socketio_connect():
|
216 |
+
if (sio.connected): return
|
217 |
+
sio.connect(socketio_url, socketio_path='/api/socketio')
|
218 |
+
|
219 |
+
current_key = None
|
220 |
+
def join_room(key):
|
221 |
+
if (current_key == key): return
|
222 |
+
def on_join(payload):
|
223 |
+
log(f"Joined room {key}")
|
224 |
+
sio.emit('join', key, callback=on_join)
|
225 |
+
|
226 |
+
old_short_key = None
|
227 |
+
def on_civitai_link_key_changed():
|
228 |
+
global old_short_key
|
229 |
+
|
230 |
+
if not sio.connected: socketio_connect()
|
231 |
+
|
232 |
+
# If the key is upgraded, don't change it back to the short key
|
233 |
+
if old_short_key is not None and old_short_key == shared.opts.data.get("civitai_link_key", None):
|
234 |
+
shared.opts.data['civitai_link_key'] = upgraded_key
|
235 |
+
return
|
236 |
+
|
237 |
+
key = shared.opts.data.get("civitai_link_key", None)
|
238 |
+
if len(key) < 10: old_short_key = key
|
239 |
+
join_room(key)
|
240 |
+
#endregion
|
sd_civitai_extension/civitai/models.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from enum import Enum
|
2 |
+
from typing import List
|
3 |
+
from pydantic import BaseModel, Field
|
4 |
+
|
5 |
+
class ResourceTypes(str, Enum):
|
6 |
+
Checkpoint = "Checkpoint"
|
7 |
+
CheckpointConfig = "CheckpointConfig"
|
8 |
+
TextualInversion = "TextualInversion"
|
9 |
+
AestheticGradient = "AestheticGradient"
|
10 |
+
Hypernetwork = "Hypernetwork"
|
11 |
+
LORA = "LORA"
|
12 |
+
VAE = "VAE"
|
13 |
+
|
14 |
+
class CommandTypes(str, Enum):
|
15 |
+
ActivitiesList = "activities:list"
|
16 |
+
ActivitiesCancel = "activities:cancel"
|
17 |
+
ResourcesList = "resources:list"
|
18 |
+
ResourcesAdd = "resources:add"
|
19 |
+
ResourcesRemove = "resources:remove"
|
20 |
+
|
21 |
+
class ImageParams(BaseModel):
|
22 |
+
prompt: str = Field(default="", title="Prompt", description="The prompt to use when generating the image.")
|
23 |
+
negativePrompt: str = Field(default="", title="Negative Prompt", description="The negative prompt to use when generating the image.")
|
24 |
+
sampler: str = Field(default="Euler a", title="Sampler", description="The sampler to use when generating the image.")
|
25 |
+
seed: int = Field(default=-1, title="Seed", description="The seed to use when generating the image.")
|
26 |
+
steps: int = Field(default=30, title="Steps", description="The number of steps to use when generating the image.")
|
27 |
+
width: int = Field(default=512, title="Width", description="The width of the image to generate.")
|
28 |
+
height: int = Field(default=512, title="Height", description="The height of the image to generate.")
|
29 |
+
cfgScale: float = Field(default=7.5, title="Scale", description="The guidance scale for image generation.")
|
30 |
+
|
31 |
+
|
32 |
+
class GenerateImageRequest(BaseModel):
|
33 |
+
quantity: int = Field(default=1, title="Quantity", description="The number of images to generate.")
|
34 |
+
batchSize: int = Field(default=1, title="Batch Size", description="The number of images to generate in each batch.")
|
35 |
+
model: str = Field(default=None, title="Model", description="The hash of the model to use when generating the images.")
|
36 |
+
vae: str = Field(default=None, title="VAE", description="The hash of the VAE to use when generating the images.")
|
37 |
+
params: ImageParams = Field(default=ImageParams(), title="Parameters", description="The parameters to use when generating the images.")
|
38 |
+
|
39 |
+
class ResourceRequest(BaseModel):
|
40 |
+
name: str = Field(default=None, title="Name", description="The name of the resource to download.")
|
41 |
+
type: ResourceTypes = Field(default=None, title="Type", description="The type of the resource to download.")
|
42 |
+
hash: str = Field(default=None, title="Hash", description="The SHA256 hash of the resource to download.")
|
43 |
+
url: str = Field(default=None, title="URL", description="The URL of the resource to download.", required=False)
|
44 |
+
previewImage: str = Field(default=None, title="Preview Image", description="The URL of the preview image.", required=False)
|
45 |
+
|
46 |
+
class RoomPresence(BaseModel):
|
47 |
+
client: int = Field(default=None, title="Clients", description="The number of clients in the room")
|
48 |
+
sd: int = Field(default=None, title="Stable Diffusion Clients", description="The number of Stable Diffusion Clients in the room")
|
49 |
+
|
50 |
+
class Command(BaseModel):
|
51 |
+
id: str = Field(default=None, title="ID", description="The ID of the command.")
|
52 |
+
type: CommandTypes = Field(default=None, title="Type", description="The type of command to execute.")
|
53 |
+
|
54 |
+
class CommandActivitiesList(Command):
|
55 |
+
type: CommandTypes = Field(default=CommandTypes.ActivitiesList, title="Type", description="The type of command to execute.")
|
56 |
+
|
57 |
+
class CommandResourcesList(Command):
|
58 |
+
type: CommandTypes = Field(default=CommandTypes.ResourcesList, title="Type", description="The type of command to execute.")
|
59 |
+
types: List[ResourceTypes] = Field(default=[], title="Types", description="The types of resources to list.")
|
60 |
+
|
61 |
+
class CommandResourcesAdd(Command):
|
62 |
+
type: CommandTypes = Field(default=CommandTypes.ResourcesAdd, title="Type", description="The type of command to execute.")
|
63 |
+
resource: ResourceRequest = Field(default=[], title="Resource", description="The resources to add.")
|
64 |
+
|
65 |
+
class ResourceCancelRequest(BaseModel):
|
66 |
+
type: ResourceTypes = Field(default=None, title="Type", description="The type of the resource to remove.")
|
67 |
+
hash: str = Field(default=None, title="Hash", description="The SHA256 hash of the resource to remove.")
|
68 |
+
|
69 |
+
class CommandActivitiesCancel(Command):
|
70 |
+
type: CommandTypes = Field(default=CommandTypes.ActivitiesCancel, title="Type", description="The type of command to execute.")
|
71 |
+
|
72 |
+
class ResourceRemoveRequest(BaseModel):
|
73 |
+
type: ResourceTypes = Field(default=None, title="Type", description="The type of the resource to remove.")
|
74 |
+
hash: str = Field(default=None, title="Hash", description="The SHA256 hash of the resource to remove.")
|
75 |
+
|
76 |
+
class CommandResourcesRemove(Command):
|
77 |
+
type: CommandTypes = Field(default=CommandTypes.ResourcesRemove, title="Type", description="The type of command to execute.")
|
78 |
+
resource: ResourceRemoveRequest = Field(default=[], title="Resource", description="The resources to remove.")
|
79 |
+
|
80 |
+
class CommandImageTxt2Img(Command):
|
81 |
+
quantity: int = Field(default=1, title="Quantity", description="The number of images to generate.")
|
82 |
+
batchSize: int = Field(default=1, title="Batch Size", description="The number of images to generate in each batch.")
|
83 |
+
model: str = Field(default=None, title="Model", description="The hash of the model to use when generating the images.")
|
84 |
+
vae: str = Field(default=None, title="VAE", description="The hash of the VAE to use when generating the images.")
|
85 |
+
params: ImageParams = Field(default=ImageParams(), title="Parameters", description="The parameters to use when generating the images.")
|
86 |
+
|
87 |
+
class UpgradeKeyPayload(BaseModel):
|
88 |
+
key: str = Field(default=None, title="Key", description="The upgraded key.")
|
89 |
+
|
90 |
+
class ErrorPayload(BaseModel):
|
91 |
+
msg: str = Field(default=None, title="Message", description="The error message.")
|
92 |
+
|
93 |
+
class JoinedPayload(BaseModel):
|
94 |
+
type: str = Field(default=None, title="Type", description="The type of the client that joined.")
|
sd_civitai_extension/install.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import subprocess
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
|
5 |
+
import git
|
6 |
+
|
7 |
+
from launch import run
|
8 |
+
|
9 |
+
req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt")
|
10 |
+
|
11 |
+
def is_package_installed(package_name, version):
|
12 |
+
# strip [] from package name
|
13 |
+
package_name = package_name.split("[")[0]
|
14 |
+
try:
|
15 |
+
result = subprocess.run(['pip', 'show', package_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
16 |
+
except FileNotFoundError:
|
17 |
+
return False
|
18 |
+
if result.returncode == 0:
|
19 |
+
for line in result.stdout.decode('utf-8').splitlines():
|
20 |
+
if line.startswith('Version: '):
|
21 |
+
installed_version = line.split(' ')[-1]
|
22 |
+
if installed_version == version:
|
23 |
+
return True
|
24 |
+
return False
|
25 |
+
|
26 |
+
def check_versions():
|
27 |
+
global req_file
|
28 |
+
reqs = open(req_file, 'r')
|
29 |
+
lines = reqs.readlines()
|
30 |
+
reqs_dict = {}
|
31 |
+
for line in lines:
|
32 |
+
splits = line.split("==")
|
33 |
+
if len(splits) == 2:
|
34 |
+
key = splits[0]
|
35 |
+
reqs_dict[key] = splits[1].replace("\n", "").strip()
|
36 |
+
# Loop through reqs and check if installed
|
37 |
+
for req in reqs_dict:
|
38 |
+
available = is_package_installed(req, reqs_dict[req])
|
39 |
+
if available: print(f"[+] {req} version {reqs_dict[req]} installed.")
|
40 |
+
else : print(f"[!] {req} version {reqs_dict[req]} NOT installed.")
|
41 |
+
|
42 |
+
base_dir = os.path.dirname(os.path.realpath(__file__))
|
43 |
+
revision = ""
|
44 |
+
app_revision = ""
|
45 |
+
|
46 |
+
try:
|
47 |
+
repo = git.Repo(base_dir)
|
48 |
+
revision = repo.rev_parse("HEAD")
|
49 |
+
app_repo = git.Repo(os.path.join(base_dir, "..", ".."))
|
50 |
+
app_revision = app_repo.rev_parse("HEAD")
|
51 |
+
except:
|
52 |
+
pass
|
53 |
+
|
54 |
+
print("")
|
55 |
+
print("#######################################################################################################")
|
56 |
+
print("Initializing Civitai Link")
|
57 |
+
print("If submitting an issue on github, please provide the below text for debugging purposes:")
|
58 |
+
print("")
|
59 |
+
print(f"Python revision: {sys.version}")
|
60 |
+
print(f"Civitai Link revision: {revision}")
|
61 |
+
print(f"SD-WebUI revision: {app_revision}")
|
62 |
+
print("")
|
63 |
+
civitai_skip_install = os.environ.get('CIVITAI_SKIP_INSTALL', False)
|
64 |
+
|
65 |
+
try:
|
66 |
+
requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt")
|
67 |
+
if requirements_file == req_file:
|
68 |
+
civitai_skip_install = True
|
69 |
+
except:
|
70 |
+
pass
|
71 |
+
|
72 |
+
if not civitai_skip_install:
|
73 |
+
name = "Civitai Link"
|
74 |
+
run(f'"{sys.executable}" -m pip install -r "{req_file}"', f"Checking {name} requirements...",
|
75 |
+
f"Couldn't install {name} requirements.")
|
76 |
+
|
77 |
+
check_versions()
|
78 |
+
print("")
|
79 |
+
print("#######################################################################################################")
|
sd_civitai_extension/javascript/across-tabs.min.js
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*!
|
2 |
+
*
|
3 |
+
* across-tabs "1.2.4"
|
4 |
+
* https://github.com/wingify/across-tabs
|
5 |
+
* MIT licensed
|
6 |
+
*
|
7 |
+
* Copyright (C) 2017-2019 Wingify Pvt. Ltd. - Authored by Varun Malhotra(https://github.com/softvar)
|
8 |
+
*
|
9 |
+
*/
|
10 |
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("AcrossTabs",[],t):"object"==typeof exports?exports.AcrossTabs=t():e.AcrossTabs=t()}(this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var a=n[i]={i:i,l:!1,exports:{}};return e[i].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,i){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:i})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=6)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i={LOADED:"__TAB__LOADED_EVENT__",CUSTOM:"__TAB__CUSTOM_EVENT__",HANDSHAKE:"__TAB__HANDSHAKE_EVENT__",ON_BEFORE_UNLOAD:"__TAB__ON_BEFORE_UNLOAD__",PARENT_DISCONNECTED:"__PARENT_DISCONNECTED__",HANDSHAKE_WITH_PARENT:"__HANDSHAKE_WITH_PARENT__",PARENT_COMMUNICATED:"__PARENT_COMMUNICATED__"};t.default=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i={INVALID_JSON:"Invalid JSON Object!",INVALID_DATA:"Some wrong message is being sent by Parent.",CONFIG_REQUIRED:"Configuration options required. Please read docs.",CUSTOM_EVENT:"CustomEvent(and it's polyfill) is not supported in this browser.",URL_REQUIRED:"Url is needed for creating and opening a new window/tab. Please read docs."};t.default=i},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(0),o=i(a),r=n(3),s=i(r),u=n(4),d=i(u),l=n(1),f=i(l),c={tabs:[],config:{}};c._remove=function(e){var t=void 0;t=s.default.searchByKeyName(c.tabs,"id",e.id,"index"),c.tabs.splice(t,1)},c._preProcessMessage=function(e){try{e=c.config.stringify(e)}catch(e){throw new Error(f.default.INVALID_JSON)}return e&&-1===e.indexOf(o.default.PARENT_COMMUNICATED)&&(e=o.default.PARENT_COMMUNICATED+e),e},c.addNew=function(e){c.tabs.push(e)},c.getOpened=function(){return c.tabs.filter(function(e){return e.status===d.default.OPEN})},c.getClosed=function(){return c.tabs.filter(function(e){return e.status===d.default.CLOSE})},c.getAll=function(){return c.tabs},c.closeTab=function(e){var t=s.default.searchByKeyName(c.tabs,"id",e);return t&&t.ref&&(t.ref.close(),t.status=d.default.CLOSE),c},c.closeAll=function(){var e=void 0;for(e=0;e<c.tabs.length;e++)c.tabs[e]&&c.tabs[e].ref&&(c.tabs[e].ref.close(),c.tabs[e].status=d.default.CLOSE);return c},c.broadCastAll=function(e,t){var n=void 0,i=c.getOpened();for(e=c._preProcessMessage(e),n=0;n<i.length;n++)c.sendMessage(i[n],e,t);return c},c.broadCastTo=function(e,t,n){var i=void 0,a=c.getAll();return t=c._preProcessMessage(t),i=s.default.searchByKeyName(a,"id",e),c.sendMessage(i,t,n),c},c.sendMessage=function(e,t,n){var i=c.config.origin||"*";if(n&&e.ref[0])for(var a=0;a<e.ref.length;a++)e.ref[a].postMessage(t,i);else e.ref&&e.ref.top&&e.ref.top.postMessage(t,i)},t.default=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i={},a={INDEX:"index",OBJECT:"object",BOTH:"both"};i.searchByKeyName=function(e,t,n,i){if(!e||!t)return!1;i=i||a[1];var o=void 0,r=void 0,s=void 0,u=-1;for(o=0;o<e.length;o++){if(r=e[o],!isNaN(n)&&parseInt(r[t],10)===parseInt(n,10)){u=o;break}if(isNaN(n)&&r[t]===n){u=o;break}}switch(-1===u&&(e[u]={}),i){case a.INDEX:s=u;break;case a.BOTH:s={obj:e[u],index:u};break;case a.OBJECT:default:s=e[u]}return s},t.default=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i={OPEN:"open",CLOSE:"close"};t.default=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i={disable:function(e){if(!e)return!1;var t=void 0,n=document.querySelectorAll("["+e+"]");for(t=0;t<n.length;t++)n[t].setAttribute("disabled","disabled")},enable:function(e){if(!e)return!1;var t=void 0,n=document.querySelectorAll("["+e+"]");for(t=0;t<n.length;t++)n[t].removeAttribute("disabled")}};t.default=i},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),o=i(a),r=n(12),s=i(r),u={Parent:o.default,Child:s.default};t.default=u},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),s=n(8),u=i(s),d=n(2),l=i(d),f=n(5),c=i(f),h=n(4),v=i(h),_=n(1),g=i(_),w=n(0),p=i(w),b=n(10),y=i(b),E=void 0,m=void 0,O=function(){function e(t){a(this,e),t=t||{},void 0===t.heartBeatInterval&&(t.heartBeatInterval=500),void 0===t.shouldInitImmediately&&(t.shouldInitImmediately=!0),"function"!=typeof t.parse&&(t.parse=JSON.parse),"function"!=typeof t.stringify&&(t.stringify=JSON.stringify),l.default.tabs=[],this.Tab=u.default,o(this,t),l.default.config=t,this.shouldInitImmediately&&this.init()}return r(e,[{key:"addInterval",value:function(){var e=void 0,t=l.default.getAll(),n=l.default.getOpened();if(!n||!n.length)return window.clearInterval(E),E=null,!1;for(e=0;e<t.length;e++)this.removeClosedTabs&&this.watchStatus(t[e]),t[e]&&t[e].ref&&(t[e].status=t[e].ref.closed?v.default.CLOSE:v.default.OPEN);this.onPollingCallback&&this.onPollingCallback()}},{key:"startPollingTabs",value:function(){var e=this;E=window.setInterval(function(){return e.addInterval()},this.heartBeatInterval)}},{key:"watchStatus",value:function(e){if(!e||!e.ref)return!1;var t=e.ref.closed?v.default.CLOSE:v.default.OPEN,n=e.status;if(!t||t===n)return!1;n===v.default.OPEN&&t===v.default.CLOSE&&l.default._remove(e)}},{key:"onChildUnload",value:function(e){this.onChildDisconnect&&this.onChildDisconnect(e.detail)}},{key:"customEventUnListener",value:function(e){this.enableElements(),e.detail&&e.detail.type===p.default.HANDSHAKE&&this.onHandshakeCallback?this.onHandshakeCallback(e.detail.tabInfo):e.detail&&e.detail.type===p.default.CUSTOM&&this.onChildCommunication&&this.onChildCommunication(e.detail.tabInfo)}},{key:"addEventListeners",value:function(){var e=this;window.removeEventListener("message",y.default.onNewTab),window.addEventListener("message",y.default.onNewTab),window.removeEventListener("onCustomChildMessage",this.customEventUnListener),window.addEventListener("onCustomChildMessage",function(t){return e.customEventUnListener(t)}),window.removeEventListener("onChildUnload",this.onChildUnload),window.addEventListener("onChildUnload",function(t){return e.onChildUnload(t)}),window.onbeforeunload=function(){l.default.broadCastAll(p.default.PARENT_DISCONNECTED)}}},{key:"enableElements",value:function(){c.default.enable("data-tab-opener")}},{key:"getAllTabs",value:function(){return l.default.getAll()}},{key:"getOpenedTabs",value:function(){return l.default.getOpened()}},{key:"getClosedTabs",value:function(){return l.default.getClosed()}},{key:"closeAllTabs",value:function(){return l.default.closeAll()}},{key:"closeTab",value:function(e){return l.default.closeTab(e)}},{key:"broadCastAll",value:function(e){return l.default.broadCastAll(e)}},{key:"broadCastTo",value:function(e,t){return l.default.broadCastTo(e,t)}},{key:"openNewTab",value:function(e){if(!e)throw new Error(g.default.CONFIG_REQUIRED);if(!e.url)throw new Error(g.default.URL_REQUIRED);return m=new this.Tab,m.create(e),E||this.startPollingTabs(),m}},{key:"init",value:function(){this.addEventListeners()}}]),e}();t.default=O},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),s=n(2),u=i(s),d=n(9),l=i(d),f=n(5),c=i(f),h=function(){function e(){a(this,e),window.name=window.name||"PARENT_TAB"}return r(e,[{key:"create",value:function(e){return e=e||{},o(this,e),this.id=l.default.generate()||u.default.tabs.length+1,this.status="open",this.ref=window.open(this.url,e.windowName||"_blank",e.windowFeatures),c.default.disable("data-tab-opener"),window.newlyTabOpened={id:this.id,name:this.name||this.windowName,ref:this.ref},u.default.addNew(this),this}}]),e}();t.default=h},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});/**
|
11 |
+
* UUID.js: The RFC-compliant UUID generator for JavaScript.
|
12 |
+
* ES6 port of only `generate` method of UUID by Varun Malhotra under MIT License
|
13 |
+
*
|
14 |
+
* @author LiosK
|
15 |
+
* @version v3.3.0
|
16 |
+
* @license The MIT License: Copyright (c) 2010-2016 LiosK.
|
17 |
+
*/
|
18 |
+
var i=void 0;i=function(){function e(){}return e.generate=function(){var t=e._getRandomInt,n=e._hexAligner;return n(t(32),8)+"-"+n(t(16),4)+"-"+n(16384|t(12),4)+"-"+n(32768|t(14),4)+"-"+n(t(48),12)},e._getRandomInt=function(e){return e<0?NaN:e<=30?0|Math.random()*(1<<e):e<=53?(0|Math.random()*(1<<30))+(0|Math.random()*(1<<e-30))*(1<<30):NaN},e._getIntAligner=function(e){return function(t,n){for(var i=t.toString(e),a=n-i.length,o="0";a>0;a>>>=1,o+=o)1&a&&(i=o+i);return i}},e._hexAligner=e._getIntAligner(16),e.prototype.toString=function(){return this.hexString},e}(),t.default=i},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(3),o=i(a),r=n(2),s=i(r),u=n(1),d=i(u),l=n(0),f=i(l);n(11);var c={};c._onLoad=function(e){var t=void 0,n=void 0,i=e.split(f.default.LOADED)[1];if(i)try{i=s.default.config.parse(i),i.id&&(t=s.default.getAll(),t.length&&(window.newlyTabOpened=t[t.length-1],window.newlyTabOpened.id=i.id,window.newlyTabOpened.name=i.name||i.windowName))}catch(e){throw new Error(d.default.INVALID_JSON)}if(window.newlyTabOpened)try{n=f.default.HANDSHAKE_WITH_PARENT,n+=s.default.config.stringify({id:window.newlyTabOpened.id,name:window.newlyTabOpened.name||window.newlyTabOpened.windowName,parentName:window.name}),s.default.sendMessage(window.newlyTabOpened,n,i.isSiteInsideFrame)}catch(e){throw new Error(d.default.INVALID_JSON)}},c._onCustomMessage=function(e,t){var n=void 0,i=void 0,a=e.split(t)[1];try{a=s.default.config.parse(a)}catch(e){throw new Error(d.default.INVALID_JSON)}i={tabInfo:a,type:t},n=new CustomEvent("onCustomChildMessage",{detail:i}),window.dispatchEvent(n)},c._onBeforeUnload=function(e){var t=void 0,n=e.split(f.default.ON_BEFORE_UNLOAD)[1];try{n=s.default.config.parse(n)}catch(e){throw new Error(d.default.INVALID_JSON)}s.default.tabs.length&&(t=s.default.getAll(),window.newlyTabOpened=o.default.searchByKeyName(t,"id",n.id)||window.newlyTabOpened);var i=new CustomEvent("onChildUnload",{detail:n});window.dispatchEvent(i)},c.onNewTab=function(e){var t=e.data;return!(!t||"string"!=typeof t||!s.default.tabs.length)&&((!s.default.config.origin||s.default.config.origin===e.origin)&&void(t.indexOf(f.default.LOADED)>-1?c._onLoad(t):t.indexOf(f.default.CUSTOM)>-1?c._onCustomMessage(t,f.default.CUSTOM):t.indexOf(f.default.HANDSHAKE)>-1?c._onCustomMessage(t,f.default.HANDSHAKE):t.indexOf(f.default.ON_BEFORE_UNLOAD)>-1&&c._onBeforeUnload(t)))},t.default=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){function e(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!1,!1,t.detail),n}"function"!=typeof window.CustomEvent&&(e.prototype=window.Event.prototype,window.CustomEvent=e)}()},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),s=n(0),u=i(s),d=n(1),l=i(d),f=function(){function e(t){a(this,e),this.sessionStorageKey="__vwo_new_tab_info__",t||(t={}),void 0===t.handshakeExpiryLimit&&(t.handshakeExpiryLimit=5e3),void 0===t.shouldInitImmediately&&(t.shouldInitImmediately=!0),"function"!=typeof t.parse&&(t.parse=JSON.parse),"function"!=typeof t.stringify&&(t.stringify=JSON.stringify),this.tabName=window.name,this.tabId=null,this.tabParentName=null,o(this,t),this.config=t,this.shouldInitImmediately&&this.init()}return r(e,[{key:"_isSessionStorage",value:function(){return!!("sessionStorage"in window&&window.sessionStorage)}},{key:"_getData",value:function(){return!!this.isSessionStorageSupported&&window.sessionStorage.getItem(this.sessionStorageKey)}},{key:"_setData",value:function(e){return!!this.isSessionStorageSupported&&(window.sessionStorage.setItem(this.sessionStorageKey,e),e)}},{key:"_restoreData",value:function(){if(!this.isSessionStorageSupported)return!1;if(this.isSessionStorageSupported){var e=this._getData();this._parseData(e)}}},{key:"_parseData",value:function(e){var t=void 0;try{t=this.config.parse(e),this.tabId=t&&t.id,this.tabName=t&&t.name,this.tabParentName=t&&t.parentName}catch(e){throw new Error(l.default.INVALID_DATA)}}},{key:"onCommunication",value:function(e){var t=this,n=void 0,i=e.data;if(i&&"string"==typeof i&&(!this.config.origin||this.config.origin===e.origin)){if(window.clearTimeout(this.timeout),i.indexOf(u.default.PARENT_DISCONNECTED)>-1&&(this.config.onParentDisconnect&&this.config.onParentDisconnect(),window.removeEventListener("message",function(e){return t.onCommunication(e)})),i.indexOf(u.default.HANDSHAKE_WITH_PARENT)>-1){var a=void 0;n=i.split(u.default.HANDSHAKE_WITH_PARENT)[1],this._setData(n),this._parseData(n),a={id:this.tabId,isSiteInsideFrame:this.config.isSiteInsideFrame},this.sendMessageToParent(a,u.default.HANDSHAKE),this.config.onInitialize&&this.config.onInitialize()}if(i.indexOf(u.default.PARENT_COMMUNICATED)>-1){n=i.split(u.default.PARENT_COMMUNICATED)[1];try{n=this.config.parse(n)}catch(e){throw new Error(l.default.INVALID_JSON)}this.config.onParentCommunication&&this.config.onParentCommunication(n)}}}},{key:"addListeners",value:function(){var e=this;window.onbeforeunload=function(t){var n={id:e.tabId,isSiteInsideFrame:e.config.isSiteInsideFrame};e.sendMessageToParent(n,u.default.ON_BEFORE_UNLOAD)},window.removeEventListener("message",function(t){return e.onCommunication(t)}),window.addEventListener("message",function(t){return e.onCommunication(t)})}},{key:"setHandshakeExpiry",value:function(){var e=this;return window.setTimeout(function(){e.config.onHandShakeExpiry&&e.config.onHandShakeExpiry()},this.handshakeExpiryLimit)}},{key:"sendMessageToParent",value:function(e,t){var n=void 0;e=(t||u.default.CUSTOM)+this.config.stringify(e),window.top.opener&&(n=this.config.origin||"*",window.top.opener.postMessage(e,n))}},{key:"getTabInfo",value:function(){return{id:this.tabId,name:this.tabName,parentName:this.tabParentName,isSiteInsideFrame:this.config.isSiteInsideFrame}}},{key:"init",value:function(){this.isSessionStorageSupported=this._isSessionStorage(),this.addListeners(),this._restoreData(),this.sendMessageToParent(this.getTabInfo(),u.default.LOADED),this.timeout=this.setHandshakeExpiry(),this.config.onReady&&this.config.onReady()}}]),e}();t.default=f}])});
|
sd_civitai_extension/javascript/civitai.js
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
(async function () {
|
2 |
+
// #region [utils]
|
3 |
+
const log = (...args) => console.log(`[civitai]`, ...args);
|
4 |
+
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
5 |
+
const getElement = (selector, timeout = 10000) => new Promise((resolve, reject) => {
|
6 |
+
const interval = setInterval(() => {
|
7 |
+
const el = gradioApp().querySelector(selector);
|
8 |
+
timeout -= 100;
|
9 |
+
if (timeout < 0) {
|
10 |
+
reject('timeout');
|
11 |
+
clearInterval(interval);
|
12 |
+
} else if (el) {
|
13 |
+
resolve(el);
|
14 |
+
clearInterval(interval);
|
15 |
+
}
|
16 |
+
}, 100);
|
17 |
+
})
|
18 |
+
// #endregion
|
19 |
+
|
20 |
+
|
21 |
+
async function generate() {
|
22 |
+
const generateButton = await getElement('#txt2img_generate');
|
23 |
+
generateButton.click();
|
24 |
+
log('generating image');
|
25 |
+
}
|
26 |
+
|
27 |
+
async function handlePrompt(prompt, andGenerate = false, delayMs = 3000) {
|
28 |
+
log('injecting prompt', prompt);
|
29 |
+
const promptEl = await getElement('#txt2img_prompt textarea');
|
30 |
+
promptEl.value = prompt;
|
31 |
+
promptEl.dispatchEvent(new Event("input", { bubbles: true })); // internal Svelte trigger
|
32 |
+
|
33 |
+
const pastePromptButton = await getElement('#paste');
|
34 |
+
pastePromptButton.click();
|
35 |
+
log('applying prompt');
|
36 |
+
|
37 |
+
if (andGenerate) {
|
38 |
+
await delay(delayMs);
|
39 |
+
await generate();
|
40 |
+
notifyParent({generate: true});
|
41 |
+
}
|
42 |
+
}
|
43 |
+
|
44 |
+
function notifyParent(msg) {
|
45 |
+
if (child && child.sendMessageToParent)
|
46 |
+
child.sendMessageToParent(msg);
|
47 |
+
}
|
48 |
+
|
49 |
+
async function refreshModels() {
|
50 |
+
const refreshModelsButton = await getElement('#refresh_sd_model_checkpoint');
|
51 |
+
refreshModelsButton.click();
|
52 |
+
}
|
53 |
+
|
54 |
+
let child;
|
55 |
+
async function hookChild() {
|
56 |
+
child = new AcrossTabs.default.Child({
|
57 |
+
// origin: 'https://civitai.com',
|
58 |
+
origin: 'http://localhost:3000',
|
59 |
+
onParentCommunication: commandHandler
|
60 |
+
});
|
61 |
+
}
|
62 |
+
|
63 |
+
function commandHandler({ command, ...data }) {
|
64 |
+
log('tab communication', { command, data })
|
65 |
+
switch (command) {
|
66 |
+
case 'generate': return handlePrompt(data.generationParams, true, 500);
|
67 |
+
case 'refresh-models': return refreshModels();
|
68 |
+
}
|
69 |
+
}
|
70 |
+
|
71 |
+
let statusElement = document.createElement('div');
|
72 |
+
let currentStatus = false;
|
73 |
+
async function checkStatus() {
|
74 |
+
const { connected } = await fetch('/civitai/v1/link-status').then(x=>x.json());
|
75 |
+
if (currentStatus != connected) {
|
76 |
+
currentStatus = connected;
|
77 |
+
statusElement.classList.toggle('connected', connected);
|
78 |
+
}
|
79 |
+
}
|
80 |
+
async function startStatusChecks() {
|
81 |
+
statusElement.id = 'civitai-status';
|
82 |
+
statusElement.classList.add('civitai-status');
|
83 |
+
await getElement('.gradio-container'); // wait for gradio to load
|
84 |
+
gradioApp().appendChild(statusElement);
|
85 |
+
|
86 |
+
setInterval(checkStatus, 1000 * 10);
|
87 |
+
checkStatus();
|
88 |
+
}
|
89 |
+
|
90 |
+
// Bootstrap
|
91 |
+
const searchParams = new URLSearchParams(location.search);
|
92 |
+
if (searchParams.has('civitai_prompt'))
|
93 |
+
handlePrompt(atob(searchParams.get('civitai_prompt')), searchParams.has('civitai_generate'));
|
94 |
+
if (searchParams.has('civitai_refresh_models'))
|
95 |
+
refreshModels()
|
96 |
+
if (searchParams.has('civitai_hook_child'))
|
97 |
+
hookChild();
|
98 |
+
|
99 |
+
// clear search params
|
100 |
+
history.replaceState({}, document.title, location.href);
|
101 |
+
await startStatusChecks();
|
102 |
+
})();
|
sd_civitai_extension/preload.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# loaded before parsing commandline args
|
2 |
+
import argparse
|
3 |
+
|
4 |
+
def preload(parser: argparse.ArgumentParser):
|
5 |
+
parser.add_argument("--civitai-endpoint", type=str, help="Endpoint for interacting with a Civitai instance", default="https://civitai.com/api/v1")
|
6 |
+
parser.add_argument("--civitai-link-endpoint", type=str, help="Endpoint for interacting with a Civitai Link server", default="https://link.civitai.com/api/socketio")
|
sd_civitai_extension/requirements.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
python-socketio[client]==5.7.2
|
sd_civitai_extension/scripts/api.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# api endpoints
|
2 |
+
import gradio as gr
|
3 |
+
from fastapi import FastAPI
|
4 |
+
|
5 |
+
from modules import script_callbacks as script_callbacks
|
6 |
+
|
7 |
+
import civitai.lib as civitai
|
8 |
+
from civitai.models import GenerateImageRequest, ResourceRequest
|
9 |
+
|
10 |
+
def civitaiAPI(_: gr.Blocks, app: FastAPI):
|
11 |
+
@app.get('/civitai/v1/link-status')
|
12 |
+
def link_status():
|
13 |
+
return { "connected": civitai.connected }
|
14 |
+
|
15 |
+
script_callbacks.on_app_started(civitaiAPI)
|
16 |
+
civitai.log("API loaded")
|
sd_civitai_extension/scripts/gen_hashing.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import re
|
3 |
+
import os
|
4 |
+
|
5 |
+
import civitai.lib as civitai
|
6 |
+
from modules import script_callbacks, sd_vae, shared
|
7 |
+
|
8 |
+
additional_network_type_map = {
|
9 |
+
'lora': 'LORA',
|
10 |
+
'hypernet': 'Hypernetwork'
|
11 |
+
}
|
12 |
+
additional_network_pattern = r'<(lora|hypernet):([a-zA-Z0-9_\.\-]+):([0-9.]+)(?:[:].*)?>'
|
13 |
+
model_hash_pattern = r'Model hash: ([0-9a-fA-F]{10})'
|
14 |
+
|
15 |
+
# Automatically pull model with corresponding hash from Civitai
|
16 |
+
def add_resource_hashes(params):
|
17 |
+
if 'parameters' not in params.pnginfo: return
|
18 |
+
|
19 |
+
hashify_resources = shared.opts.data.get('civitai_hashify_resources', True)
|
20 |
+
if not hashify_resources: return
|
21 |
+
|
22 |
+
lines = params.pnginfo['parameters'].split('\n')
|
23 |
+
generation_params = lines.pop()
|
24 |
+
prompt_parts = '\n'.join(lines).split('Negative prompt:')
|
25 |
+
prompt, negative_prompt = [s.strip() for s in prompt_parts[:2] + ['']*(2-len(prompt_parts))]
|
26 |
+
|
27 |
+
hashed_prompt = prompt
|
28 |
+
hashed_negative_prompt = negative_prompt
|
29 |
+
|
30 |
+
resources = civitai.load_resource_list([])
|
31 |
+
resource_hashes = {}
|
32 |
+
|
33 |
+
# Hash the VAE
|
34 |
+
if hashify_resources and sd_vae.loaded_vae_file is not None:
|
35 |
+
vae_name = os.path.splitext(sd_vae.get_filename(sd_vae.loaded_vae_file))[0]
|
36 |
+
vae_matches = [r for r in resources if r['type'] == 'VAE' and r['name'] == vae_name]
|
37 |
+
if len(vae_matches) > 0:
|
38 |
+
short_hash = vae_matches[0]['hash'][:10]
|
39 |
+
resource_hashes['vae'] = short_hash
|
40 |
+
|
41 |
+
|
42 |
+
# Check for embeddings in prompt
|
43 |
+
embeddings = [r for r in resources if r['type'] == 'TextualInversion']
|
44 |
+
for embedding in embeddings:
|
45 |
+
embedding_name = embedding['name']
|
46 |
+
embedding_pattern = re.compile(r'(?<![^\s:(|\[\]])' + re.escape(embedding_name) + r'(?![^\s:)|\[\]\,])', re.MULTILINE | re.IGNORECASE)
|
47 |
+
|
48 |
+
match_prompt = embedding_pattern.search(prompt)
|
49 |
+
match_negative = embedding_pattern.search(negative_prompt)
|
50 |
+
if not match_prompt and not match_negative: continue
|
51 |
+
|
52 |
+
short_hash = embedding['hash'][:10]
|
53 |
+
resource_hashes[f'embed:{embedding_name}'] = short_hash
|
54 |
+
|
55 |
+
# Check for additional networks in prompt
|
56 |
+
network_matches = re.findall(additional_network_pattern, prompt)
|
57 |
+
for match in network_matches:
|
58 |
+
network_type, network_name, network_weight = match
|
59 |
+
resource_type = additional_network_type_map[network_type]
|
60 |
+
matching_resource = [r for r in resources if r['type'] == resource_type and (r['name'].lower() == network_name.lower() or r['name'].lower().split('-')[0] == network_name.lower())]
|
61 |
+
if len(matching_resource) > 0:
|
62 |
+
short_hash = matching_resource[0]['hash'][:10]
|
63 |
+
resource_hashes[f'{network_type}:{network_name}'] = short_hash
|
64 |
+
|
65 |
+
# Check for model hash in generation parameters
|
66 |
+
model_match = re.search(model_hash_pattern, generation_params)
|
67 |
+
if hashify_resources and model_match:
|
68 |
+
model_hash = model_match.group(1)
|
69 |
+
matching_resource = [r for r in resources if r['type'] == 'Checkpoint' and r['hash'].startswith(model_hash)]
|
70 |
+
if len(matching_resource) > 0:
|
71 |
+
short_hash = matching_resource[0]['hash'][:10]
|
72 |
+
resource_hashes['model'] = short_hash
|
73 |
+
|
74 |
+
if len(resource_hashes) > 0:
|
75 |
+
params.pnginfo['parameters'] += f", Hashes: {json.dumps(resource_hashes)}"
|
76 |
+
|
77 |
+
script_callbacks.on_before_image_saved(add_resource_hashes)
|
sd_civitai_extension/scripts/info.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
import gradio as gr
|
3 |
+
import threading
|
4 |
+
import json
|
5 |
+
from pathlib import Path
|
6 |
+
|
7 |
+
import civitai.lib as civitai
|
8 |
+
|
9 |
+
from modules import script_callbacks, shared
|
10 |
+
|
11 |
+
actionable_types = ['LORA', 'LoCon', 'Hypernetwork', 'TextualInversion', 'Checkpoint']
|
12 |
+
|
13 |
+
|
14 |
+
def load_info():
|
15 |
+
download_missing_previews = shared.opts.data.get('civitai_download_triggers', True)
|
16 |
+
if not download_missing_previews:
|
17 |
+
return
|
18 |
+
|
19 |
+
civitai.log("Check resources for missing info files")
|
20 |
+
resources = civitai.load_resource_list()
|
21 |
+
resources = [r for r in resources if r['type'] in actionable_types]
|
22 |
+
|
23 |
+
# get all resources that have no info files
|
24 |
+
missing_info = [r for r in resources if r['hasInfo'] is False]
|
25 |
+
civitai.log(f"Found {len(missing_info)} resources missing info files")
|
26 |
+
hashes = [r['hash'] for r in missing_info]
|
27 |
+
|
28 |
+
# split hashes into batches of 100 and fetch into results
|
29 |
+
results = []
|
30 |
+
try:
|
31 |
+
for i in range(0, len(hashes), 100):
|
32 |
+
batch = hashes[i:i + 100]
|
33 |
+
results.extend(civitai.get_all_by_hash(batch))
|
34 |
+
except:
|
35 |
+
civitai.log("Failed to fetch info from Civitai")
|
36 |
+
return
|
37 |
+
|
38 |
+
if len(results) == 0:
|
39 |
+
civitai.log("No info found on Civitai")
|
40 |
+
return
|
41 |
+
|
42 |
+
civitai.log(f"Found {len(results)} hash matches")
|
43 |
+
|
44 |
+
# update the resources with the new info
|
45 |
+
updated = 0
|
46 |
+
for r in results:
|
47 |
+
if (r is None):
|
48 |
+
continue
|
49 |
+
|
50 |
+
for file in r['files']:
|
51 |
+
if not 'hashes' in file or not 'SHA256' in file['hashes']:
|
52 |
+
continue
|
53 |
+
file_hash = file['hashes']['SHA256']
|
54 |
+
if file_hash.lower() not in hashes:
|
55 |
+
continue
|
56 |
+
|
57 |
+
if "SD 1" in r['baseModel']:
|
58 |
+
sd_version = "SD1"
|
59 |
+
elif "SD 2" in r['baseModel']:
|
60 |
+
sd_version = "SD2"
|
61 |
+
elif "SDXL" in r['baseModel']:
|
62 |
+
sd_version = "SDXL"
|
63 |
+
else:
|
64 |
+
sd_version = "unknown"
|
65 |
+
data = {
|
66 |
+
"description": r['description'],
|
67 |
+
"sd version": sd_version,
|
68 |
+
"activation text": ", ".join(r['trainedWords']),
|
69 |
+
"preferred weight": 0.8,
|
70 |
+
"notes": "",
|
71 |
+
}
|
72 |
+
|
73 |
+
matches = [resource for resource in missing_info if file_hash.lower() == resource['hash']]
|
74 |
+
if len(matches) == 0:
|
75 |
+
continue
|
76 |
+
|
77 |
+
for resource in matches:
|
78 |
+
Path(resource['path']).with_suffix(".json").write_text(json.dumps(data, indent=4))
|
79 |
+
updated += 1
|
80 |
+
|
81 |
+
civitai.log(f"Updated {updated} info files")
|
82 |
+
|
83 |
+
|
84 |
+
# Automatically pull model with corresponding hash from Civitai
|
85 |
+
def start_load_info(demo: gr.Blocks, app):
|
86 |
+
thread = threading.Thread(target=load_info)
|
87 |
+
thread.start()
|
88 |
+
|
89 |
+
|
90 |
+
script_callbacks.on_app_started(start_load_info)
|
sd_civitai_extension/scripts/link.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
import civitai.link as link
|
4 |
+
|
5 |
+
from modules import shared, script_callbacks
|
6 |
+
|
7 |
+
def connect_to_civitai(demo: gr.Blocks, app):
|
8 |
+
key = shared.opts.data.get("civitai_link_key", None)
|
9 |
+
# If key is empty or not set, don't connect to Civitai Link
|
10 |
+
if not key: return
|
11 |
+
|
12 |
+
link.log('Connecting to Civitai Link Server')
|
13 |
+
link.socketio_connect()
|
14 |
+
link.join_room(key)
|
15 |
+
|
16 |
+
script_callbacks.on_app_started(connect_to_civitai)
|
17 |
+
|
sd_civitai_extension/scripts/pasted.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import civitai.lib as civitai
|
2 |
+
|
3 |
+
from modules import shared, script_callbacks
|
4 |
+
|
5 |
+
# Automatically pull model with corresponding hash from Civitai
|
6 |
+
def on_infotext_pasted(infotext, params):
|
7 |
+
download_missing_models = shared.opts.data.get('civitai_download_missing_models', True)
|
8 |
+
if (not download_missing_models or "Model hash" not in params or shared.opts.disable_weights_auto_swap):
|
9 |
+
return
|
10 |
+
|
11 |
+
model_hash = params["Model hash"]
|
12 |
+
model = civitai.get_model_by_hash(model_hash)
|
13 |
+
if (model is None):
|
14 |
+
civitai.fetch_model_by_hash(model_hash)
|
15 |
+
|
16 |
+
script_callbacks.on_infotext_pasted(on_infotext_pasted)
|
sd_civitai_extension/scripts/previews.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
import gradio as gr
|
3 |
+
import threading
|
4 |
+
|
5 |
+
import civitai.lib as civitai
|
6 |
+
|
7 |
+
from modules import script_callbacks, shared
|
8 |
+
|
9 |
+
previewable_types = ['LORA', 'LoCon', 'Hypernetwork', 'TextualInversion', 'Checkpoint']
|
10 |
+
def load_previews():
|
11 |
+
download_missing_previews = shared.opts.data.get('civitai_download_previews', True)
|
12 |
+
if not download_missing_previews: return
|
13 |
+
nsfw_previews = shared.opts.data.get('civitai_nsfw_previews', True)
|
14 |
+
|
15 |
+
civitai.log(f"Check resources for missing preview images")
|
16 |
+
resources = civitai.load_resource_list()
|
17 |
+
resources = [r for r in resources if r['type'] in previewable_types]
|
18 |
+
|
19 |
+
# get all resources that are missing previews
|
20 |
+
missing_previews = [r for r in resources if r['hasPreview'] is False]
|
21 |
+
civitai.log(f"Found {len(missing_previews)} resources missing preview images")
|
22 |
+
hashes = [r['hash'] for r in missing_previews]
|
23 |
+
|
24 |
+
# split hashes into batches of 100 and fetch into results
|
25 |
+
results = []
|
26 |
+
try:
|
27 |
+
for i in range(0, len(hashes), 100):
|
28 |
+
batch = hashes[i:i + 100]
|
29 |
+
results.extend(civitai.get_all_by_hash(batch))
|
30 |
+
except:
|
31 |
+
civitai.log("Failed to fetch preview images from Civitai")
|
32 |
+
return
|
33 |
+
|
34 |
+
if len(results) == 0:
|
35 |
+
civitai.log("No preview images found on Civitai")
|
36 |
+
return
|
37 |
+
|
38 |
+
civitai.log(f"Found {len(results)} hash matches")
|
39 |
+
|
40 |
+
# update the resources with the new preview
|
41 |
+
updated = 0
|
42 |
+
for r in results:
|
43 |
+
if (r is None): continue
|
44 |
+
|
45 |
+
for file in r['files']:
|
46 |
+
if not 'hashes' in file or not 'SHA256' in file['hashes']: continue
|
47 |
+
hash = file['hashes']['SHA256']
|
48 |
+
if hash.lower() not in hashes: continue
|
49 |
+
images = r['images']
|
50 |
+
if (nsfw_previews is False): images = [i for i in images if i['nsfw'] is False]
|
51 |
+
if (len(images) == 0): continue
|
52 |
+
image_url = images[0]['url']
|
53 |
+
civitai.update_resource_preview(hash, image_url)
|
54 |
+
updated += 1
|
55 |
+
|
56 |
+
civitai.log(f"Updated {updated} preview images")
|
57 |
+
|
58 |
+
# Automatically pull model with corresponding hash from Civitai
|
59 |
+
def start_load_previews(demo: gr.Blocks, app):
|
60 |
+
thread = threading.Thread(target=load_previews)
|
61 |
+
thread.start()
|
62 |
+
|
63 |
+
script_callbacks.on_app_started(start_load_previews)
|
sd_civitai_extension/scripts/settings.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from civitai.link import on_civitai_link_key_changed
|
2 |
+
from modules import shared, script_callbacks
|
3 |
+
|
4 |
+
def on_ui_settings():
|
5 |
+
section = ('civitai_link', "Civitai")
|
6 |
+
shared.opts.add_option("civitai_link_key", shared.OptionInfo("", "Your Civitai Link Key", section=section, onchange=on_civitai_link_key_changed))
|
7 |
+
shared.opts.add_option("civitai_link_logging", shared.OptionInfo(True, "Show Civitai Link events in the console", section=section))
|
8 |
+
shared.opts.add_option("civitai_api_key", shared.OptionInfo("", "Your Civitai API Key", section=section))
|
9 |
+
shared.opts.add_option("civitai_download_previews", shared.OptionInfo(True, "Download missing preview images on startup", section=section))
|
10 |
+
shared.opts.add_option("civitai_download_triggers", shared.OptionInfo(True, "Download missing activation triggers on startup", section=section))
|
11 |
+
shared.opts.add_option("civitai_nsfw_previews", shared.OptionInfo(False, "Download NSFW (adult) preview images", section=section))
|
12 |
+
shared.opts.add_option("civitai_download_missing_models", shared.OptionInfo(True, "Download missing models upon reading generation parameters from prompt", section=section))
|
13 |
+
shared.opts.add_option("civitai_hashify_resources", shared.OptionInfo(True, "Include resource hashes in image metadata (for resource auto-detection on Civitai)", section=section))
|
14 |
+
shared.opts.add_option("civitai_folder_model", shared.OptionInfo("", "Models directory (if not default)", section=section))
|
15 |
+
shared.opts.add_option("civitai_folder_lora", shared.OptionInfo("", "LoRA directory (if not default)", section=section))
|
16 |
+
shared.opts.add_option("civitai_folder_lyco", shared.OptionInfo("", "LyCORIS directory (if not default)", section=section))
|
17 |
+
|
18 |
+
|
19 |
+
script_callbacks.on_ui_settings(on_ui_settings)
|
sd_civitai_extension/style.css
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
div.civitai-status{
|
2 |
+
position: absolute;
|
3 |
+
top: 7px;
|
4 |
+
right: 5px;
|
5 |
+
width:24px;
|
6 |
+
height:24px;
|
7 |
+
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 178 178' style='enable-background:new 0 0 178 178' xml:space='preserve'%3E%3ClinearGradient id='a' gradientUnits='userSpaceOnUse' x1='89.3' y1='1.5' x2='89.3' y2='177.014'%3E%3Cstop offset='0' style='stop-color:%23081692'/%3E%3Cstop offset='1' style='stop-color:%231e043c'/%3E%3C/linearGradient%3E%3ClinearGradient id='b' gradientUnits='userSpaceOnUse' x1='89.3' y1='1.5' x2='89.3' y2='177.014'%3E%3Cstop offset='0' style='stop-color:%231284f7'/%3E%3Cstop offset='1' style='stop-color:%230a20c9'/%3E%3C/linearGradient%3E%3Cpath style='fill:url(%23a)' d='M13.3 45.4v87.7l76 43.9 76-43.9V45.4l-76-43.9z'/%3E%3Cpath style='fill:url(%23b)' d='m89.3 29.2 52 30v60l-52 30-52-30v-60l52-30m0-27.7-76 43.9v87.8l76 43.9 76-43.9V45.4l-76-43.9z'/%3E%3Cpath style='fill:%23fff' d='m104.1 97.2-14.9 8.5-14.9-8.5v-17l14.9-8.5 14.9 8.5h18.2V69.7l-33-19-33 19v38.1l33 19 33-19V97.2z'/%3E%3C/svg%3E");
|
8 |
+
z-index: 1000;
|
9 |
+
}
|
10 |
+
|
11 |
+
div.civitai-status:before {
|
12 |
+
width:6px;
|
13 |
+
height:6px;
|
14 |
+
background: red;
|
15 |
+
border-radius: 50%;
|
16 |
+
content: '';
|
17 |
+
position:absolute;
|
18 |
+
top:-4px;
|
19 |
+
right:1px;
|
20 |
+
border: 1px solid rgba(255,255,255,0.3);
|
21 |
+
}
|
22 |
+
|
23 |
+
/* blinking animation */
|
24 |
+
@keyframes blink {
|
25 |
+
0% { opacity: 0.2; }
|
26 |
+
50% { opacity: 1; }
|
27 |
+
100% { opacity: 0.2; }
|
28 |
+
}
|
29 |
+
|
30 |
+
div.civitai-status.connected:before {
|
31 |
+
background:green;
|
32 |
+
animation: blink 1s ease-in-out infinite;
|
33 |
+
}
|