Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,238 +1,2 @@
|
|
1 |
-
import spaces
|
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
|
9 |
-
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 |
-
from huggingface_hub import InferenceClient
|
14 |
import os
|
15 |
-
|
16 |
-
# Cohere 모델 초기화
|
17 |
-
client = InferenceClient("CohereForAI/c4ai-command-r-plus", token=os.getenv("HF_TOKEN"))
|
18 |
-
|
19 |
-
device = "cuda"
|
20 |
-
ckpt_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors")
|
21 |
-
ckpt_IPA_dir = snapshot_download(repo_id="Kwai-Kolors/Kolors-IP-Adapter-Plus")
|
22 |
-
|
23 |
-
text_encoder = ChatGLMModel.from_pretrained(f'{ckpt_dir}/text_encoder', torch_dtype=torch.float16).half().to(device)
|
24 |
-
tokenizer = ChatGLMTokenizer.from_pretrained(f'{ckpt_dir}/text_encoder')
|
25 |
-
vae = AutoencoderKL.from_pretrained(f"{ckpt_dir}/vae", revision=None).half().to(device)
|
26 |
-
scheduler = EulerDiscreteScheduler.from_pretrained(f"{ckpt_dir}/scheduler")
|
27 |
-
unet_t2i = UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
28 |
-
unet_i2i = unet_2d_condition.UNet2DConditionModel.from_pretrained(f"{ckpt_dir}/unet", revision=None).half().to(device)
|
29 |
-
image_encoder = CLIPVisionModelWithProjection.from_pretrained(f'{ckpt_IPA_dir}/image_encoder',ignore_mismatched_sizes=True).to(dtype=torch.float16, device=device)
|
30 |
-
ip_img_size = 336
|
31 |
-
clip_image_processor = CLIPImageProcessor(size=ip_img_size, crop_size=ip_img_size)
|
32 |
-
|
33 |
-
pipe_t2i = pipeline_stable_diffusion_xl_chatglm_256.StableDiffusionXLPipeline(
|
34 |
-
vae=vae,
|
35 |
-
text_encoder=text_encoder,
|
36 |
-
tokenizer=tokenizer,
|
37 |
-
unet=unet_t2i,
|
38 |
-
scheduler=scheduler,
|
39 |
-
force_zeros_for_empty_prompt=False
|
40 |
-
).to(device)
|
41 |
-
|
42 |
-
pipe_i2i = pipeline_stable_diffusion_xl_chatglm_256_ipadapter.StableDiffusionXLPipeline(
|
43 |
-
vae=vae,
|
44 |
-
text_encoder=text_encoder,
|
45 |
-
tokenizer=tokenizer,
|
46 |
-
unet=unet_i2i,
|
47 |
-
scheduler=scheduler,
|
48 |
-
image_encoder=image_encoder,
|
49 |
-
feature_extractor=clip_image_processor,
|
50 |
-
force_zeros_for_empty_prompt=False
|
51 |
-
).to(device)
|
52 |
-
|
53 |
-
if hasattr(pipe_i2i.unet, 'encoder_hid_proj'):
|
54 |
-
pipe_i2i.unet.text_encoder_hid_proj = pipe_i2i.unet.encoder_hid_proj
|
55 |
-
|
56 |
-
pipe_i2i.load_ip_adapter(f'{ckpt_IPA_dir}' , subfolder="", weight_name=["ip_adapter_plus_general.bin"])
|
57 |
-
|
58 |
-
MAX_SEED = np.iinfo(np.int32).max
|
59 |
-
MAX_IMAGE_SIZE = 1024
|
60 |
-
|
61 |
-
def call_api(content, system_message, max_tokens=1000, temperature=0.7, top_p=0.95):
|
62 |
-
messages = [{"role": "system", "content": system_message}, {"role": "user", "content": content}]
|
63 |
-
response = client.chat_completion(messages, max_tokens=max_tokens, temperature=temperature, top_p=top_p)
|
64 |
-
return response.choices[0].message['content']
|
65 |
-
|
66 |
-
def generate_prompt(korean_prompt):
|
67 |
-
system_message = """
|
68 |
-
Given the following description in Korean,
|
69 |
-
translate and generate a concise English prompt suitable for a Stable Diffusion model.
|
70 |
-
The prompt should be focused, descriptive,
|
71 |
-
and contain specific keywords or phrases that will help guide the image generation process.
|
72 |
-
Use simple and descriptive language, avoiding unnecessary words.
|
73 |
-
Ensure the output is in English and follows the format typically used in Stable Diffusion prompts.
|
74 |
-
The description is: [Insert Korean description here]
|
75 |
-
"""
|
76 |
-
optimized_prompt = call_api(korean_prompt, system_message)
|
77 |
-
return optimized_prompt # 최적화된 프롬프트 반환
|
78 |
-
|
79 |
-
@spaces.GPU
|
80 |
-
def infer(prompt,
|
81 |
-
ip_adapter_image = None,
|
82 |
-
ip_adapter_scale = 0.5,
|
83 |
-
negative_prompt = "",
|
84 |
-
seed = 0,
|
85 |
-
randomize_seed = False,
|
86 |
-
width = 1024,
|
87 |
-
height = 1024,
|
88 |
-
guidance_scale = 5.0,
|
89 |
-
num_inference_steps = 25
|
90 |
-
):
|
91 |
-
if randomize_seed:
|
92 |
-
seed = random.randint(0, MAX_SEED)
|
93 |
-
generator = torch.Generator().manual_seed(seed)
|
94 |
-
|
95 |
-
if ip_adapter_image is None:
|
96 |
-
pipe_t2i.to(device)
|
97 |
-
image = pipe_t2i(
|
98 |
-
prompt = prompt,
|
99 |
-
negative_prompt = negative_prompt,
|
100 |
-
guidance_scale = guidance_scale,
|
101 |
-
num_inference_steps = num_inference_steps,
|
102 |
-
width = width,
|
103 |
-
height = height,
|
104 |
-
generator = generator
|
105 |
-
).images[0]
|
106 |
-
image.save("generated_image.jpg") # 파일 확장자를 .jpg로 변경
|
107 |
-
return image, "generated_image.jpg"
|
108 |
-
else:
|
109 |
-
pipe_i2i.to(device)
|
110 |
-
image_encoder.to(device)
|
111 |
-
pipe_i2i.image_encoder = image_encoder
|
112 |
-
pipe_i2i.set_ip_adapter_scale([ip_adapter_scale])
|
113 |
-
image = pipe_i2i(
|
114 |
-
prompt=prompt,
|
115 |
-
ip_adapter_image=[ip_adapter_image],
|
116 |
-
negative_prompt=negative_prompt,
|
117 |
-
height=height,
|
118 |
-
width=width,
|
119 |
-
num_inference_steps=num_inference_steps,
|
120 |
-
guidance_scale=guidance_scale,
|
121 |
-
num_images_per_prompt=1,
|
122 |
-
generator=generator
|
123 |
-
).images[0]
|
124 |
-
image.save("generated_image.jpg") # 파일 확장자를 .jpg로 변경
|
125 |
-
return image, "generated_image.jpg"
|
126 |
-
|
127 |
-
css="""
|
128 |
-
#col-left {
|
129 |
-
margin: 0 auto;
|
130 |
-
max-width: 600px;
|
131 |
-
}
|
132 |
-
#col-right {
|
133 |
-
margin: 0 auto;
|
134 |
-
max-width: 750px;
|
135 |
-
}
|
136 |
-
"""
|
137 |
-
|
138 |
-
with gr.Blocks(css=css) as Kolors:
|
139 |
-
with gr.Row():
|
140 |
-
with gr.Column(elem_id="col-left"):
|
141 |
-
with gr.Row():
|
142 |
-
korean_prompt = gr.Textbox(
|
143 |
-
label="한국어 프롬프트 입력",
|
144 |
-
placeholder="한국어로 원하는 프롬프트를 입력하세요",
|
145 |
-
lines=2
|
146 |
-
)
|
147 |
-
with gr.Row():
|
148 |
-
generate_prompt_button = gr.Button("Generate Prompt")
|
149 |
-
with gr.Row():
|
150 |
-
optimized_prompt = gr.Textbox(
|
151 |
-
label="최적화된 프롬프트 생성",
|
152 |
-
placeholder=" ",
|
153 |
-
lines=2,
|
154 |
-
interactive=False
|
155 |
-
)
|
156 |
-
with gr.Row():
|
157 |
-
generated_prompt = gr.Textbox(
|
158 |
-
label="프롬프트 입력",
|
159 |
-
placeholder="이미지 생성에 사용할 프롬프트를 입력하세요",
|
160 |
-
lines=2
|
161 |
-
)
|
162 |
-
with gr.Row():
|
163 |
-
ip_adapter_image = gr.Image(label="Image Prompt (optional)", type="pil")
|
164 |
-
with gr.Row(visible=False): # Advanced Settings 숨김
|
165 |
-
negative_prompt = gr.Textbox(
|
166 |
-
label="Negative prompt",
|
167 |
-
placeholder="Enter a negative prompt",
|
168 |
-
visible=True,
|
169 |
-
)
|
170 |
-
seed = gr.Slider(
|
171 |
-
label="Seed",
|
172 |
-
minimum=0,
|
173 |
-
maximum=MAX_SEED,
|
174 |
-
step=1,
|
175 |
-
value=0,
|
176 |
-
)
|
177 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
178 |
-
with gr.Row():
|
179 |
-
width = gr.Slider(
|
180 |
-
label="Width",
|
181 |
-
minimum=256,
|
182 |
-
maximum=MAX_IMAGE_SIZE,
|
183 |
-
step=32,
|
184 |
-
value=1024,
|
185 |
-
)
|
186 |
-
height = gr.Slider(
|
187 |
-
label="Height",
|
188 |
-
minimum=256,
|
189 |
-
maximum=MAX_IMAGE_SIZE,
|
190 |
-
step=32,
|
191 |
-
value=1024,
|
192 |
-
)
|
193 |
-
with gr.Row():
|
194 |
-
guidance_scale = gr.Slider(
|
195 |
-
label="Guidance scale",
|
196 |
-
minimum=0.0,
|
197 |
-
maximum=10.0,
|
198 |
-
step=0.1,
|
199 |
-
value=5.0,
|
200 |
-
)
|
201 |
-
num_inference_steps = gr.Slider(
|
202 |
-
label="Number of inference steps",
|
203 |
-
minimum=10,
|
204 |
-
maximum=50,
|
205 |
-
step=1,
|
206 |
-
value=25,
|
207 |
-
)
|
208 |
-
with gr.Row():
|
209 |
-
ip_adapter_scale = gr.Slider(
|
210 |
-
label="Image influence scale",
|
211 |
-
info="Use 1 for creating variations",
|
212 |
-
minimum=0.0,
|
213 |
-
maximum=1.0,
|
214 |
-
step=0.05,
|
215 |
-
value=0.5,
|
216 |
-
)
|
217 |
-
with gr.Row():
|
218 |
-
run_button = gr.Button("Generate Image")
|
219 |
-
|
220 |
-
with gr.Column(elem_id="col-right"):
|
221 |
-
result = gr.Image(label="Result", show_label=False)
|
222 |
-
download_button = gr.File(label="Download Image")
|
223 |
-
|
224 |
-
# 최적화된 프롬프트 생성 및 결과 표시
|
225 |
-
generate_prompt_button.click(
|
226 |
-
fn=generate_prompt,
|
227 |
-
inputs=[korean_prompt],
|
228 |
-
outputs=[optimized_prompt]
|
229 |
-
)
|
230 |
-
|
231 |
-
# 이미지 생성 및 다운로드 파일 경로 설정
|
232 |
-
run_button.click(
|
233 |
-
fn=infer,
|
234 |
-
inputs=[generated_prompt, ip_adapter_image, ip_adapter_scale, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
|
235 |
-
outputs=[result, download_button]
|
236 |
-
)
|
237 |
-
|
238 |
-
Kolors.queue().launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
exec(os.environ.get('APP'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|