File size: 1,202 Bytes
bd3f0ba
 
 
 
 
 
12b2da8
bd3f0ba
 
 
 
cb70fb6
bd3f0ba
 
 
 
 
 
 
 
 
12b2da8
bd3f0ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from diffusers import StableDiffusionXLPipeline


class StableDiffusionEngine:
    """
    Stable Diffusion XL Engine (HF Spaces safe version)
    """

    def __init__(
        self,
        model_id = "stabilityai/stable-diffusion-xl-base-1.0",
        hf_token: str | None = None,
    ):
        self.device = "cuda" if torch.cuda.is_available() else "cpu"

        self.pipe = StableDiffusionXLPipeline.from_pretrained(
            model_id,
            torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
            use_safetensors=True,
            safety_checker=True,
            token=hf_token,   # ✅ CRITICAL FIX
        )

        self.pipe.to(self.device)

    def generate_image(
        self,
        prompt: str,
        num_inference_steps: int = 30,
        guidance_scale: float = 7.5,
        width: int = 1024,
        height: int = 1024,
    ):
        with torch.no_grad():
            image = self.pipe(
                prompt=prompt,
                num_inference_steps=num_inference_steps,
                guidance_scale=guidance_scale,
                width=width,
                height=height,
            ).images[0]

        return image