Ephemeral182 commited on
Commit
64016ec
·
verified ·
1 Parent(s): 28ee67d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +314 -132
app.py CHANGED
@@ -1,154 +1,336 @@
1
- import gradio as gr
2
- import numpy as np
3
  import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
 
7
  import torch
 
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
 
 
 
 
11
 
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
 
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
-
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
  )
 
 
 
 
 
 
 
 
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
 
 
 
81
 
82
- result = gr.Image(label="Result", show_label=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
 
 
 
 
 
 
 
 
90
  )
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
98
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
 
 
 
 
 
 
101
 
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
 
127
 
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
152
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
1
+ import os
 
2
  import random
3
+ import logging
4
+ import numpy as np
5
+ import gradio as gr
6
+ import spaces
7
  import torch
8
+ from diffusers import FluxPipeline, FluxTransformer2DModel
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
 
11
+ # ------------------------------------------------------------------
12
+ # 1. Global Configuration
13
+ # ------------------------------------------------------------------
14
+ DEFAULT_PIPELINE_PATH = "black-forest-labs/FLUX.1-dev"
15
+ DEFAULT_QWEN_MODEL_PATH = "Qwen/Qwen3-8B"
16
+ DEFAULT_CUSTOM_WEIGHTS_PATH = "PosterCraft/PosterCraft-v1_RL"
17
 
18
+ MAX_SEED = np.iinfo(np.int32).max
19
+ MAX_IMAGE_SIZE = 2048
 
 
20
 
21
+ # No need to manually set CUDA device on Spaces
22
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
+ torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
24
 
25
+ logging.basicConfig(
26
+ level=logging.INFO,
27
+ format="%(asctime)s - %(levelname)s - %(message)s",
28
+ )
29
+
30
+ # ------------------------------------------------------------------
31
+ # 2. Model Download Function (Referencing JarvisIR's approach)
32
+ # ------------------------------------------------------------------
33
+ def download_model_weights(target_dir, repo_id, subdir=None):
34
+ """
35
+ Download model weights to specified directory
36
+
37
+ Args:
38
+ target_dir (str): Local target directory
39
+ repo_id (str): HuggingFace repository ID
40
+ subdir (str): Subdirectory path in the repository (optional)
41
+ """
42
+ from huggingface_hub import snapshot_download
43
+ import shutil
44
+
45
+ if os.path.exists(target_dir):
46
+ logging.info(f"Directory {target_dir} already exists, skipping download")
47
+ return
48
+
49
+ tmp_dir = "hf_temp_download"
50
+ os.makedirs(tmp_dir, exist_ok=True)
51
+
52
+ try:
53
+ if subdir:
54
+ # If subdirectory is specified, only download that subdirectory
55
+ snapshot_download(
56
+ repo_id=repo_id,
57
+ repo_type="model",
58
+ local_dir=tmp_dir,
59
+ allow_patterns=os.path.join(subdir, "**"),
60
+ local_dir_use_symlinks=False,
61
+ )
62
+ src_dir = os.path.join(tmp_dir, subdir)
63
+ else:
64
+ # Download entire repository
65
+ snapshot_download(
66
+ repo_id=repo_id,
67
+ repo_type="model",
68
+ local_dir=tmp_dir,
69
+ local_dir_use_symlinks=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  )
71
+ src_dir = tmp_dir
72
+
73
+ # Copy to target directory
74
+ if os.path.exists(src_dir):
75
+ shutil.copytree(src_dir, target_dir)
76
+ logging.info(f"Successfully downloaded {repo_id} to {target_dir}")
77
+ else:
78
+ logging.warning(f"Source directory {src_dir} does not exist")
79
 
80
+ except Exception as e:
81
+ logging.error(f"Download failed: {e}")
82
+ finally:
83
+ # Clean up temporary directory
84
+ if os.path.exists(tmp_dir):
85
+ shutil.rmtree(tmp_dir)
86
 
87
+ # ------------------------------------------------------------------
88
+ # 3. Qwen Prompt Rewriting Agent
89
+ # ------------------------------------------------------------------
90
+ class QwenRecapAgent:
91
+ def __init__(self, model_path: str):
92
+ self.model_path = model_path
93
+ self.tokenizer = None
94
+ self.model = None
95
+ self.is_loaded = False
96
+
97
+ self.prompt_template = (
98
+ """You are an expert poster prompt designer. Your task is to rewrite a user's short poster prompt into a detailed and vivid long-format prompt. Follow these steps carefully:
99
+ **Step 1: Analyze the Core Requirements**
100
+ Identify the key elements in the user's prompt. Do not miss any details.
101
+ - **Subject:** What is the main subject? (e.g., a person, an object, a scene)
102
+ - **Style:** What is the visual style? (e.g., photorealistic, cartoon, vintage, minimalist)
103
+ - **Text:** Is there any text, like a title or slogan?
104
+ - **Color Palette:** Are there specific colors mentioned?
105
+ - **Composition:** Are there any layout instructions?
106
+ **Step 2: Expand and Add Detail**
107
+ Elaborate on each core requirement to create a rich description.
108
+ - **Do Not Omit:** You must include every piece of information from the original prompt.
109
+ - **Enrich with Specifics:** Add professional and descriptive details.
110
+ - **Example:** If the user says "a woman with a bow", you could describe her as "a young woman with a determined expression, holding a finely crafted wooden longbow, with an arrow nocked and ready to fire."
111
+ - **Fill in the Gaps:** If the original prompt is simple (e.g., "a poster for a coffee shop"), use your creativity to add fitting details. You might add "The poster features a top-down view of a steaming latte with delicate art on its foam, placed on a rustic wooden table next to a few scattered coffee beans."
112
+ **Step 3: Handle Text Precisely**
113
+ - **Identify All Text Elements:** Carefully look for any text mentioned in the prompt. This includes:
114
+ - **Explicit Text:** Subtitles, slogans, or any text in quotes.
115
+ - **Implicit Titles:** The name of an event, movie, or product is often the main title. For example, if the prompt is "generate a 'Inception' poster ...", the title is "Inception".
116
+ - **Rules for Text:**
117
+ - **If Text Exists:**
118
+ - You must use the exact text identified from the prompt.
119
+ - Do NOT add new text or delete existing text.
120
+ - Describe each text's appearance (font, style, color, position). Example: `The title 'Inception' is written in a bold, sans-serif font, integrated into the cityscape.`
121
+ - **If No Text Exists:**
122
+ - Do not add any text elements. The poster must be purely visual.
123
+ - Most posters have titles. When a title exists, you must extend the title's description. Only when you are absolutely sure that there is no text to render, you can allow the extended prompt not to render text.
124
+ **Step 4: Final Output Rules**
125
+ - **Output ONLY the rewritten prompt.** No introductions, no explanations, no "Here is the prompt:".
126
+ - **Use a descriptive and confident tone.** Write as if you are describing a finished, beautiful poster.
127
+ - **Keep it concise.** The final prompt should be under 300 words.
128
+ ---
129
+ **User Prompt:**
130
+ {brief_description}"""
131
+ )
132
 
133
+ def _load_model(self):
134
+ """Lazy load model"""
135
+ if not self.is_loaded:
136
+ logging.info(f"Loading Qwen model: {self.model_path}")
137
+
138
+ # Ensure model files exist, if not download from Hub
139
+ if not os.path.exists(self.model_path):
140
+ download_model_weights(self.model_path, DEFAULT_QWEN_MODEL_PATH)
141
+
142
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
143
+ self.model = AutoModelForCausalLM.from_pretrained(
144
+ self.model_path,
145
+ torch_dtype=torch_dtype,
146
+ device_map="auto"
147
  )
148
+ self.is_loaded = True
149
 
150
+ def recap(self, text: str) -> str:
151
+ try:
152
+ self._load_model()
153
+
154
+ messages = [
155
+ {"role": "user", "content": self.prompt_template.format(brief_description=text)}
156
+ ]
157
+ chat = self.tokenizer.apply_chat_template(
158
+ messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
159
  )
160
+ inputs = self.tokenizer([chat], return_tensors="pt").to(self.model.device)
161
+
162
+ with torch.no_grad():
163
+ ids = self.model.generate(
164
+ **inputs, max_new_tokens=1024, temperature=0.6, do_sample=True
165
+ )
166
+ out = self.tokenizer.decode(
167
+ ids[0][len(inputs.input_ids[0]):], skip_special_tokens=True
168
+ ).strip()
169
+
170
+ if "</think>" in out:
171
+ out = out.split("</think>")[-1].strip()
172
+ return out or text
173
+ except Exception as e:
174
+ logging.warning(f"Recap failed: {e}. Using original prompt.")
175
+ return text
176
 
177
+ # ------------------------------------------------------------------
178
+ # 4. Poster Generator
179
+ # ------------------------------------------------------------------
180
+ class PosterGenerator:
181
+ def __init__(self):
182
+ self.pipeline = None
183
+ self.qwen = None
184
+ self.is_loaded = False
185
 
186
+ def _load_models(self):
187
+ """Lazy load all models"""
188
+ if not self.is_loaded:
189
+ logging.info("Starting model loading...")
190
+
191
+ # Download custom weights (if not exists)
192
+ custom_weights_local = "local_weights/PosterCraft-v1_RL"
193
+ if not os.path.exists(custom_weights_local):
194
+ logging.info("Downloading custom Transformer weights...")
195
+ download_model_weights(custom_weights_local, DEFAULT_CUSTOM_WEIGHTS_PATH)
196
+
197
+ # Load FLUX pipeline
198
+ logging.info("Loading FLUX pipeline...")
199
+ self.pipeline = FluxPipeline.from_pretrained(
200
+ DEFAULT_PIPELINE_PATH,
201
+ torch_dtype=torch_dtype
202
+ )
203
+
204
+ # Load custom Transformer
205
+ if os.path.exists(custom_weights_local):
206
+ try:
207
+ logging.info("Loading custom Transformer...")
208
+ transformer = FluxTransformer2DModel.from_pretrained(
209
+ custom_weights_local,
210
+ torch_dtype=torch_dtype
211
+ )
212
+ self.pipeline.transformer = transformer
213
+ logging.info("Custom Transformer loaded successfully")
214
+ except Exception as e:
215
+ logging.warning(f"Custom weights loading failed: {e}, using default weights")
216
+
217
+ # Enable memory optimization
218
+ self.pipeline.enable_model_cpu_offload()
219
+
220
+ # Initialize Qwen (lazy loading)
221
+ qwen_local = "local_weights/Qwen3-8B"
222
+ if not os.path.exists(qwen_local):
223
+ logging.info("Downloading Qwen model...")
224
+ download_model_weights(qwen_local, DEFAULT_QWEN_MODEL_PATH)
225
+
226
+ self.qwen = QwenRecapAgent(qwen_local)
227
+
228
+ self.is_loaded = True
229
+ logging.info("All models loaded successfully")
230
 
231
+ def generate(self, prompt, enable_recap, **kwargs):
232
+ """Generate poster with given parameters"""
233
+ final_prompt = prompt
234
+ if enable_recap:
235
+ if not self.qwen:
236
+ raise gr.Error("Recap is enabled, but the recap model is not available. Check model path.")
237
+ final_prompt = self.qwen.recap(prompt)
238
+
239
+ generator = torch.Generator(device="cpu").manual_seed(kwargs['seed'])
240
+
241
+ with torch.inference_mode():
242
+ image = self.pipeline(
243
+ prompt=final_prompt,
244
+ generator=generator,
245
+ num_inference_steps=kwargs['num_inference_steps'],
246
+ guidance_scale=kwargs['guidance_scale'],
247
+ width=kwargs['width'],
248
+ height=kwargs['height']
249
+ ).images[0]
250
+
251
+ return image, final_prompt
252
 
253
+ # Global instance
254
+ poster_gen = PosterGenerator()
255
+
256
+ # ------------------------------------------------------------------
257
+ # 5. ZeroGPU Inference Function
258
+ # ------------------------------------------------------------------
259
+ @spaces.GPU(duration=120)
260
+ def generate_image_interface(
261
+ original_prompt, enable_recap, height, width,
262
+ num_inference_steps, guidance_scale, seed_input,
263
+ progress=gr.Progress(track_tqdm=True),
264
+ ):
265
+ if not original_prompt or not original_prompt.strip():
266
+ raise gr.Error("Prompt cannot be empty!")
267
+
268
+ if width > MAX_IMAGE_SIZE or height > MAX_IMAGE_SIZE:
269
+ raise gr.Error(f"Maximum resolution limit is {MAX_IMAGE_SIZE}×{MAX_IMAGE_SIZE}")
270
+
271
+ progress(0, desc="Loading models...")
272
+
273
+ try:
274
+ actual_seed = int(seed_input) if seed_input and seed_input > 0 else random.randint(1, 2**32 - 1)
275
+
276
+ # Ensure models are loaded
277
+ poster_gen._load_models()
278
+
279
+ image, final_prompt = poster_gen.generate(
280
+ prompt=original_prompt,
281
+ enable_recap=enable_recap,
282
+ height=int(height),
283
+ width=int(width),
284
+ num_inference_steps=int(num_inference_steps),
285
+ guidance_scale=float(guidance_scale),
286
+ seed=actual_seed
287
+ )
288
+
289
+ status_log = f"Seed: {actual_seed} | Generation complete."
290
+ progress(1, desc="Generation complete!")
291
+ return image, final_prompt, status_log
292
+
293
+ except Exception as e:
294
+ logging.error(f"Generation failed: {e}")
295
+ raise gr.Error(f"An error occurred: {e}")
296
+
297
+ # ------------------------------------------------------------------
298
+ # 6. Gradio Interface (Similar to demo format)
299
+ # ------------------------------------------------------------------
300
+ with gr.Blocks(theme=gr.themes.Soft(), title="PosterCraft") as demo:
301
+ gr.Markdown("# PosterCraft-v1.0")
302
+ gr.Markdown(f"Running on: **{device}** | Base Pipeline: **{DEFAULT_PIPELINE_PATH}**")
303
+ gr.Markdown("⚠️ **First use requires model download, please wait about 10-15 minutes**")
304
+
305
+ with gr.Row():
306
+ with gr.Column(scale=1):
307
+ gr.Markdown("### 1. Configuration")
308
+ prompt_input = gr.Textbox(label="Prompt", lines=3, placeholder="Enter your creative prompt...")
309
+ enable_recap_checkbox = gr.Checkbox(label="Enable Prompt Recap", value=True, info=f"Uses {DEFAULT_QWEN_MODEL_PATH} for rewriting.")
310
+
311
  with gr.Row():
312
+ width_input = gr.Slider(label="Width", minimum=256, maximum=2048, value=832, step=64)
313
+ height_input = gr.Slider(label="Height", minimum=256, maximum=2048, value=1216, step=64)
314
+ gr.Markdown("Tip: Recommended size is 832x1216 for best results.")
315
+
316
+ num_inference_steps_input = gr.Slider(label="Inference Steps", minimum=1, maximum=100, value=28, step=1)
317
+ guidance_scale_input = gr.Slider(label="Guidance Scale (CFG)", minimum=0.0, maximum=20.0, value=3.5, step=0.1)
318
+ seed_number_input = gr.Number(label="Seed", value=None, minimum=-1, step=1, info="Leave blank or set to -1 for a random seed.")
319
+ generate_button = gr.Button("Generate Image", variant="primary")
320
 
321
+ with gr.Column(scale=1):
322
+ gr.Markdown("### 2. Results")
323
+ image_output = gr.Image(label="Generated Image", type="pil", show_download_button=True, height=512)
324
+ recapped_prompt_output = gr.Textbox(label="Final Prompt Used", lines=5, interactive=False)
325
+ status_output = gr.Textbox(label="Status Log", lines=4, interactive=False)
 
 
326
 
327
+ inputs_list = [
328
+ prompt_input, enable_recap_checkbox, height_input, width_input,
329
+ num_inference_steps_input, guidance_scale_input, seed_number_input
330
+ ]
331
+ outputs_list = [image_output, recapped_prompt_output, status_output]
332
+
333
+ generate_button.click(fn=generate_image_interface, inputs=inputs_list, outputs=outputs_list)
 
 
 
 
 
 
 
 
 
334
 
335
  if __name__ == "__main__":
336
+ demo.launch()