File size: 11,396 Bytes
80b58c8
 
 
 
 
 
 
 
c97fe2c
80b58c8
 
 
 
c97fe2c
 
 
 
 
80b58c8
c97fe2c
 
 
 
 
 
 
 
 
 
 
 
 
 
80b58c8
 
 
0e3999b
 
 
c97fe2c
 
0e3999b
c97fe2c
80b58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e3999b
80b58c8
 
 
 
0e3999b
80b58c8
 
 
 
0e3999b
80b58c8
 
 
 
 
 
0e3999b
80b58c8
 
 
 
0e3999b
80b58c8
 
 
 
0e3999b
80b58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e3999b
 
 
 
 
 
 
 
 
 
80b58c8
0e3999b
80b58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e3999b
80b58c8
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
"""

Byte Dream - Gradio Web Interface

Interactive web UI for image generation

"""

import gradio as gr
from bytedream.generator import ByteDreamGenerator
import torch
import os


# Initialize generator
print("Loading Byte Dream model...")

# Check if we should load from Hugging Face
HF_REPO_ID = os.getenv("HF_REPO_ID", None)
MODEL_PATH = os.getenv("MODEL_PATH", "./models/bytedream")

try:
    if HF_REPO_ID:
        print(f"Loading model from Hugging Face: {HF_REPO_ID}...")
        generator = ByteDreamGenerator(
            hf_repo_id=HF_REPO_ID,
            config_path="config.yaml",
            device="cpu",
        )
    else:
        print(f"Loading model from local path: {MODEL_PATH}...")
        generator = ByteDreamGenerator(
            model_path=MODEL_PATH,
            config_path="config.yaml",
            device="cpu",
        )
    print("βœ“ Model loaded successfully!")
except Exception as e:
    print(f"⚠ Warning: Could not load model: {e}")
    print("  Please train the model first using: python train.py")
    print("  Or download pretrained weights from Hugging Face.")
    print("")
    print("  To use a model from Hugging Face, set environment variable:")
    print("    HF_REPO_ID=username/repo_name")
    print("")
    print("Starting in demo mode...")
    generator = None


def generate_image(

    prompt,

    negative_prompt,

    width,

    height,

    num_steps,

    guidance_scale,

    seed,

):
    """Generate image from prompt"""
    
    if generator is None:
        return None, "Error: Model not loaded. Please train or download model weights."
    
    # Convert seed to None if -1
    seed_value = None if seed == -1 else seed
    
    try:
        # Generate image
        image = generator.generate(
            prompt=prompt,
            negative_prompt=negative_prompt if negative_prompt else None,
            width=int(width),
            height=int(height),
            num_inference_steps=int(num_steps),
            guidance_scale=float(guidance_scale),
            seed=seed_value,
        )
        
        return image, "Success! βœ“"
    
    except Exception as e:
        print(f"Error generating image: {e}")
        import traceback
        traceback.print_exc()
        return None, f"Error: {str(e)}"


# Create Gradio interface
with gr.Blocks(
    title="Byte Dream - AI Image Generator",
    css="""

    .gradio-container {

        max-width: 1400px !important;

    }

    #main-heading {

        text-align: center;

        margin-bottom: 20px;

    }

    .description {

        text-align: center;

        margin-bottom: 30px;

    }

    """
) as demo:
    
    gr.Markdown("""

    # 🎨 Byte Dream - AI Image Generator

    

    ### Transform your imagination into reality with advanced AI

    

    Powered by state-of-the-art latent diffusion models, optimized for CPU inference.

    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### πŸ“ Create Your Prompt")
            
            prompt_input = gr.Textbox(
                label="Positive Prompt",
                placeholder="Describe the image you want to create...",
                lines=3,
                value="A beautiful sunset over mountains, digital art, highly detailed, vibrant colors",
            )
            
            negative_prompt_input = gr.Textbox(
                label="Negative Prompt (Optional)",
                placeholder="What to avoid in the image...",
                lines=2,
                value="ugly, blurry, low quality, distorted, deformed",
            )
            
            gr.Markdown("### βš™οΈ Settings")
            
            with gr.Row():
                width_slider = gr.Slider(
                    minimum=256,
                    maximum=1024,
                    step=64,
                    value=512,
                    label="Width (px)",
                    info="Image width - multiples of 64"
                )
                height_slider = gr.Slider(
                    minimum=256,
                    maximum=1024,
                    step=64,
                    value=512,
                    label="Height (px)",
                    info="Image height - multiples of 64"
                )
            
            with gr.Row():
                steps_slider = gr.Slider(
                    minimum=10,
                    maximum=150,
                    step=5,
                    value=50,
                    label="Inference Steps",
                    info="More steps = better quality but slower"
                )
                guidance_slider = gr.Slider(
                    minimum=1.0,
                    maximum=20.0,
                    step=0.5,
                    value=7.5,
                    label="Guidance Scale",
                    info="Higher = closer to prompt, Lower = more creative"
                )
            
            seed_input = gr.Number(
                label="Seed",
                value=-1,
                precision=0,
                info="-1 for random, any number for reproducibility",
            )
            
            generate_btn = gr.Button(
                "🎨 Generate Image",
                variant="primary",
                size="lg",
            )
        
        with gr.Column(scale=1):
            gr.Markdown("### πŸ–ΌοΈ Result")
            
            output_image = gr.Image(
                label="Generated Image",
                type="pil",
                height=512,
            )
            status_text = gr.Textbox(
                label="Status",
                interactive=False,
            )
            
            download_btn = gr.File(
                label="Download",
                visible=True,
            )
    
    # Tips section
    with gr.Accordion("πŸ’‘ Tips for Better Results", open=False):
        gr.Markdown("""

        **Writing Effective Prompts:**

        - Be specific and descriptive

        - Include art style references (e.g., "digital art", "oil painting", "watercolor")

        - Mention lighting ("dramatic lighting", "soft sunlight", "neon lights")

        - Add quality modifiers ("highly detailed", "4K", "masterpiece")

        - Specify mood and atmosphere ("peaceful", "dramatic", "mysterious")

        

        **Using Negative Prompts:**

        - Remove unwanted elements ("no people", "no text")

        - Avoid quality issues ("no blur", "no distortion")

        - Fix common problems ("bad anatomy", "extra limbs")

        

        **Parameter Guide:**

        - **Steps**: 20-30 for quick previews, 50-75 for final images, 100+ for best quality

        - **Guidance**: 5-7 for creative freedom, 7-9 for balanced, 9-12 for strict prompt following

        - **Resolution**: Higher = more detail but slower. Start with 512x512, increase if needed

        """)
    
    # Examples section
    gr.Markdown("### πŸ’‘ Example Prompts")
    
    with gr.Row():
        example_btn1 = gr.Button(
            "πŸŒ† Cyberpunk City",
            size="sm",
            elem_id="example_btn1",
        )
        example_btn2 = gr.Button(
            "πŸ‰ Fantasy Dragon",
            size="sm",
            elem_id="example_btn2",
        )
        example_btn3 = gr.Button(
            "πŸ”οΈ Peaceful Landscape",
            size="sm",
            elem_id="example_btn3",
        )
    
    with gr.Row():
        example_btn4 = gr.Button(
            "πŸ‘€ Character Portrait",
            size="sm",
            elem_id="example_btn4",
        )
        example_btn5 = gr.Button(
            "🌊 Underwater Scene",
            size="sm",
            elem_id="example_btn5",
        )
        example_btn6 = gr.Button(
            "🎨 Abstract Art",
            size="sm",
            elem_id="example_btn6",
        )
    
    # Example prompt values
    example_prompts = {
        "example_btn1": (
            "A cyberpunk city at night with neon lights, futuristic architecture, flying cars, rain-slicked streets, highly detailed, digital art, cinematic lighting",
            "ugly, blurry, low quality, distorted, dark, gloomy"
        ),
        "example_btn2": (
            "A majestic dragon breathing fire, fantasy art, dramatic lighting, epic scene, scales gleaming, powerful wings, mountain landscape background",
            "ugly, deformed, blurry, low quality, cartoonish"
        ),
        "example_btn3": (
            "A peaceful cottage in a meadow, wildflowers, sunny day, blue sky, studio ghibli style, serene atmosphere, pastoral landscape",
            "people, animals, buildings, urban, dark, stormy"
        ),
        "example_btn4": (
            "Portrait of a warrior princess, ornate armor, fantasy setting, intricate details, character design, dramatic lighting, confident expression, long flowing hair",
            "ugly, deformed, asymmetrical, blurry, low quality, bad anatomy"
        ),
        "example_btn5": (
            "Underwater coral reef, tropical fish, sunlight filtering through water, photorealistic, vibrant colors, marine life, crystal clear water",
            "polluted, murky, dark, blurry, low quality"
        ),
        "example_btn6": (
            "Abstract geometric art, colorful shapes, dynamic composition, modern art, bold patterns, artistic expression, vivid colors",
            "representational, realistic, boring, dull colors, simple"
        ),
    }
    
    # Connect example buttons
    def set_example(prompt, negative):
        return prompt, negative, "Click Generate to create!"
    
    # Map button names to their variables
    button_map = {
        "example_btn1": example_btn1,
        "example_btn2": example_btn2,
        "example_btn3": example_btn3,
        "example_btn4": example_btn4,
        "example_btn5": example_btn5,
        "example_btn6": example_btn6,
    }
    
    for btn_name, (prompt, negative) in example_prompts.items():
        button_map[btn_name].click(
            fn=set_example,
            inputs=[gr.State(prompt), gr.State(negative)],
            outputs=[prompt_input, negative_prompt_input, status_text],
        )
    
    # Connect generate button
    generate_btn.click(
        fn=generate_image,
        inputs=[
            prompt_input,
            negative_prompt_input,
            width_slider,
            height_slider,
            steps_slider,
            guidance_slider,
            seed_input,
        ],
        outputs=[output_image, status_text],
    )
    
    # Footer
    gr.Markdown("""

    ---

    **Byte Dream** v1.0.0 | Powered by Latent Diffusion Models | Optimized for CPU Inference

    

    Created with ❀️ using PyTorch and Hugging Face Diffusers

    """)


if __name__ == "__main__":
    print("\n" + "="*60)
    print("Starting Byte Dream Web Interface")
    print("="*60)
    print("\nOpening browser...")
    print("Press Ctrl+C to close\n")
    
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True,
        theme=gr.themes.Soft(),
    )