styles.py 2.7 KB
Newer Older
A
AUTOMATIC 已提交
1
import csv
2
import os
A
AUTOMATIC 已提交
3
import os.path
4 5
import typing
import shutil
A
AUTOMATIC 已提交
6 7


8 9 10 11
class PromptStyle(typing.NamedTuple):
    name: str
    prompt: str
    negative_prompt: str
A
AUTOMATIC 已提交
12 13


A
AUTOMATIC 已提交
14 15 16 17 18 19
def merge_prompts(style_prompt: str, prompt: str) -> str:
    if "{prompt}" in style_prompt:
        res = style_prompt.replace("{prompt}", prompt)
    else:
        parts = filter(None, (prompt.strip(), style_prompt.strip()))
        res = ", ".join(parts)
A
AUTOMATIC 已提交
20

A
AUTOMATIC 已提交
21
    return res
A
AUTOMATIC 已提交
22 23


A
AUTOMATIC 已提交
24 25 26
def apply_styles_to_prompt(prompt, styles):
    for style in styles:
        prompt = merge_prompts(style, prompt)
27

A
AUTOMATIC 已提交
28
    return prompt
A
AUTOMATIC 已提交
29 30


A
AUTOMATIC 已提交
31 32 33
class StyleDatabase:
    def __init__(self, path: str):
        self.no_style = PromptStyle("None", "", "")
34 35
        self.styles = {}
        self.path = path
A
AUTOMATIC 已提交
36

37 38 39 40 41 42
        self.reload()

    def reload(self):
        self.styles.clear()

        if not os.path.exists(self.path):
A
AUTOMATIC 已提交
43 44
            return

45
        with open(self.path, "r", encoding="utf-8-sig", newline='') as file:
46
            reader = csv.DictReader(file, skipinitialspace=True)
A
AUTOMATIC 已提交
47 48 49 50 51 52
            for row in reader:
                # Support loading old CSV format with "name, text"-columns
                prompt = row["prompt"] if "prompt" in row else row["text"]
                negative_prompt = row.get("negative_prompt", "")
                self.styles[row["name"]] = PromptStyle(row["name"], prompt, negative_prompt)

53 54 55 56 57 58
    def get_style_prompts(self, styles):
        return [self.styles.get(x, self.no_style).prompt for x in styles]

    def get_negative_style_prompts(self, styles):
        return [self.styles.get(x, self.no_style).negative_prompt for x in styles]

A
AUTOMATIC 已提交
59 60 61 62 63 64 65
    def apply_styles_to_prompt(self, prompt, styles):
        return apply_styles_to_prompt(prompt, [self.styles.get(x, self.no_style).prompt for x in styles])

    def apply_negative_styles_to_prompt(self, prompt, styles):
        return apply_styles_to_prompt(prompt, [self.styles.get(x, self.no_style).negative_prompt for x in styles])

    def save_styles(self, path: str) -> None:
66 67
        # Always keep a backup file around
        if os.path.exists(path):
68
            shutil.copy(path, f"{path}.bak")
69 70

        fd = os.open(path, os.O_RDWR|os.O_CREAT)
W
w-e-w 已提交
71
        with os.fdopen(fd, "w", encoding="utf-8-sig", newline='') as file:
A
AUTOMATIC 已提交
72 73 74 75 76
            # _fields is actually part of the public API: typing.NamedTuple is a replacement for collections.NamedTuple,
            # and collections.NamedTuple has explicit documentation for accessing _fields. Same goes for _asdict()
            writer = csv.DictWriter(file, fieldnames=PromptStyle._fields)
            writer.writeheader()
            writer.writerows(style._asdict() for k,     style in self.styles.items())