GabrielSalem commited on
Commit
f0e13d9
Β·
verified Β·
1 Parent(s): 56360b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -224
app.py CHANGED
@@ -1,236 +1,128 @@
1
- import random
 
 
 
 
 
 
 
 
 
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
- def load_generated_images():
49
- if not os.path.exists(SAVE_DIR):
50
- return []
51
-
52
- # Load all images from the directory
53
- image_files = [os.path.join(SAVE_DIR, f) for f in os.listdir(SAVE_DIR)
54
- if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))]
55
- # Sort by creation time (newest first)
56
- image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
57
- return image_files
58
-
59
- def load_predefined_images():
60
- # Return empty list since we're not using predefined images
61
- return []
62
-
63
- @spaces.GPU(duration=120)
64
- def inference(
65
- prompt: str,
66
- seed: int,
67
- randomize_seed: bool,
68
- width: int,
69
- height: int,
70
- guidance_scale: float,
71
- num_inference_steps: int,
72
- lora_scale: float,
73
- progress: gr.Progress = gr.Progress(track_tqdm=True),
74
- ):
75
- if randomize_seed:
76
- seed = random.randint(0, MAX_SEED)
77
- generator = torch.Generator(device=device).manual_seed(seed)
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- image = pipeline(
80
- prompt=prompt,
81
- guidance_scale=guidance_scale,
82
- num_inference_steps=num_inference_steps,
83
- width=width,
84
- height=height,
85
- generator=generator,
86
- joint_attention_kwargs={"scale": lora_scale},
87
- ).images[0]
88
-
89
- # Save the generated image
90
- filepath = save_generated_image(image, prompt)
91
-
92
- # Return the image, seed, and updated gallery
93
- return image, seed, load_generated_images()
94
-
95
- examples = [
96
- "A haunting cathedral ruins bathed in ethereal moonlight, with ancient stone archways stretching toward a starlit sky. The title 'WHISPERS OF ETERNITY' appears in weathered silver lettering that seems to float between the pillars. Ghostly wisps of fog curl around crumbling gothic sculptures, while 'By Alexander Blackwood' is inscribed in elegant script that glows with a subtle blue luminescence. Delicate patterns of celestial symbols and arcane runes border the edges. [trigger]",
97
-
98
- "A massive ancient tree with crystalline leaves dominates the composition, its translucent branches reaching across a sunset sky streaked with impossible colors. 'THE LUMINOUS Crown' is written in intricate golden calligraphy that intertwines with the branches. Mysterious glowing orbs float among the leaves, casting prismatic light. 'By Isabella Moonshadow' appears to be carved into the tree's bark. Sacred geometry patterns shimmer in the background. [trigger]",
99
-
100
- "A dramatic spiral staircase made of weathered copper and stained glass descends into swirling cosmic depths. The title 'CHRONICLES OF THE INFINITE' spans the spiral in bold art deco typography that seems to be crafted from constellations. Nebulae and galaxies swirl in the background, while 'By Marcus Starweaver' appears to be formed from falling stardust. Complex mechanical clockwork elements frame the corners. [trigger]",
101
-
102
- "An intricate doorway carved from ancient jade stands solitary in a field of shimmering black sand. 'GATES OF THE IMMORTAL' is emblazoned across the top in powerful metallic letters that seem to be forged from liquid mercury. Ethereal phoenix feathers drift across the scene, leaving trails of golden light. 'By Victoria Jade' flows along the bottom in brushstrokes that resemble living smoke. Sacred Chinese characters appear to float in the background. [trigger]",
103
-
104
- "A magnificent underwater city of pearl and coral rises from abyssal depths, illuminated by bioluminescent sea life. 'DEPTHS OF WONDER' ripples across the scene in iridescent letters that appear to be formed from living water. Schools of ethereal fish create flowing patterns of light, while 'By Neptune Rivers' shimmers like mother-of-pearl below. Ancient Atlantean symbols pulse with a subtle aqua glow around the borders. [trigger]",
105
-
106
- "A colossal steampunk clocktower pierces through storm clouds, its gears and mechanisms visible through crystalline walls. 'TIMEKEEPER'S LEGACY' is constructed from intricate brass and copper mechanisms that appear to be in constant motion. Lightning arcs between copper spires, while 'By Theodore Cogsworth' is etched in burnished bronze below. Mathematical equations and alchemical symbols float in the turbulent sky. [trigger]"
107
- ]
108
-
109
- css = """
110
- footer {
111
- visibility: hidden;
112
- }
113
- """
114
-
115
- with gr.Blocks(theme=gr.themes.Soft(), css=css, analytics_enabled=False) as demo:
116
- gr.HTML('<div class="title"> eBOOK Cover generation </div>')
117
-
118
- gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fginigen-Book-Cover.hf.space">
119
- <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fginigen-Book-Cover.hf.space&countColor=%23263759" />
120
- </a>""")
121
-
122
- with gr.Tabs() as tabs:
123
- with gr.Tab("Generation"):
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
- refresh_btn = gr.Button("πŸ”„ Refresh Gallery")
208
-
209
- # Event handlers
210
- def refresh_gallery():
211
- return load_generated_images()
 
 
 
 
 
 
212
 
213
- refresh_btn.click(
214
- fn=refresh_gallery,
215
- inputs=None,
216
- outputs=generated_gallery,
217
- )
218
 
219
- gr.on(
220
- triggers=[run_button.click, prompt.submit],
221
- fn=inference,
222
- inputs=[
223
- prompt,
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()