Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,7 @@ import spaces
|
|
2 |
import random
|
3 |
import torch
|
4 |
from huggingface_hub import snapshot_download
|
5 |
-
from transformers import
|
6 |
from kolors.pipelines import pipeline_stable_diffusion_xl_chatglm_256_ipadapter, pipeline_stable_diffusion_xl_chatglm_256
|
7 |
from kolors.models.modeling_chatglm import ChatGLMModel
|
8 |
from kolors.models.tokenization_chatglm import ChatGLMTokenizer
|
@@ -10,37 +10,34 @@ from kolors.models import unet_2d_condition
|
|
10 |
from diffusers import AutoencoderKL, EulerDiscreteScheduler, UNet2DConditionModel
|
11 |
import gradio as gr
|
12 |
import numpy as np
|
|
|
13 |
import os
|
14 |
-
from
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
|
19 |
-
device =
|
20 |
-
|
21 |
-
# ๋ชจ๋ธ ์ฒดํฌํฌ์ธํธ ๋ค์ด๋ก๋
|
22 |
ckpt_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors")
|
23 |
ckpt_IPA_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors-IP-Adapter-Plus")
|
24 |
|
25 |
-
# ChatGLMModel, AutoencoderKL, EulerDiscreteScheduler, UNet2DConditionModel ๋ก๋
|
26 |
text_encoder = ChatGLMModel.from_pretrained(f'{ckpt_dir}/text_encoder', torch_dtype=torch.float16).half().to(device)
|
27 |
tokenizer = ChatGLMTokenizer.from_pretrained(f'{ckpt_dir}/text_encoder')
|
28 |
vae = AutoencoderKL.from_pretrained(f"{ckpt_dir}/vae", revision=None).half().to(device)
|
29 |
scheduler = EulerDiscreteScheduler.from_pretrained(f"{ckpt_dir}/scheduler")
|
30 |
unet_t2i = UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
31 |
unet_i2i = unet_2d_condition.UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
32 |
-
image_encoder =
|
33 |
-
|
34 |
ip_img_size = 336
|
35 |
-
|
36 |
|
37 |
-
# Stable Diffusion ํ์ดํ๋ผ์ธ ์ค์
|
38 |
pipe_t2i = pipeline_stable_diffusion_xl_chatglm_256.StableDiffusionXLPipeline(
|
39 |
vae=vae,
|
40 |
-
text_encoder=text_encoder,
|
41 |
-
tokenizer=tokenizer,
|
42 |
-
unet=unet_t2i,
|
43 |
-
scheduler=scheduler,
|
44 |
force_zeros_for_empty_prompt=False
|
45 |
).to(device)
|
46 |
|
@@ -51,7 +48,7 @@ pipe_i2i = pipeline_stable_diffusion_xl_chatglm_256_ipadapter.StableDiffusionXLP
|
|
51 |
unet=unet_i2i,
|
52 |
scheduler=scheduler,
|
53 |
image_encoder=image_encoder,
|
54 |
-
feature_extractor=
|
55 |
force_zeros_for_empty_prompt=False
|
56 |
).to(device)
|
57 |
|
@@ -60,23 +57,37 @@ if hasattr(pipe_i2i.unet, 'encoder_hid_proj'):
|
|
60 |
|
61 |
pipe_i2i.load_ip_adapter(f'{ckpt_IPA_dir}' , subfolder="", weight_name=["ip_adapter_plus_general.bin"])
|
62 |
|
63 |
-
# CLIP ๋ชจ๋ธ ๋ฐ ํ๋ก์ธ์ ๋ก๋
|
64 |
-
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
|
65 |
-
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
66 |
-
|
67 |
MAX_SEED = np.iinfo(np.int32).max
|
68 |
MAX_IMAGE_SIZE = 1024
|
69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
@spaces.GPU
|
71 |
-
def infer(prompt,
|
72 |
-
ip_adapter_image = None,
|
73 |
-
ip_adapter_scale = 0.5,
|
74 |
-
negative_prompt = "",
|
75 |
-
seed = 0,
|
76 |
-
randomize_seed = False,
|
77 |
-
width = 1024,
|
78 |
-
height = 1024,
|
79 |
-
guidance_scale = 5.0,
|
80 |
num_inference_steps = 25
|
81 |
):
|
82 |
if randomize_seed:
|
@@ -86,15 +97,15 @@ def infer(prompt,
|
|
86 |
if ip_adapter_image is None:
|
87 |
pipe_t2i.to(device)
|
88 |
image = pipe_t2i(
|
89 |
-
prompt = prompt,
|
90 |
negative_prompt = negative_prompt,
|
91 |
-
guidance_scale = guidance_scale,
|
92 |
-
num_inference_steps = num_inference_steps,
|
93 |
-
width = width,
|
94 |
height = height,
|
95 |
generator = generator
|
96 |
-
).images[0]
|
97 |
-
image.save("generated_image.jpg")
|
98 |
return image, "generated_image.jpg"
|
99 |
else:
|
100 |
pipe_i2i.to(device)
|
@@ -104,24 +115,54 @@ def infer(prompt,
|
|
104 |
image = pipe_i2i(
|
105 |
prompt=prompt,
|
106 |
ip_adapter_image=[ip_adapter_image],
|
107 |
-
negative_prompt=negative_prompt,
|
108 |
height=height,
|
109 |
width=width,
|
110 |
-
num_inference_steps=num_inference_steps,
|
111 |
guidance_scale=guidance_scale,
|
112 |
num_images_per_prompt=1,
|
113 |
generator=generator
|
114 |
).images[0]
|
115 |
-
image.save("generated_image.jpg")
|
116 |
return image, "generated_image.jpg"
|
117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
def describe_image(image):
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
css="""
|
127 |
#col-left {
|
@@ -137,6 +178,21 @@ css="""
|
|
137 |
with gr.Blocks(css=css) as Kolors:
|
138 |
with gr.Row():
|
139 |
with gr.Column(elem_id="col-left"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
with gr.Row():
|
141 |
generated_prompt = gr.Textbox(
|
142 |
label="ํ๋กฌํํธ ์
๋ ฅ",
|
@@ -205,16 +261,24 @@ with gr.Blocks(css=css) as Kolors:
|
|
205 |
result = gr.Image(label="Result", show_label=False)
|
206 |
download_button = gr.File(label="Download Image")
|
207 |
image_description = gr.Textbox(label="Image Description", placeholder="์ด๋ฏธ์ง ๋ถ์ ๊ฒฐ๊ณผ๊ฐ ์ฌ๊ธฐ์ ํ์๋ฉ๋๋ค.", interactive=False)
|
|
|
208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
# ์ด๋ฏธ์ง ์์ฑ ๋ฐ ๋ค์ด๋ก๋ ํ์ผ ๊ฒฝ๋ก ์ค์
|
210 |
run_button.click(
|
211 |
fn=infer,
|
212 |
inputs=[generated_prompt, ip_adapter_image, ip_adapter_scale, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
|
213 |
outputs=[result, download_button]
|
214 |
)
|
215 |
-
|
216 |
# ์ด๋ฏธ์ง ์ค๋ช
์์ฑ
|
217 |
-
|
218 |
fn=describe_image,
|
219 |
inputs=[ip_adapter_image],
|
220 |
outputs=[image_description]
|
|
|
2 |
import random
|
3 |
import torch
|
4 |
from huggingface_hub import snapshot_download
|
5 |
+
from transformers import CLIPVisionModelWithProjection, CLIPImageProcessor
|
6 |
from kolors.pipelines import pipeline_stable_diffusion_xl_chatglm_256_ipadapter, pipeline_stable_diffusion_xl_chatglm_256
|
7 |
from kolors.models.modeling_chatglm import ChatGLMModel
|
8 |
from kolors.models.tokenization_chatglm import ChatGLMTokenizer
|
|
|
10 |
from diffusers import AutoencoderKL, EulerDiscreteScheduler, UNet2DConditionModel
|
11 |
import gradio as gr
|
12 |
import numpy as np
|
13 |
+
from huggingface_hub import InferenceClient
|
14 |
import os
|
15 |
+
from PIL import Image
|
16 |
+
import re
|
17 |
|
18 |
+
# Cohere ๋ชจ๋ธ ์ด๊ธฐํ
|
19 |
+
client = InferenceClient("CohereForAI/c4ai-command-r-plus", token=os.getenv("HF_TOKEN"))
|
20 |
|
21 |
+
device = "cuda"
|
|
|
|
|
22 |
ckpt_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors")
|
23 |
ckpt_IPA_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors-IP-Adapter-Plus")
|
24 |
|
|
|
25 |
text_encoder = ChatGLMModel.from_pretrained(f'{ckpt_dir}/text_encoder', torch_dtype=torch.float16).half().to(device)
|
26 |
tokenizer = ChatGLMTokenizer.from_pretrained(f'{ckpt_dir}/text_encoder')
|
27 |
vae = AutoencoderKL.from_pretrained(f"{ckpt_dir}/vae", revision=None).half().to(device)
|
28 |
scheduler = EulerDiscreteScheduler.from_pretrained(f"{ckpt_dir}/scheduler")
|
29 |
unet_t2i = UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
30 |
unet_i2i = unet_2d_condition.UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
31 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(f'{ckpt_IPA_dir}/image_encoder', ignore_mismatched_sizes=True).to(dtype=torch.float16, device=device)
|
|
|
32 |
ip_img_size = 336
|
33 |
+
clip_image_processor = CLIPImageProcessor(size=ip_img_size, crop_size=ip_img_size)
|
34 |
|
|
|
35 |
pipe_t2i = pipeline_stable_diffusion_xl_chatglm_256.StableDiffusionXLPipeline(
|
36 |
vae=vae,
|
37 |
+
text_encoder=text_encoder,
|
38 |
+
tokenizer=tokenizer,
|
39 |
+
unet=unet_t2i,
|
40 |
+
scheduler=scheduler,
|
41 |
force_zeros_for_empty_prompt=False
|
42 |
).to(device)
|
43 |
|
|
|
48 |
unet=unet_i2i,
|
49 |
scheduler=scheduler,
|
50 |
image_encoder=image_encoder,
|
51 |
+
feature_extractor=clip_image_processor,
|
52 |
force_zeros_for_empty_prompt=False
|
53 |
).to(device)
|
54 |
|
|
|
57 |
|
58 |
pipe_i2i.load_ip_adapter(f'{ckpt_IPA_dir}' , subfolder="", weight_name=["ip_adapter_plus_general.bin"])
|
59 |
|
|
|
|
|
|
|
|
|
60 |
MAX_SEED = np.iinfo(np.int32).max
|
61 |
MAX_IMAGE_SIZE = 1024
|
62 |
|
63 |
+
def call_api(content, system_message, max_tokens=1000, temperature=0.7, top_p=0.95):
|
64 |
+
messages = [{"role": "system", "content": system_message}, {"role": "user", "content": content}]
|
65 |
+
response = client.chat_completion(messages, max_tokens=max_tokens, temperature=temperature, top_p=top_p)
|
66 |
+
return response.choices[0].message['content']
|
67 |
+
|
68 |
+
def generate_prompt(korean_prompt):
|
69 |
+
system_message = """
|
70 |
+
Given the following description in Korean,
|
71 |
+
translate and generate a concise English prompt suitable for a Stable Diffusion model.
|
72 |
+
The prompt should be focused, descriptive,
|
73 |
+
and contain specific keywords or phrases that will help guide the image generation process.
|
74 |
+
Use simple and descriptive language, avoiding unnecessary words.
|
75 |
+
Ensure the output is in English and follows the format typically used in Stable Diffusion prompts.
|
76 |
+
The description is: [Insert Korean description here]
|
77 |
+
"""
|
78 |
+
optimized_prompt = call_api(korean_prompt, system_message)
|
79 |
+
return optimized_prompt # ์ต์ ํ๋ ํ๋กฌํํธ ๋ฐํ
|
80 |
+
|
81 |
@spaces.GPU
|
82 |
+
def infer(prompt,
|
83 |
+
ip_adapter_image = None,
|
84 |
+
ip_adapter_scale = 0.5,
|
85 |
+
negative_prompt = "",
|
86 |
+
seed = 0,
|
87 |
+
randomize_seed = False,
|
88 |
+
width = 1024,
|
89 |
+
height = 1024,
|
90 |
+
guidance_scale = 5.0,
|
91 |
num_inference_steps = 25
|
92 |
):
|
93 |
if randomize_seed:
|
|
|
97 |
if ip_adapter_image is None:
|
98 |
pipe_t2i.to(device)
|
99 |
image = pipe_t2i(
|
100 |
+
prompt = prompt,
|
101 |
negative_prompt = negative_prompt,
|
102 |
+
guidance_scale = guidance_scale,
|
103 |
+
num_inference_steps = num_inference_steps,
|
104 |
+
width = width,
|
105 |
height = height,
|
106 |
generator = generator
|
107 |
+
).images[0]
|
108 |
+
image.save("generated_image.jpg") # ํ์ผ ํ์ฅ์๋ฅผ .jpg๋ก ๋ณ๊ฒฝ
|
109 |
return image, "generated_image.jpg"
|
110 |
else:
|
111 |
pipe_i2i.to(device)
|
|
|
115 |
image = pipe_i2i(
|
116 |
prompt=prompt,
|
117 |
ip_adapter_image=[ip_adapter_image],
|
118 |
+
negative_prompt=negative_prompt,
|
119 |
height=height,
|
120 |
width=width,
|
121 |
+
num_inference_steps=num_inference_steps,
|
122 |
guidance_scale=guidance_scale,
|
123 |
num_images_per_prompt=1,
|
124 |
generator=generator
|
125 |
).images[0]
|
126 |
+
image.save("generated_image.jpg") # ํ์ผ ํ์ฅ์๋ฅผ .jpg๋ก ๋ณ๊ฒฝ
|
127 |
return image, "generated_image.jpg"
|
128 |
|
129 |
+
# ์ฌ์ง ์ค๋ช
๊ธฐ๋ฅ ์ถ๊ฐ๋ฅผ ์ํ ์ฐธ์กฐ ์ฝ๋ ํตํฉ
|
130 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
131 |
+
|
132 |
+
model = AutoModelForCausalLM.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True).to("cuda").eval()
|
133 |
+
processor = AutoProcessor.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True)
|
134 |
+
|
135 |
+
def modify_caption(caption: str) -> str:
|
136 |
+
prefix_substrings = [
|
137 |
+
('captured from ', ''),
|
138 |
+
('captured at ', '')
|
139 |
+
]
|
140 |
+
pattern = '|'.join([re.escape(opening) for opening, _ in prefix_substrings])
|
141 |
+
replacers = {opening.lower(): replacer for opening, replacer in prefix_substrings}
|
142 |
+
def replace_fn(match):
|
143 |
+
return replacers[match.group(0).lower()]
|
144 |
+
modified_caption = re.sub(pattern, replace_fn, caption, count=1, flags=re.IGNORECASE)
|
145 |
+
return modified_caption if modified_caption != caption else caption
|
146 |
+
|
147 |
+
@spaces.GPU
|
148 |
def describe_image(image):
|
149 |
+
image = Image.fromarray(image)
|
150 |
+
task_prompt = "<DESCRIPTION>"
|
151 |
+
prompt = task_prompt + "Describe this image in great detail."
|
152 |
+
|
153 |
+
if image.mode != "RGB":
|
154 |
+
image = image.convert("RGB")
|
155 |
+
|
156 |
+
inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
|
157 |
+
generated_ids = model.generate(
|
158 |
+
input_ids=inputs["input_ids"],
|
159 |
+
pixel_values=inputs["pixel_values"],
|
160 |
+
max_new_tokens=1024,
|
161 |
+
num_beams=3
|
162 |
+
)
|
163 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
|
164 |
+
parsed_answer = processor.post_process_generation(generated_text, task=task_prompt, image_size=(image.width, image.height))
|
165 |
+
return modify_caption(parsed_answer["<DESCRIPTION>"])
|
166 |
|
167 |
css="""
|
168 |
#col-left {
|
|
|
178 |
with gr.Blocks(css=css) as Kolors:
|
179 |
with gr.Row():
|
180 |
with gr.Column(elem_id="col-left"):
|
181 |
+
with gr.Row():
|
182 |
+
korean_prompt = gr.Textbox(
|
183 |
+
label="ํ๊ตญ์ด ํ๋กฌํํธ ์
๋ ฅ",
|
184 |
+
placeholder="ํ๊ตญ์ด๋ก ์ํ๋ ํ๋กฌํํธ๋ฅผ ์
๋ ฅํ์ธ์",
|
185 |
+
lines=2
|
186 |
+
)
|
187 |
+
with gr.Row():
|
188 |
+
generate_prompt_button = gr.Button("Generate Prompt")
|
189 |
+
with gr.Row():
|
190 |
+
optimized_prompt = gr.Textbox(
|
191 |
+
label="์ต์ ํ๋ ํ๋กฌํํธ ์์ฑ",
|
192 |
+
placeholder=" ",
|
193 |
+
lines=2,
|
194 |
+
interactive=False
|
195 |
+
)
|
196 |
with gr.Row():
|
197 |
generated_prompt = gr.Textbox(
|
198 |
label="ํ๋กฌํํธ ์
๋ ฅ",
|
|
|
261 |
result = gr.Image(label="Result", show_label=False)
|
262 |
download_button = gr.File(label="Download Image")
|
263 |
image_description = gr.Textbox(label="Image Description", placeholder="์ด๋ฏธ์ง ๋ถ์ ๊ฒฐ๊ณผ๊ฐ ์ฌ๊ธฐ์ ํ์๋ฉ๋๋ค.", interactive=False)
|
264 |
+
analyze_button = gr.Button("Analyze Image")
|
265 |
|
266 |
+
# ์ต์ ํ๋ ํ๋กฌํํธ ์์ฑ ๋ฐ ๊ฒฐ๊ณผ ํ์
|
267 |
+
generate_prompt_button.click(
|
268 |
+
fn=generate_prompt,
|
269 |
+
inputs=[korean_prompt],
|
270 |
+
outputs=[optimized_prompt]
|
271 |
+
)
|
272 |
+
|
273 |
# ์ด๋ฏธ์ง ์์ฑ ๋ฐ ๋ค์ด๋ก๋ ํ์ผ ๊ฒฝ๋ก ์ค์
|
274 |
run_button.click(
|
275 |
fn=infer,
|
276 |
inputs=[generated_prompt, ip_adapter_image, ip_adapter_scale, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
|
277 |
outputs=[result, download_button]
|
278 |
)
|
279 |
+
|
280 |
# ์ด๋ฏธ์ง ์ค๋ช
์์ฑ
|
281 |
+
analyze_button.click(
|
282 |
fn=describe_image,
|
283 |
inputs=[ip_adapter_image],
|
284 |
outputs=[image_description]
|