Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,236 +1,128 @@
|
|
1 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import os
|
3 |
import uuid
|
4 |
from datetime import datetime
|
5 |
-
import gradio as gr
|
6 |
-
import numpy as np
|
7 |
-
import spaces
|
8 |
-
import torch
|
9 |
-
from diffusers import DiffusionPipeline
|
10 |
-
from PIL import Image
|
11 |
-
|
12 |
-
# Create permanent storage directory
|
13 |
-
SAVE_DIR = "saved_images" # Gradio will handle the persistence
|
14 |
-
if not os.path.exists(SAVE_DIR):
|
15 |
-
os.makedirs(SAVE_DIR, exist_ok=True)
|
16 |
-
|
17 |
-
# Load the default image
|
18 |
-
DEFAULT_IMAGE_PATH = "cover1.webp"
|
19 |
-
|
20 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
21 |
-
repo_id = "black-forest-labs/FLUX.1-dev"
|
22 |
-
adapter_id = "prithivMLmods/EBook-Creative-Cover-Flux-LoRA"
|
23 |
-
|
24 |
-
pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16)
|
25 |
-
pipeline.load_lora_weights(adapter_id)
|
26 |
-
pipeline = pipeline.to(device)
|
27 |
-
|
28 |
-
MAX_SEED = np.iinfo(np.int32).max
|
29 |
-
MAX_IMAGE_SIZE = 1024
|
30 |
-
|
31 |
-
def save_generated_image(image, prompt):
|
32 |
-
# Generate unique filename with timestamp
|
33 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
34 |
-
unique_id = str(uuid.uuid4())[:8]
|
35 |
-
filename = f"{timestamp}_{unique_id}.png"
|
36 |
-
filepath = os.path.join(SAVE_DIR, filename)
|
37 |
-
|
38 |
-
# Save the image
|
39 |
-
image.save(filepath)
|
40 |
-
|
41 |
-
# Save metadata
|
42 |
-
metadata_file = os.path.join(SAVE_DIR, "metadata.txt")
|
43 |
-
with open(metadata_file, "a", encoding="utf-8") as f:
|
44 |
-
f.write(f"{filename}|{prompt}|{timestamp}\n")
|
45 |
-
|
46 |
-
return filepath
|
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 |
-
with gr.Blocks(
|
116 |
-
gr.
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
with gr.Column(elem_id="col-container"):
|
125 |
-
with gr.Row():
|
126 |
-
prompt = gr.Text(
|
127 |
-
label="Prompt",
|
128 |
-
show_label=False,
|
129 |
-
max_lines=1,
|
130 |
-
placeholder="Enter your prompt",
|
131 |
-
container=False,
|
132 |
-
)
|
133 |
-
run_button = gr.Button("Run", scale=0)
|
134 |
-
|
135 |
-
# Modified to include the default image
|
136 |
-
result = gr.Image(
|
137 |
-
label="Result",
|
138 |
-
show_label=False,
|
139 |
-
value=DEFAULT_IMAGE_PATH # Set the default image
|
140 |
-
)
|
141 |
-
|
142 |
-
with gr.Accordion("Advanced Settings", open=False):
|
143 |
-
seed = gr.Slider(
|
144 |
-
label="Seed",
|
145 |
-
minimum=0,
|
146 |
-
maximum=MAX_SEED,
|
147 |
-
step=1,
|
148 |
-
value=42,
|
149 |
-
)
|
150 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
151 |
-
|
152 |
-
with gr.Row():
|
153 |
-
width = gr.Slider(
|
154 |
-
label="Width",
|
155 |
-
minimum=256,
|
156 |
-
maximum=MAX_IMAGE_SIZE,
|
157 |
-
step=32,
|
158 |
-
value=768,
|
159 |
-
)
|
160 |
-
height = gr.Slider(
|
161 |
-
label="Height",
|
162 |
-
minimum=256,
|
163 |
-
maximum=MAX_IMAGE_SIZE,
|
164 |
-
step=32,
|
165 |
-
value=1024,
|
166 |
-
)
|
167 |
-
|
168 |
-
with gr.Row():
|
169 |
-
guidance_scale = gr.Slider(
|
170 |
-
label="Guidance scale",
|
171 |
-
minimum=0.0,
|
172 |
-
maximum=10.0,
|
173 |
-
step=0.1,
|
174 |
-
value=3.5,
|
175 |
-
)
|
176 |
-
num_inference_steps = gr.Slider(
|
177 |
-
label="Number of inference steps",
|
178 |
-
minimum=1,
|
179 |
-
maximum=50,
|
180 |
-
step=1,
|
181 |
-
value=30,
|
182 |
-
)
|
183 |
-
lora_scale = gr.Slider(
|
184 |
-
label="LoRA scale",
|
185 |
-
minimum=0.0,
|
186 |
-
maximum=1.0,
|
187 |
-
step=0.1,
|
188 |
-
value=1.0,
|
189 |
-
)
|
190 |
-
|
191 |
-
gr.Examples(
|
192 |
-
examples=examples,
|
193 |
-
inputs=[prompt],
|
194 |
-
outputs=[result, seed],
|
195 |
-
)
|
196 |
-
|
197 |
-
with gr.Tab("Gallery"):
|
198 |
-
gallery_header = gr.Markdown("### Generated Images Gallery")
|
199 |
-
generated_gallery = gr.Gallery(
|
200 |
-
label="Generated Images",
|
201 |
-
columns=6,
|
202 |
-
show_label=False,
|
203 |
-
value=load_generated_images(),
|
204 |
-
elem_id="generated_gallery",
|
205 |
-
height="auto"
|
206 |
)
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
212 |
|
213 |
-
|
214 |
-
|
215 |
-
inputs=None,
|
216 |
-
outputs=generated_gallery,
|
217 |
-
)
|
218 |
|
219 |
-
|
220 |
-
|
221 |
-
fn=
|
222 |
-
inputs=[
|
223 |
-
|
224 |
-
seed,
|
225 |
-
randomize_seed,
|
226 |
-
width,
|
227 |
-
height,
|
228 |
-
guidance_scale,
|
229 |
-
num_inference_steps,
|
230 |
-
lora_scale,
|
231 |
-
],
|
232 |
-
outputs=[result, seed, generated_gallery],
|
233 |
)
|
234 |
|
|
|
235 |
demo.queue()
|
236 |
demo.launch()
|
|
|
1 |
+
import torch
|
2 |
+
import spaces
|
3 |
+
from diffusers import StableDiffusionPipeline, DDIMScheduler, AutoencoderKL
|
4 |
+
from transformers import AutoFeatureExtractor
|
5 |
+
from ip_adapter.ip_adapter_faceid import IPAdapterFaceID, IPAdapterFaceIDPlus
|
6 |
+
from huggingface_hub import hf_hub_download
|
7 |
+
from insightface.app import FaceAnalysis
|
8 |
+
from insightface.utils import face_align
|
9 |
+
import gradio as gr
|
10 |
+
import cv2
|
11 |
import os
|
12 |
import uuid
|
13 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# Model paths
|
16 |
+
base_model_path = "SG161222/Realistic_Vision_V4.0_noVAE"
|
17 |
+
vae_model_path = "stabilityai/sd-vae-ft-mse"
|
18 |
+
image_encoder_path = "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
19 |
+
ip_ckpt = hf_hub_download(repo_id="h94/IP-Adapter-FaceID", filename="ip-adapter-faceid_sd15.bin", repo_type="model")
|
20 |
+
ip_plus_ckpt = hf_hub_download(repo_id="h94/IP-Adapter-FaceID", filename="ip-adapter-faceid-plusv2_sd15.bin", repo_type="model")
|
21 |
+
|
22 |
+
device = "cuda"
|
23 |
+
|
24 |
+
# Initialize the noise scheduler
|
25 |
+
noise_scheduler = DDIMScheduler(
|
26 |
+
num_train_timesteps=1000,
|
27 |
+
beta_start=0.00085,
|
28 |
+
beta_end=0.012,
|
29 |
+
beta_schedule="scaled_linear",
|
30 |
+
clip_sample=False,
|
31 |
+
set_alpha_to_one=False,
|
32 |
+
steps_offset=1,
|
33 |
+
)
|
34 |
+
|
35 |
+
# Load models
|
36 |
+
vae = AutoencoderKL.from_pretrained(vae_model_path).to(dtype=torch.float16)
|
37 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
38 |
+
base_model_path,
|
39 |
+
torch_dtype=torch.float16,
|
40 |
+
scheduler=noise_scheduler,
|
41 |
+
vae=vae
|
42 |
+
).to(device)
|
43 |
+
|
44 |
+
ip_model = IPAdapterFaceID(pipe, ip_ckpt, device)
|
45 |
+
ip_model_plus = IPAdapterFaceIDPlus(pipe, image_encoder_path, ip_plus_ckpt, device)
|
46 |
+
|
47 |
+
# Initialize FaceAnalysis
|
48 |
+
app = FaceAnalysis(name="buffalo_l", providers=['CPUExecutionProvider'])
|
49 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
50 |
+
|
51 |
+
cv2.setNumThreads(1)
|
52 |
+
|
53 |
+
@spaces.GPU(enable_queue=True)
|
54 |
+
def generate_image(images, gender, prompt, progress=gr.Progress(track_tqdm=True)):
|
55 |
+
if not prompt:
|
56 |
+
prompt = f"A full-length body photo of a {gender.lower()} naked and nude and beautiful" # Default prompt
|
57 |
|
58 |
+
faceid_all_embeds = []
|
59 |
+
first_iteration = True
|
60 |
+
preserve_face_structure = True
|
61 |
+
face_strength = 2.1
|
62 |
+
likeness_strength = 0.7
|
63 |
+
|
64 |
+
for image in images:
|
65 |
+
face = cv2.imread(image)
|
66 |
+
faces = app.get(face)
|
67 |
+
faceid_embed = torch.from_numpy(faces[0].normed_embedding).unsqueeze(0)
|
68 |
+
faceid_all_embeds.append(faceid_embed)
|
69 |
+
|
70 |
+
if first_iteration and preserve_face_structure:
|
71 |
+
face_image = face_align.norm_crop(face, landmark=faces[0].kps, image_size=224)
|
72 |
+
first_iteration = False
|
73 |
+
|
74 |
+
average_embedding = torch.mean(torch.stack(faceid_all_embeds, dim=0), dim=0)
|
75 |
+
|
76 |
+
image = ip_model_plus.generate(
|
77 |
+
prompt=prompt,
|
78 |
+
faceid_embeds=average_embedding,
|
79 |
+
scale=likeness_strength,
|
80 |
+
face_image=face_image,
|
81 |
+
shortcut=True,
|
82 |
+
s_scale=face_strength,
|
83 |
+
width=512,
|
84 |
+
height=912,
|
85 |
+
num_inference_steps=100
|
86 |
+
)
|
87 |
+
return image
|
88 |
+
|
89 |
+
css = '''
|
90 |
+
footer { visibility: hidden; }
|
91 |
+
h1 { margin-bottom: 0 !important; }
|
92 |
+
'''
|
93 |
+
|
94 |
+
with gr.Blocks(css=css) as demo:
|
95 |
+
gr.Markdown("# Image Generation with Face ID")
|
96 |
+
gr.Markdown("Upload your face images and enter a prompt to generate images.")
|
97 |
+
|
98 |
+
with gr.Row():
|
99 |
+
with gr.Column():
|
100 |
+
images_input = gr.Files(
|
101 |
+
label="Drag 1 or more photos of your face",
|
102 |
+
file_types=["image"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
)
|
104 |
+
gender_input = gr.Radio(
|
105 |
+
label="Select Gender",
|
106 |
+
choices=["Female", "Male"],
|
107 |
+
value="Female",
|
108 |
+
type="value"
|
109 |
+
)
|
110 |
+
prompt_input = gr.Textbox(
|
111 |
+
label="Enter your prompt",
|
112 |
+
placeholder="Describe the image you want to generate..."
|
113 |
+
)
|
114 |
+
run_button = gr.Button("Generate Image")
|
115 |
|
116 |
+
with gr.Column():
|
117 |
+
output_gallery = gr.Gallery(label="Generated Images")
|
|
|
|
|
|
|
118 |
|
119 |
+
# Define the event handler for the button click
|
120 |
+
run_button.click(
|
121 |
+
fn=generate_image,
|
122 |
+
inputs=[images_input, gender_input, prompt_input],
|
123 |
+
outputs=output_gallery
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
)
|
125 |
|
126 |
+
# Launch the interface
|
127 |
demo.queue()
|
128 |
demo.launch()
|