File size: 1,744 Bytes
f9d8d84
75a470f
f9d8d84
 
 
75a470f
f9d8d84
 
75a470f
 
 
 
 
f9d8d84
 
75a470f
f9d8d84
 
75a470f
 
f9d8d84
 
75a470f
f9d8d84
 
 
 
 
 
75a470f
 
f9d8d84
 
 
 
75a470f
f9d8d84
 
 
75a470f
f9d8d84
 
 
 
 
 
 
 
 
 
 
75a470f
 
f9d8d84
 
 
 
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
import torch
from diffusers import DiffusionPipeline
import spaces

# Configuration
MODEL_ID = 'black-forest-labs/FLUX.1-dev'
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# Set dtype based on device for compatibility
dtype = torch.bfloat16 if DEVICE == "cuda" else torch.float32

# Load pipeline with appropriate dtype for device
pipe = DiffusionPipeline.from_pretrained(MODEL_ID, dtype=dtype)
pipe.to(DEVICE)

# AoT Compilation for faster inference (requires GPU)
@spaces.GPU(duration=1500)
def compile_transformer():
    with spaces.aoti_capture(pipe.transformer) as call:
        pipe("test prompt")
    
    exported = torch.export.export(
        pipe.transformer,
        args=call.args,
        kwargs=call.kwargs,
    )
    return spaces.aoti_compile(exported)

# Apply compiled model
compiled_transformer = compile_transformer()
spaces.aoti_apply(compiled_transformer, pipe.transformer)

@spaces.GPU
def generate_image(prompt, negative_prompt="", num_inference_steps=20, guidance_scale=7.5):
    """
    Generate an image from text prompt using FLUX.
    
    Args:
        prompt (str): The text prompt for image generation.
        negative_prompt (str): Negative prompt (not used in FLUX).
        num_inference_steps (int): Number of denoising steps.
        guidance_scale (float): Scale for classifier-free guidance.
    
    Returns:
        PIL.Image: Generated image.
    """
    try:
        result = pipe(
            prompt=prompt,
            num_inference_steps=int(num_inference_steps),
            guidance_scale=float(guidance_scale),
            height=1024,
            width=1024
        )
        return result.images[0]
    except Exception as e:
        raise gr.Error(f"Generation failed: {str(e)}")