File size: 4,238 Bytes
9b34f86
 
 
 
 
 
 
 
 
 
 
 
 
923cb30
 
 
9b34f86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d33db96
9b34f86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d33db96
9b34f86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import torch
from diffusers import (
    StableDiffusionControlNetPipeline,
    ControlNetModel,
    EulerAncestralDiscreteScheduler,
)
from typing import Dict, List, Any

import qrcode
import os
import base64
from io import BytesIO

from pyzbar.pyzbar import decode
from PIL import Image

MODEL_ID = "simdi/colorful_qr"
WIDTH = 768
HEIGHT = 768

WEIGHT_PAIRS = [
    (0.25, 0.20),
    (0.25, 0.25),
    (0.35, 0.20),
    (0.35, 0.25),
    (0.45, 0.20),
    (0.45, 0.25),
]


def float_to_pair_index(f: float):
    length = len(WEIGHT_PAIRS)
    # If f is less than length, convert to integer and use directly
    if f < length:
        return int(f)
    # If f is greater or equal to length, assume it's a proportion of the length
    else:
        # Ensuring f is between 0 and 1
        f = max(0.0, min(f, 1.0))
        # Convert the float to an index
        index = int(f * length)
        # Make sure the index is in the valid range
        index = min(index, length - 1)
        return index


def select_weight_pair(f: float):
    return WEIGHT_PAIRS[float_to_pair_index(f)]


def load_models():
    controlnet_tile = ControlNetModel.from_pretrained(
        "lllyasviel/control_v11f1e_sd15_tile",
        torch_dtype=torch.float16,
    )

    controlnet_brightness = ControlNetModel.from_pretrained(
        "ioclab/control_v1p_sd15_brightness",
        torch_dtype=torch.float16,
    )

    pipe = StableDiffusionControlNetPipeline.from_pretrained(
        MODEL_ID,
        controlnet=[
            controlnet_tile,
            controlnet_brightness,
        ],
        torch_dtype=torch.float16,
        cache_dir="cache",
        # local_files_only=True,
    ).to("cuda")

    pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
    pipe.enable_xformers_memory_efficient_attention()
    return pipe


def resize_for_condition_image(input_image, resolution: int):
    input_image = input_image.convert("RGB")
    W, H = input_image.size
    k = float(resolution) / min(H, W)
    H *= k
    W *= k
    H = int(round(H / 64.0)) * 64
    W = int(round(W / 64.0)) * 64
    img = input_image.resize((W, H), resample=Image.LANCZOS)
    return img


def generate_qr_code(content: str):
    qrcode_generator = qrcode.QRCode(
        version=1,
        error_correction=qrcode.ERROR_CORRECT_H,
        box_size=10,
        border=2,
    )
    qrcode_generator.clear()
    qrcode_generator.add_data(content)
    qrcode_generator.make(fit=True)
    img = qrcode_generator.make_image(fill_color="black", back_color="white")
    img = resize_for_condition_image(img, 768)
    return img


def image_to_base64(image):
    buffered = BytesIO()
    image.save(buffered, format="PNG")
    return base64.b64encode(buffered.getvalue()).decode("utf-8")


def generate_image_with_conditioning_scale(**inputs):
    styles = inputs["styles"]
    pair = inputs["pair"]
    pipe = inputs["pipe"]
    qr_image = inputs["qr_image"]
    generator = inputs["generator"]

    images = pipe(
        prompt=styles,
        negative_prompt=[""] * len(styles),
        width=WIDTH,
        height=HEIGHT,
        guidance_scale=7.0,
        generator=generator,
        num_inference_steps=25,
        num_images_per_prompt=2,
        controlnet_conditioning_scale=pair,
        image=[qr_image] * 2,
    ).images

    return [{"data": image_to_base64(image), "format": "png"} for image in images]


def generate_image(pipe, inputs):
    styles = inputs["styles"]
    content = inputs["content"]
    art_scale = inputs["art_scale"]

    with torch.inference_mode():
        with torch.autocast("cuda"):

            qr_image = generate_qr_code(content)
            generator = torch.Generator()
            pair = select_weight_pair(art_scale)
            return generate_image_with_conditioning_scale(
                styles=styles,
                pair=pair,
                pipe=pipe,
                qr_image=qr_image,
                generator=generator,
            )


class EndpointHandler:
    def __init__(self, path=""):
        self._model = load_models()

    def __call__(self, model_input: Dict[str, Any]) -> List[Dict[str, Any]]:
        images = generate_image(self._model, model_input)
        return images