File size: 16,103 Bytes
712801c
64016ec
52fe588
64016ec
 
 
 
52fe588
9819163
52fe588
0cf15c3
044ef1c
bbb89b4
64016ec
 
 
52fe588
64016ec
 
52fe588
712801c
64016ec
712801c
 
64016ec
712801c
 
 
 
64016ec
712801c
 
52fe588
8136fd1
 
 
 
 
 
 
 
 
712801c
 
359c460
712801c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359c460
712801c
 
 
8136fd1
712801c
7f0949a
712801c
359c460
64016ec
 
 
 
 
 
 
359c460
64016ec
 
 
 
 
 
359c460
64016ec
 
 
 
 
 
 
 
 
 
 
 
359c460
64016ec
 
 
 
359c460
64016ec
 
 
52fe588
712801c
 
 
64016ec
712801c
 
1aca16b
712801c
31f3d2a
 
af420c8
31f3d2a
 
 
 
 
64016ec
712801c
 
1aca16b
712801c
 
 
 
 
 
 
 
 
 
 
 
64016ec
7f00cf1
712801c
 
 
 
 
 
 
 
64016ec
 
07ec0a5
1aca16b
07ec0a5
1aca16b
9819163
044ef1c
07ec0a5
64016ec
07ec0a5
712801c
07ec0a5
712801c
 
af420c8
712801c
359c460
07ec0a5
1aca16b
359c460
07ec0a5
64016ec
07ec0a5
712801c
 
 
 
 
 
 
 
 
 
 
1aca16b
07ec0a5
 
1aca16b
9819163
64016ec
07ec0a5
 
64016ec
9819163
07ec0a5
bbb89b4
83ebc4c
 
949194b
83ebc4c
949194b
83ebc4c
 
 
 
 
 
7e009fb
949194b
 
83ebc4c
 
 
 
 
 
949194b
83ebc4c
949194b
83ebc4c
 
 
 
 
 
 
 
 
 
7e009fb
949194b
7e009fb
 
 
 
 
 
949194b
7e009fb
 
83ebc4c
949194b
83ebc4c
 
 
949194b
83ebc4c
 
 
 
 
 
 
 
 
949194b
83ebc4c
 
 
949194b
 
83ebc4c
 
 
 
 
 
949194b
 
83ebc4c
 
 
949194b
83ebc4c
 
 
949194b
 
83ebc4c
 
 
 
949194b
83ebc4c
 
 
 
 
 
949194b
83ebc4c
 
 
949194b
7e009fb
949194b
83ebc4c
 
949194b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8542ca
 
 
 
 
83ebc4c
 
 
 
 
7e009fb
 
83ebc4c
 
 
7e009fb
83ebc4c
 
 
 
 
 
 
 
 
7e009fb
83ebc4c
 
 
 
 
 
 
 
 
c8547ac
83ebc4c
 
 
 
949194b
83ebc4c
 
1aca16b
7e009fb
 
 
 
 
 
 
9819163
 
52fe588
 
9819163
 
 
 
 
712801c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# -*- coding: utf-8 -*-
import os
import random
import logging
import numpy as np
import gradio as gr
import spaces
import torch
from huggingface_hub import login, whoami


HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN")

DEFAULT_PIPELINE_PATH = "black-forest-labs/FLUX.1-dev"
DEFAULT_QWEN_MODEL_PATH = "Qwen/Qwen3-8B"
DEFAULT_CUSTOM_WEIGHTS_PATH = "PosterCraft/PosterCraft-v1_RL"

MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 2048

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

auth_status = "πŸ”΄ Not Authenticated"
if HF_TOKEN:
    try:
        login(token=HF_TOKEN, add_to_git_credential=True)
        user_info = whoami(HF_TOKEN)
        auth_status = f"βœ… Authenticated as {user_info['name']}"
        logging.info(f"Successfully authenticated with Hugging Face as {user_info['name']}")
    except Exception as e:
        logging.error(f"HF authentication failed: {e}")
        auth_status = f"πŸ”΄ Authentication Error: {str(e)}"


def is_gpu_available():
    try:
        import torch
        return torch.cuda.is_available()
    except ImportError:
        return False

if is_gpu_available():
    from diffusers import FluxPipeline, FluxTransformer2DModel
    from transformers import AutoModelForCausalLM, AutoTokenizer
    
    print("⏱️  [GPU init] Loading FLUX pipeline...")
    FLUX_PIPELINE = FluxPipeline.from_pretrained(
        DEFAULT_PIPELINE_PATH,
        torch_dtype=torch.bfloat16,
        token=HF_TOKEN
    ).to("cuda")

    print("⏱️  [GPU init] Loading PosterCraft transformer...")
    POSTERCRAFT_TRANSFORMER = FluxTransformer2DModel.from_pretrained(
        DEFAULT_CUSTOM_WEIGHTS_PATH,
        torch_dtype=torch.bfloat16,
        token=HF_TOKEN
    ).to("cuda")
    FLUX_PIPELINE.transformer = POSTERCRAFT_TRANSFORMER

    print("⏱️  [GPU init] Loading Qwen model...")
    QWEN_TOKENIZER = AutoTokenizer.from_pretrained(
        DEFAULT_QWEN_MODEL_PATH, 
        token=HF_TOKEN, 
        trust_remote_code=True,
        use_fast=True
    )
    QWEN_MODEL = AutoModelForCausalLM.from_pretrained(
        DEFAULT_QWEN_MODEL_PATH,
        torch_dtype=torch.bfloat16,
        device_map="auto",
        token=HF_TOKEN,
        trust_remote_code=True,
    )
    
    print("βœ… [GPU init] All models loaded successfully!")

def enhance_prompt_with_qwen(original_prompt):
    if not is_gpu_available():
        return original_prompt
        
    prompt_template = """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:

**Step 1: Analyze the Core Requirements**
Identify the key elements in the user's prompt. Do not miss any details.
- **Subject:** What is the main subject? (e.g., a person, an object, a scene)
- **Style:** What is the visual style? (e.g., photorealistic, cartoon, vintage, minimalist)
- **Text:** Is there any text, like a title or slogan?
- **Color Palette:** Are there specific colors mentioned?
- **Composition:** Are there any layout instructions?

**Step 2: Expand and Add Detail**
Elaborate on each core requirement to create a rich description.
- **Do Not Omit:** You must include every piece of information from the original prompt.
- **Enrich with Specifics:** Add professional and descriptive details.
    - **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."
- **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."

**Step 3: Handle Text Precisely**
- **Identify All Text Elements:** Carefully look for any text mentioned in the prompt. This includes:
    - **Explicit Text:** Subtitles, slogans, or any text in quotes.
    - **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".
- **Rules for Text:**
    - **If Text Exists:**
        - You must use the exact text identified from the prompt.
        - Do NOT add new text or delete existing text.
        - 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.`
    - **If No Text Exists:**
        - Do not add any text elements. The poster must be purely visual.
- 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.

**Step 4: Final Output Rules**
- **Output ONLY the rewritten prompt.** No introductions, no explanations, no "Here is the prompt:".
- **Use a descriptive and confident tone.** Write as if you are describing a finished, beautiful poster.
- **Keep it concise.** The final prompt should be under 300 words.

---
**User Prompt:**
{brief_description}"""

    try:
        full_prompt = prompt_template.format(brief_description=original_prompt)
        messages = [{"role": "user", "content": full_prompt}]
        
        text = QWEN_TOKENIZER.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
        model_inputs = QWEN_TOKENIZER([text], return_tensors="pt").to(QWEN_MODEL.device)
        
        with torch.no_grad():
            generated_ids = QWEN_MODEL.generate(
                **model_inputs,
                max_new_tokens=512,          
                temperature=0.6,
                top_p=0.9,
                do_sample=True,
                eos_token_id=QWEN_TOKENIZER.eos_token_id,
            )
        
        output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
        full_response = QWEN_TOKENIZER.decode(output_ids, skip_special_tokens=True)
        
        if "</think>" in full_response:
            final_answer = full_response.split("</think>")[-1].strip()
        elif "<think>" not in full_response:
            final_answer = full_response.strip()
        else:
            final_answer = original_prompt
            
        return final_answer if final_answer else original_prompt
        
    except Exception as e:
        logging.error(f"Qwen enhancement failed: {e}")
        return original_prompt

@spaces.GPU(duration=30)
def generate_poster(
    original_prompt, 
    enable_recap, 
    height, 
    width, 
    num_inference_steps, 
    guidance_scale, 
    seed_input,
    progress=gr.Progress(track_tqdm=True),
):
    """Generate poster using preloaded models"""
    if not original_prompt or not original_prompt.strip():
        return None, "❌ Prompt cannot be empty!", ""

    try:
        if not HF_TOKEN:
            return None, "❌ Error: HF_TOKEN not found, please configure authentication.", ""

        progress(0.1, desc="Starting generation...")

        # Determine final prompt
        final_prompt = original_prompt
        if enable_recap:
            progress(0.2, desc="Re-writing prompt...")
            final_prompt = enhance_prompt_with_qwen(original_prompt)
        
        # Determine seed
        actual_seed = int(seed_input) if seed_input and seed_input != -1 else random.randint(1, 2**32 - 1)
        
        progress(0.3, desc="Generating image...")
        
        # Use preloaded FLUX pipeline to generate image
        generator = torch.Generator("cuda").manual_seed(actual_seed)
        
        with torch.inference_mode():
            image = FLUX_PIPELINE(
                prompt=final_prompt,
                generator=generator,
                num_inference_steps=int(num_inference_steps),
                guidance_scale=float(guidance_scale),
                width=int(width),
                height=int(height)
            ).images[0]
        
        progress(1.0, desc="Complete!")
        status_log = f"βœ… Generation complete! Seed: {actual_seed}"
        return image, status_log, final_prompt

    except Exception as e:
        logging.error(f"Generation failed: {e}")
        return None, f"❌ Generation failed: {str(e)}", ""

def create_interface():
    """Create Gradio interface"""
    
    custom_css = """
.gradio-container {
    background: linear-gradient(135deg, #3b4371 0%, #2d1b69 25%, #673ab7 50%, #8e24aa 75%, #6a1b9a 100%);
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    min-height: 100vh;
}

.contain {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 15px;
    padding: 25px;
    margin: 15px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(10px);
}

.title-container {
    text-align: center;
    margin-bottom: 25px;
    padding: 20px;
    background: linear-gradient(135deg, #673ab7, #8e24aa);
    border-radius: 12px;
    box-shadow: 0 5px 20px rgba(103, 58, 183, 0.4);
}

.title-container h1 {
    color: white;
    font-size: 2.2em;
    font-weight: bold;
    margin: 0;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
}

.info-bar {
    background: linear-gradient(135deg, #7c4dff, #6a1b9a);
    padding: 12px;
    border-radius: 8px;
    margin-bottom: 20px;
    color: white;
    text-align: center;
    font-weight: 500;
    box-shadow: 0 3px 12px rgba(124, 77, 255, 0.3);
}

.section-header {
    background: linear-gradient(135deg, #e1bee7, #d1c4e9);
    padding: 12px;
    border-radius: 8px;
    margin-bottom: 15px;
    border-left: 4px solid #673ab7;
}

.section-header h3 {
    margin: 0;
    color: #333;
    font-weight: 600;
}

.input-group {
    background: rgba(255, 255, 255, 0.85);
    padding: 18px;
    border-radius: 12px;
    margin-bottom: 15px;
    border: 1px solid rgba(103, 58, 183, 0.2);
    box-shadow: 0 3px 12px rgba(103, 58, 183, 0.1);
}

.result-section {
    background: rgba(255, 255, 255, 0.9);
    padding: 18px;
    border-radius: 12px;
    border: 1px solid rgba(103, 58, 183, 0.2);
    box-shadow: 0 3px 12px rgba(103, 58, 183, 0.1);
}

.tip-box {
    background: linear-gradient(135deg, #f3e5f5, #e8eaf6);
    padding: 10px;
    border-radius: 6px;
    margin: 8px 0;
    border-left: 3px solid #673ab7;
    color: #4a148c;
    font-weight: 500;
}

button.primary {
    background: linear-gradient(135deg, #673ab7, #8e24aa) !important;
    border: none !important;
    border-radius: 20px !important;
    padding: 12px 25px !important;
    color: white !important;
    font-weight: bold !important;
    font-size: 15px !important;
    box-shadow: 0 5px 15px rgba(103, 58, 183, 0.4) !important;
}

button.primary:hover {
    box-shadow: 0 8px 25px rgba(103, 58, 183, 0.6) !important;
    opacity: 0.9 !important;
    transform: translateY(-2px) !important;
}


label {
    color: #4a148c !important;
    font-weight: 600 !important;
}

input, textarea, select {
    border: 1px solid rgba(103, 58, 183, 0.3) !important;
    border-radius: 6px !important;
}

input:focus, textarea:focus, select:focus {
    border-color: #673ab7 !important;
    box-shadow: 0 0 0 2px rgba(103, 58, 183, 0.2) !important;
}

.gr-slider input[type="range"] {
    accent-color: #673ab7 !important;
}

input[type="checkbox"] {
    accent-color: #673ab7 !important;
}

.preserve-aspect-ratio img {
    object-fit: contain !important;
    width: auto !important;
    max-height: 512px !important;
}
"""
    
    with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
        with gr.Column(elem_classes="contain"):
            gr.HTML('<div class="title-container"><h1>🎨 PosterCraft-v1.0</h1></div>')

            with gr.Row():
                with gr.Column(scale=1, elem_classes="input-group"):
                    gr.HTML('<div class="section-header"><h3>βš™οΈ 1. Configuration</h3></div>')
                    prompt_input = gr.Textbox(label="πŸ’‘ Prompt", lines=3, placeholder="Enter your creative prompt...")
                    enable_recap_checkbox = gr.Checkbox(label="πŸ”„ Enable Prompt Recap", value=True, info=f"Uses Qwen3 for rewriting.")
                    gr.Examples(
                        examples=[
                            ["Urban Canvas Street Art Expo poster with bold graffiti-style lettering and dynamic colorful splashes"],
                            ["This poster for 'PixelPlay Retro Game Console' features the console with classic 8-bit game graphics, evoking nostalgia and fun with a vibrant, playful, and retro-gaming aesthetic."],
                            ["Poster about Mars Tourism Campaign, text:\"NEXT STOP MARS\\nBOOK YOUR TICKET NOW\", astronaut_on_red_planet, rocket_launch, sunrise_horizon_glow, retro_futurism_style, dust_clouds, panoramic_view, bold_headline_text, sci-fi_palette, highres, 16x9_ratio"],
                            ["This intriguing poster for \"CODE OF THE SAMURAI\" presents a stark contrast. On one side, a traditional samurai warrior in full armor, holding a katana, is depicted in a sepia-toned, historical style. On the other side, a futuristic cyborg warrior with glowing blue optics and sleek armor is shown in a cool, modern, digital style. The two figures are back-to-back, divided by a shimmering energy line. The title \"CODE OF THE SAMURAI\" is written in a font that blends traditional Japanese calligraphy with modern digital elements, in a metallic silver, positioned horizontally across the center where the two styles meet. The tagline, \"HONOR IS TIMELESS,\" is in a smaller, clean white sans-serif font at the bottom. The layout highlights the duality and the clash or merging of ancient traditions with future technology."]
                        ],
                        inputs=[prompt_input],
                        label="πŸ“ Example Prompts",
                        examples_per_page=5
                    )
                    
                    with gr.Row():
                        width_input = gr.Slider(label="πŸ“ Width", minimum=256, maximum=2048, value=832, step=64)
                        height_input = gr.Slider(label="πŸ“ Height", minimum=256, maximum=2048, value=1216, step=64)
                    gr.HTML('<div class="tip-box">πŸ’‘ Tip: Recommended size is 832x1216 for best results.</div>')
                    
                    num_inference_steps_input = gr.Slider(label="πŸ”„ Inference Steps", minimum=1, maximum=100, value=28, step=1)
                    guidance_scale_input = gr.Slider(label="🎯 Guidance Scale (CFG)", minimum=0.0, maximum=20.0, value=3.5, step=0.1)
                    seed_number_input = gr.Number(label="🎲 Seed", value=-1, minimum=-1, step=1, info="Leave blank or set to -1 for a random seed.")
                    generate_button = gr.Button("πŸš€ Generate Image", variant="primary")

                with gr.Column(scale=1, elem_classes="result-section"):
                    gr.HTML('<div class="section-header"><h3>🎨 2. Results</h3></div>')
                    image_output = gr.Image(label="πŸ–ΌοΈ Generated Image", type="pil", show_download_button=True, height=512, container=False, elem_classes="preserve-aspect-ratio")
                    recapped_prompt_output = gr.Textbox(label="πŸ“ Final Prompt Used", lines=5, interactive=False)
                    status_output = gr.Textbox(label="πŸ“Š Status Log", lines=4, interactive=False)

            inputs_list = [
                prompt_input, enable_recap_checkbox, height_input, width_input,
                num_inference_steps_input, guidance_scale_input, seed_number_input
            ]
            outputs_list = [image_output, recapped_prompt_output, status_output]
            
            generate_button.click(fn=generate_poster, inputs=inputs_list, outputs=outputs_list)
        
    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_api=False
    )