File size: 6,897 Bytes
0b7c365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
from diffusers import HiDreamImagePipeline
from transformers import PreTrainedTokenizerFast, LlamaForCausalLM
import random
import spaces
import numpy as np

# Set data type
dtype = torch.bfloat16
device = "cpu"  # Initial device for model loading; inference will use GPU

# Load tokenizer and text encoder for Llama
try:
    tokenizer_4 = PreTrainedTokenizerFast.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
    text_encoder_4 = LlamaForCausalLM.from_pretrained(
        "meta-llama/Meta-Llama-3.1-8B-Instruct",
        output_hidden_states=True,
        output_attentions=True,
        torch_dtype=dtype,
    ).to(device)
except Exception as e:
    raise Exception(f"Failed to load Llama model: {e}. Ensure you have access to 'meta-llama/Meta-Llama-3.1-8B-Instruct' and are logged in via `huggingface-cli login`.")

# Load the HiDreamImagePipeline
try:
    pipe = HiDreamImagePipeline.from_pretrained(
        "HiDream-ai/HiDream-I1-Full",
        tokenizer_4=tokenizer_4,
        text_encoder_4=text_encoder_4,
        torch_dtype=dtype,
    ).to(device)
    pipe.enable_model_cpu_offload()  # Offload to CPU when not in use, critical for Spaces
except Exception as e:
    raise Exception(f"Failed to load HiDreamImagePipeline: {e}. Ensure you have access to 'HiDream-ai/HiDream-I1-Full'.")

# Define maximum values
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 2048

# Inference function with GPU access
@spaces.GPU()
def infer(prompt, negative_prompt="", seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=50, guidance_scale=5.0, progress=gr.Progress(track_tqdm=True)):
    # Ensure the model is on GPU for inference
    pipe.to("cuda")
    
    try:
        if randomize_seed:
            seed = random.randint(0, MAX_SEED)
        generator = torch.Generator("cuda").manual_seed(seed)
        
        # Generate the image
        image = pipe(
            prompt=prompt,
            negative_prompt=negative_prompt,
            height=height,
            width=width,
            num_inference_steps=num_inference_steps,
            guidance_scale=guidance_scale,
            generator=generator,
            output_type="pil",
        ).images[0]
        
        # Clear GPU memory
        torch.cuda.empty_cache()
        
        return image, seed
    finally:
        # Move model back to CPU to free GPU memory
        pipe.to("cpu")
        torch.cuda.empty_cache()

# Define examples
examples = [
    ["A cat holding a sign that says \"Hi-Dreams.ai\".", ""],
    ["A futuristic cityscape with flying cars.", "blurry, low quality"],
    ["A serene landscape with mountains and a lake.", ""],
]

# CSS styling
css = """
#col-container {
   margin: 0 auto;
   max-width: 960px;
}
.generate-btn {
   background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%) !important;
   border: none !important;
   color: white !important;
}
.generate-btn:hover {
   transform: translateY(-2px);
   box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
"""

# Create Gradio interface
with gr.Blocks(css=css) as app:
    gr.HTML("<center><h1>HiDreamImage Generator</h1></center>")
    with gr.Column(elem_id="col-container"):
        with gr.Row():
            with gr.Column():
                with gr.Row():
                    text_prompt = gr.Textbox(
                        label="Prompt",
                        placeholder="Enter a prompt here",
                        lines=3,
                        elem_id="prompt-text-input"
                    )
                with gr.Row():
                    with gr.Accordion("Advanced Settings", open=False):
                        with gr.Row():
                            width = gr.Slider(
                                label="Width",
                                value=1024,
                                minimum=64,
                                maximum=MAX_IMAGE_SIZE,
                                step=8
                            )
                            height = gr.Slider(
                                label="Height",
                                value=1024,
                                minimum=64,
                                maximum=MAX_IMAGE_SIZE,
                                step=8
                            )
                        with gr.Row():
                            steps = gr.Slider(
                                label="Inference Steps",
                                value=50,
                                minimum=1,
                                maximum=100,
                                step=1
                            )
                            cfg = gr.Slider(
                                label="Guidance Scale",
                                value=5.0,
                                minimum=1,
                                maximum=20,
                                step=0.5
                            )
                        with gr.Row():
                            seed = gr.Slider(
                                label="Seed",
                                value=42,
                                minimum=0,
                                maximum=MAX_SEED,
                                step=1
                            )
                            randomize_seed = gr.Checkbox(
                                label="Randomize Seed",
                                value=True
                            )
                        with gr.Row():
                            negative_prompt = gr.Textbox(
                                label="Negative Prompt",
                                placeholder="Enter what to avoid (optional)",
                                lines=2
                            )
                with gr.Row():
                    text_button = gr.Button(
                        "✨ Generate Image",
                        variant='primary',
                        elem_classes=["generate-btn"]
                    )
            with gr.Column():
                with gr.Row():
                    image_output = gr.Image(
                        type="pil",
                        label="Generated Image",
                        elem_id="gallery"
                    )
                seed_output = gr.Textbox(
                    label="Seed Used",
                    interactive=False
                )
        
        with gr.Column():
            gr.Examples(
                examples=examples,
                inputs=[text_prompt, negative_prompt],
            )
    
    # Connect the button and textbox submit to the inference function
    gr.on(
        triggers=[text_button.click, text_prompt.submit],
        fn=infer,
        inputs=[text_prompt, negative_prompt, seed, randomize_seed, width, height, steps, cfg],
        outputs=[image_output, seed_output]
    )

# Launch the app
app.launch(share=True)